Programs & Examples On #Zend decorators

How do I set the timeout for a JAX-WS webservice client?

ProxyWs proxy = (ProxyWs) factory.create();
Client client = ClientProxy.getClient(proxy);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);

This worked for me.

getContext is not a function

Alternatively you can use:

this.element=$(id)[0];

Creating/writing into a new file in Qt

#include <QFile>
#include <QCoreApplication>
#include <QTextStream>

int main(int argc, char *argv[])
{
    // Create a new file     
    QFile file("out.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out << "This file is generated by Qt\n";

    // optional, as QFile destructor will already do it:
    file.close(); 

    //this would normally start the event loop, but is not needed for this
    //minimal example:
    //return app.exec();

    return 0;
}

Create session factory in Hibernate 4

In earlier versions session factory was created as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be like:

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());

How do I find the size of a struct?

The exact value is sizeof(a).
You might also take a risk and assume that it is in this case no less than 2 and no greater than 16.

How to use ScrollView in Android?

As said above you can put it inside a ScrollView... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView... and if you want your component (or layout) to support both put inside both of them like this:

  <HorizontalScrollView>
        <ScrollView>
            <!-- SOME THING -->
        </ScrollView>
    </HorizontalScrollView>

and with setting the layout_width and layout_height ofcourse.

Breaking out of nested loops

If you're able to extract the loop code into a function, a return statement can be used to exit the outermost loop at any time.

def foo():
    for x in range(10):
        for y in range(10):
            print(x*y)
            if x*y > 50:
                return
foo()

If it's hard to extract that function you could use an inner function, as @bjd2385 suggests, e.g.

def your_outer_func():
    ...
    def inner_func():
        for x in range(10):
            for y in range(10):
                print(x*y)
                if x*y > 50:
                    return
    inner_func()
    ...

Rotating a two-dimensional array in Python

I've had this problem myself and I've found the great wikipedia page on the subject (in "Common rotations" paragraph:
https://en.wikipedia.org/wiki/Rotation_matrix#Ambiguities

Then I wrote the following code, super verbose in order to have a clear understanding of what is going on.

I hope that you'll find it useful to dig more in the very beautiful and clever one-liner you've posted.

To quickly test it you can copy / paste it here:
http://www.codeskulptor.org/

triangle = [[0,0],[5,0],[5,2]]
coordinates_a = triangle[0]
coordinates_b = triangle[1]
coordinates_c = triangle[2]

def rotate90ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1]
# Here we apply the matrix coming from Wikipedia
# for 90 ccw it looks like:
# 0,-1
# 1,0
# What does this mean?
#
# Basically this is how the calculation of the new_x and new_y is happening:
# new_x = (0)(old_x)+(-1)(old_y)
# new_y = (1)(old_x)+(0)(old_y)
#
# If you check the lonely numbers between parenthesis the Wikipedia matrix's numbers
# finally start making sense.
# All the rest is standard formula, the same behaviour will apply to other rotations, just
# remember to use the other rotation matrix values available on Wiki for 180ccw and 170ccw
    new_x = -old_y
    new_y = old_x
    print "End coordinates:"
    print [new_x, new_y]

def rotate180ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1] 
    new_x = -old_x
    new_y = -old_y
    print "End coordinates:"
    print [new_x, new_y]

def rotate270ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1]  
    new_x = -old_x
    new_y = -old_y
    print "End coordinates:"
    print [new_x, new_y]

print "Let's rotate point A 90 degrees ccw:"
rotate90ccw(coordinates_a)
print "Let's rotate point B 90 degrees ccw:"
rotate90ccw(coordinates_b)
print "Let's rotate point C 90 degrees ccw:"
rotate90ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 180 degrees ccw:"
rotate180ccw(coordinates_a)
print "Let's rotate point B 180 degrees ccw:"
rotate180ccw(coordinates_b)
print "Let's rotate point C 180 degrees ccw:"
rotate180ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 270 degrees ccw:"
rotate270ccw(coordinates_a)
print "Let's rotate point B 270 degrees ccw:"
rotate270ccw(coordinates_b)
print "Let's rotate point C 270 degrees ccw:"
rotate270ccw(coordinates_c)
print "=== === === === === === === === === "

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

The documentation says:

When you need to set attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead.

So, just change id, value assignment and you should be done.

How do I compute derivative using Numpy?

To calculate gradients, the machine learning community uses Autograd:

"Efficiently computes derivatives of numpy code."

To install:

pip install autograd

Here is an example:

import autograd.numpy as np
from autograd import grad

def fct(x):
    y = x**2+1
    return y

grad_fct = grad(fct)
print(grad_fct(1.0))

It can also compute gradients of complex functions, e.g. multivariate functions.

How to set time to 24 hour format in Calendar

use SimpleDateFormat df = new SimpleDateFormat("HH:mm"); instead

UPDATE

@Ingo is right. is's better use setTime(d1);

first method getHours() and getMinutes() is now deprecated

I test this code

SimpleDateFormat df = new SimpleDateFormat("hh:mm");
  Date d1 = df.parse("23:30");
  Calendar c1 = GregorianCalendar.getInstance();
  c1.setTime(d1);
  System.out.println(c1.getTime());

and output is ok Thu Jan 01 23:30:00 FET 1970

try this

SimpleDateFormat df = new SimpleDateFormat("KK:mm aa");
  Date d1 = df.parse("10:30 PM");
  Calendar c1 = GregorianCalendar.getInstance(Locale.US);
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");  
  c1.setTime(d1);
  String str = sdf.format(c1.getTime());
  System.out.println(str);

Log4net does not write the log in the log file

Do you call

log4net.Config.XmlConfigurator.Configure();

somewhere to make log4net read your configuration? E.g. in Global.asax:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

    // Initialize log4net.
    log4net.Config.XmlConfigurator.Configure();
}

error: src refspec master does not match any

This should help you

git init
git add .
git commit -m 'Initial Commit'
git push -u origin master

How to get row count in an Excel file using POI library?

Since Sheet.getPhysicalNumberOfRows() does not count empty rows and Sheet.getLastRowNum() returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.

int rowTotal = sheet.getLastRowNum();

if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
    rowTotal++;
}

Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.

How to parse a string into a nullable int

Glenn Slaven: I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?

There is this approach that will parse directly to a nullable int (and not just int) if the value is valid like null or empty string, but does throw an exception for invalid values so you will need to catch the exception and return the default value for those situations:

public static T Parse<T>(object value)
{
    try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString()); }
    catch { return default(T); }
}

This approach can still be used for non-nullable parses as well as nullable:

enum Fruit { Orange, Apple }
var res1 = Parse<Fruit>("Apple");
var res2 = Parse<Fruit?>("Banana");
var res3 = Parse<int?>("100") ?? 5; //use this for non-zero default
var res4 = Parse<Unit>("45%");

NB: There is an IsValid method on the converter you can use instead of capturing the exception (thrown exceptions does result in unnecessary overhead if expected). Unfortunately it only works since .NET 4 but there's still an issue where it doesn't check your locale when validating correct DateTime formats, see bug 93559.

What is the official "preferred" way to install pip and virtualenv systemwide?

On Ubuntu 12.04 I've had good luck just using the package manager:

sudo apt-get install python-pip virtualenvwrapper

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

Get position/offset of element relative to a parent container?

I did it like this in Internet Explorer.

function getWindowRelativeOffset(parentWindow, elem) {
    var offset = {
        left : 0,
        top : 0
    };
    // relative to the target field's document
    offset.left = elem.getBoundingClientRect().left;
    offset.top = elem.getBoundingClientRect().top;
    // now we will calculate according to the current document, this current
    // document might be same as the document of target field or it may be
    // parent of the document of the target field
    var childWindow = elem.document.frames.window;
    while (childWindow != parentWindow) {
        offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
        offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
        childWindow = childWindow.parent;
    }

    return offset;
};

=================== you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus on IE only as per my focus but similar things can be done for other browsers.

How do I disable fail_on_empty_beans in Jackson?

In Jersey Rest Services just use the JacksonFeatures annotation ...

@JacksonFeatures(serializationDisable = {SerializationFeature.FAIL_ON_EMPTY_BEANS})
public Response getSomething() {
    Object entity = doSomething();
    return Response.ok(entity).build();
}

Where is my m2 folder on Mac OS X Mavericks

Go to finder:

Press on keyboard CMD+shift+G . it will show u a popup like this

Enter path ~/.m2

press enter.

Extracting hours from a DateTime (SQL Server 2005)

DATEPART(HOUR, [date]) returns the hour in military time ( 00 to 23 ) If you want 1AM, 3PM etc, you need to case it out:

SELECT Run_Time_Hour =
CASE DATEPART(HOUR, R.date_schedule)
    WHEN 0 THEN  '12AM'
    WHEN 1 THEN   '1AM'
    WHEN 2 THEN   '2AM'
    WHEN 3 THEN   '3AM'
    WHEN 4 THEN   '4AM'
    WHEN 5 THEN   '5AM'
    WHEN 6 THEN   '6AM'
    WHEN 7 THEN   '7AM'
    WHEN 8 THEN   '8AM'
    WHEN 9 THEN   '9AM'
    WHEN 10 THEN '10AM'
    WHEN 11 THEN '11AM'
    WHEN 12 THEN '12PM'
    ELSE CONVERT(varchar, DATEPART(HOUR, R.date_schedule)-12) + 'PM'
END
FROM
    dbo.ARCHIVE_RUN_SCHEDULE R

Casting string to enum

Have a look at using something like

Enum.TryParse

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

or

Enum.Parse

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Split String into an array of String

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}

Could not find any resources appropriate for the specified culture or the neutral culture

I resolved this by going to the project where my resources file was saved, scrolling down to its ItemGroup and adding a logical name that corresponded to the path the compiler expected.

My EmbeddedResource looked like this:

   <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
  </ItemGroup>

Now it looks like this

  <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
      <LogicalName>MyProject.Properties.Resources.resources</LogicalName>
    </EmbeddedResource>
  </ItemGroup>

java.lang.OutOfMemoryError: Java heap space

  1. Local variables are located on the stack. Heap space is occupied by objects.

  2. You can use the -Xmx option.

  3. Basically heap space is used up everytime you allocate a new object with new and freed some time after the object is no longer referenced. So make sure that you don't keep references to objects that you no longer need.

How to hide Table Row Overflow?

wrap the table in a div with class="container"

div.container {
    width: 100%;
    overflow-x: auto;
}

then

#table_id tr td {
   white-space:nowrap;
}

result

overflow effect

Can I get a patch-compatible output from git-diff?

If you want to use patch you need to remove the a/ b/ prefixes that git uses by default. You can do this with the --no-prefix option (you can also do this with patch's -p option):

git diff --no-prefix [<other git-diff arguments>]

Usually though, it is easier to use straight git diff and then use the output to feed to git apply.

Most of the time I try to avoid using textual patches. Usually one or more of temporary commits combined with rebase, git stash and bundles are easier to manage.

For your use case I think that stash is most appropriate.

# save uncommitted changes
git stash

# do a merge or some other operation
git merge some-branch

# re-apply changes, removing stash if successful
# (you may be asked to resolve conflicts).
git stash pop

What are some good SSH Servers for windows?

VanDyke VShell is the best Windows SSH Server I've ever worked with. It is kind of expensive though ($250). If you want a free solution, freeSSHd works okay. The CYGWIN solution is always an option, I've found, however, that it is a lot of work & overhead just to get SSH.

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

Is it possible to set UIView border properties from interface builder?

Storyboard doesn't work for me all the time even after trying all the solution here

So it is always perfect answer is using the code, Just create IBOutlet instance of the UIView and add the properties

Short answer :

layer.cornerRadius = 10
layer.borderWidth = 1
layer.borderColor = UIColor.blue.cgColor

Long answer :

Rounded Corners of UIView/UIButton etc

customUIView.layer.cornerRadius = 10

Border Thickness

pcustomUIView.layer.borderWidth = 2

Border Color

customUIView.layer.borderColor = UIColor.blue.cgColor

Rotate and translate

Something that may get missed: in my chaining project, it turns out a space separated list also needs a space separated semicolon at the end.

In other words, this doesn't work:

transform: translate(50%, 50%) rotate(90deg);

but this does:

transform: translate(50%, 50%) rotate(90deg) ; //has a space before ";"

Find what 2 numbers add to something and multiply to something

Come on guys, there is no need to loop, just use simple math to solve this equation system:

a*b = i;

a+b = j;

a = j/b;

a = i-b;

j/b = i-b; so:

b + j/b + i = 0

b^2 + i*b + j = 0

From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.

EDIT:

There you go:

function finder($add,$product)
{

 $inside_root = $add*$add - 4*$product;

 if($inside_root >=0)
 {

     $b = ($add + sqrt($inside_root))/2;
     $a = $add - $b;

     echo "$a+$b = $add and $a*$b=$product\n";

 }else
 {
   echo "No real solution\n";
 }
}

Real live action:

http://codepad.org/JBxMgHBd

What is an abstract class in PHP?

  • Abstract Class contains only declare the method's signature, they can't define the implementation.
  • Abstraction class are defined using the keyword abstract .
  • Abstract Class is not possible to implement multiple inheritance.
  • Latest version of PHP 5 has introduces abstract classes and methods.
  • Classes defined as abstract , we are unable to create the object ( may not instantiated )

Update Fragment from ViewPager

Because none of the above answers did the trick for me, here is my solution:

I combined the POSITION_NONE with loading on setUserVisibleHint(boolean isVisibleToUser) instead of onStart()

As seen here: https://stackoverflow.com/a/25676323/497366

In the Fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here
    }else{
       // fragment is no longer visible
    }
}

and in the FragmentStatePagerAdapter as seen in the top answer here from Simon Dorociak https://stackoverflow.com/a/18088509/497366:

@Override
public int getItemPosition(@NonNull Object object) {
    return POSITION_NONE;
}

Now the fragments reload the data into their views everytime they are shown to the user.

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

I did it with:

python3 -m pip install --upgrade tensorflow

How do you add UI inside cells in a google spreadsheet using app script?

Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.

How to convert dd/mm/yyyy string into JavaScript Date object?

Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object

    function newUYDate(pDate) {
      let dd = pDate.split("/")[0].padStart(2, "0");
      let mm = pDate.split("/")[1].padStart(2, "0");
      let yyyy = pDate.split("/")[2].split(" ")[0];
      let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
      let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
      let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
    
      mm = (parseInt(mm) - 1).toString(); // January is 0
    
      return new Date(yyyy, mm, dd, hh, mi, secs);
    }

segmentation fault : 11

What system are you running on? Do you have access to some sort of debugger (gdb, visual studio's debugger, etc.)?

That would give us valuable information, like the line of code where the program crashes... Also, the amount of memory may be prohibitive.

Additionally, may I recommend that you replace the numeric limits by named definitions?

As such:

#define DIM1_SZ 1000
#define DIM2_SZ 1000000

Use those whenever you wish to refer to the array dimension limits. It will help avoid typing errors.

Calling jQuery method from onClick attribute in HTML

you forgot to add this in your function : change to this :

<input type="button" value="ahaha"  onclick="$(this).MessageBox('msg');" />

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

iterating over and removing from a map

Use a real iterator.

Iterator<Object> it = map.keySet().iterator();

while (it.hasNext())
{
  it.next();
  if (something)
    it.remove();
 }

Actually, you might need to iterate over the entrySet() instead of the keySet() to make that work.

Different font size of strings in the same TextView

Use a Spannable String

 String s= "Hello Everyone";
 SpannableString ss1=  new SpannableString(s);
 ss1.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size
 ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color
 TextView tv= (TextView) findViewById(R.id.textview);
 tv.setText(ss1); 

Snap shot

enter image description here

You can split string using space and add span to the string you require.

 String s= "Hello Everyone";  
 String[] each = s.split(" ");

Now apply span to the string and add the same to textview.

Why is synchronized block better than synchronized method?

Because lock is expensive, when you are using synchronized block you lock only if _instance == null, and after _instance finally initialized you'll never lock. But when you synchronize on method you lock unconditionally, even after the _instance is initialized. This is the idea behind double-checked locking optimization pattern http://en.wikipedia.org/wiki/Double-checked_locking.

Getting value GET OR POST variable using JavaScript?

You can't get the value of POST variables using Javascript, although you can insert it in the document when you process the request on the server.

<script type="text/javascript">
    window.some_variable = '<?=$_POST['some_value']?>'; // That's for a string
</script>

GET variables are available through the window.location.href, and some frameworks even have methods ready to parse them.

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

How to use gitignore command in git

There is a file in your git root directory named .gitignore. It's a file, not a command. You just need to insert the names of the files that you want to ignore, and they will automatically be ignored. For example, if you wanted to ignore all emacs autosave files, which end in ~, then you could add this line:

*~

If you want to remove the unwanted files from your branch, you can use git add -A, which "removes files that are no longer in the working tree".

Note: What I called the "git root directory" is simply the directory in which you used git init for the first time. It is also where you can find the .git directory.

Which tool to build a simple web front-end to my database

For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.

For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.

Convert a list of characters into a string

The reduce function also works

import operator
h=['a','b','c','d']
reduce(operator.add, h)
'abcd'

CSS grid wrapping

I had a similar situation. On top of what you did, I wanted to center my columns in the container while not allowing empty columns to for them left or right:

.grid { 
    display: grid;
    grid-gap: 10px;
    justify-content: center;
    grid-template-columns: repeat(auto-fit, minmax(200px, auto));
}

Where is database .bak file saved from SQL Server Management Studio?

Use the script below, and switch the DatabaseName with then name of the database that you've backed up. On the column physical_device_name, you'll have the full path of your backed-up database:

select a.backup_set_id, a.server_name, a.database_name, a.name, a.user_name, a.position, a.software_major_version, a.backup_start_date, backup_finish_date, a.backup_size, a.recovery_model, b.physical_device_name
from msdb.dbo.backupset a join msdb.dbo.backupmediafamily b
  on a.media_set_id = b.media_set_id
where a.database_name = 'DatabaseName'
order by a.backup_finish_date desc

How many threads can a Java VM support?

After playing around with Charlie's DieLikeACode class, it looks like the Java thread stack size is a huge part of how many threads you can create.

-Xss set java thread stack size

For example

java -Xss100k DieLikeADog

But, Java has the Executor interface. I would use that, you will be able to submit thousands of Runnable tasks, and have the Executor process those tasks with a fixed number of threads.

Submit a form using jQuery

Note that if you already installed a submit event listener for your form, the innner call to submit()

jQuery('#<form-id>').submit( function(e){ 
    e.preventDefault();
    // maybe some validation in here
    if ( <form-is-valid> ) jQuery('#<form-id>').submit();
});

won't work as it tries to install a new event listener for this form's submit event (which fails). So you have to acces the HTML Element itself (unwrap from jQquery) and call submit() on this element directly:

    jQuery('#<form-id>').submit( function(e){ 
      e.preventDefault();
      // note the [0] array access:
      if ( <form-is-valid> ) jQuery('#<form-id>')[0].submit();
    });

How to check if a char is equal to an empty space?

You could use

Character.isWhitespace(c)

or any of the other available methods in the Character class.

  if (c == ' ')

also works.

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Save PL/pgSQL output from PostgreSQL to a CSV file

CSV Export Unification

This information isn't really well represented. As this is the second time I've needed to derive this, I'll put this here to remind myself if nothing else.

Really the best way to do this (get CSV out of postgres) is to use the COPY ... TO STDOUT command. Though you don't want to do it the way shown in the answers here. The correct way to use the command is:

COPY (select id, name from groups) TO STDOUT WITH CSV HEADER

Remember just one command!

It's great for use over ssh:

$ ssh psqlserver.example.com 'psql -d mydb "COPY (select id, name from groups) TO STDOUT WITH CSV HEADER"' > groups.csv

It's great for use inside docker over ssh:

$ ssh pgserver.example.com 'docker exec -tu postgres postgres psql -d mydb -c "COPY groups TO STDOUT WITH CSV HEADER"' > groups.csv

It's even great on the local machine:

$ psql -d mydb -c 'COPY groups TO STDOUT WITH CSV HEADER' > groups.csv

Or inside docker on the local machine?:

docker exec -tu postgres postgres psql -d mydb -c 'COPY groups TO STDOUT WITH CSV HEADER' > groups.csv

Or on a kubernetes cluster, in docker, over HTTPS??:

kubectl exec -t postgres-2592991581-ws2td 'psql -d mydb -c "COPY groups TO STDOUT WITH CSV HEADER"' > groups.csv

So versatile, much commas!

Do you even?

Yes I did, here are my notes:

The COPYses

Using /copy effectively executes file operations on whatever system the psql command is running on, as the user who is executing it1. If you connect to a remote server, it's simple to copy data files on the system executing psql to/from the remote server.

COPY executes file operations on the server as the backend process user account (default postgres), file paths and permissions are checked and applied accordingly. If using TO STDOUT then file permissions checks are bypassed.

Both of these options require subsequent file movement if psql is not executing on the system where you want the resultant CSV to ultimately reside. This is the most likely case, in my experience, when you mostly work with remote servers.

It is more complex to configure something like a TCP/IP tunnel over ssh to a remote system for simple CSV output, but for other output formats (binary) it may be better to /copy over a tunneled connection, executing a local psql. In a similar vein, for large imports, moving the source file to the server and using COPY is probably the highest-performance option.

PSQL Parameters

With psql parameters you can format the output like CSV but there are downsides like having to remember to disable the pager and not getting headers:

$ psql -P pager=off -d mydb -t -A -F',' -c 'select * from groups;'
2,Technician,Test 2,,,t,,0,,                                                                                                                                                                   
3,Truck,1,2017-10-02,,t,,0,,                                                                                                                                                                   
4,Truck,2,2017-10-02,,t,,0,,

Other Tools

No, I just want to get CSV out of my server without compiling and/or installing a tool.

Parse JSON String into List<string>

Since you are using JSON.NET, personally I would go with serialization so that you can have Intellisense support for your object. You'll need a class that represents your JSON structure. You can build this by hand, or you can use something like json2csharp to generate it for you:

e.g.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class RootObject
{
    public List<Person> People { get; set; }
}

Then, you can simply call JsonConvert's methods to deserialize the JSON into an object:

RootObject instance = JsonConvert.Deserialize<RootObject>(json);

Then you have Intellisense:

var firstName = instance.People[0].FirstName;
var lastName = instance.People[0].LastName;

How do I use CSS with a ruby on rails application?

I did the following...

  1. place your css file in the app/assets/stylesheets folder.
  2. Add the stylesheet link <%= stylesheet_link_tag "filename" %> in your default layouts file (most likely application.html.erb)

I recommend this over using your public folder. You can also reference the stylesheet inline, such as in your index page.

How can I remove all files in my git repo and update/push from my local git repo?

Yes, if you do a git rm <filename> and commit & push those changes. The file will disappear from the repository for that changeset and future commits.

The file will still be available for the previous revisions.

Trying to add adb to PATH variable OSX

Just encase anyone finds this SO post when using Android Studio which includes the SDK has part of the App package (on Mac OSX).

So as @davecaunt and @user1281750 noted but insert the following line to .bash_profile

export PATH=/Applications/Android\ Studio.app/sdk/tools:/Applications/Android\ Studio.app/sdk/platform-tools:$PATH

How to "fadeOut" & "remove" a div in jQuery?

if you are anything like me coming from a google search and looking to remove an html element with cool animation, then this could help you:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    _x000D_
    var $deleteButton = $('.deleteItem');_x000D_
_x000D_
    $deleteButton.on('click', function(event) {_x000D_
    _x000D_
        event.preventDefault();_x000D_
_x000D_
        var $button = $(this);_x000D_
_x000D_
        if(confirm('Are you sure about this ?')) {_x000D_
_x000D_
            var $item = $button.closest('tr.item');_x000D_
_x000D_
            $item.addClass('removed-item')_x000D_
_x000D_
                .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {_x000D_
_x000D_
                    $(this).remove();_x000D_
            });_x000D_
        }_x000D_
      _x000D_
    });_x000D_
    _x000D_
});
_x000D_
/**_x000D_
 * Credit to Sara Soueidan_x000D_
 * @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-3.css_x000D_
 */_x000D_
_x000D_
.removed-item {_x000D_
    -webkit-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
    -o-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
    animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29)_x000D_
}_x000D_
_x000D_
@keyframes removed-item-animation {_x000D_
    0% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(0);_x000D_
        -ms-transform: translateX(0);_x000D_
        -o-transform: translateX(0);_x000D_
        transform: translateX(0)_x000D_
    }_x000D_
_x000D_
    30% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(50px);_x000D_
        -ms-transform: translateX(50px);_x000D_
        -o-transform: translateX(50px);_x000D_
        transform: translateX(50px)_x000D_
    }_x000D_
_x000D_
    80% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        -ms-transform: translateX(-800px);_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 0;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        -ms-transform: translateX(-800px);_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes removed-item-animation {_x000D_
    0% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(0);_x000D_
        transform: translateX(0)_x000D_
    }_x000D_
_x000D_
    30% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(50px);_x000D_
        transform: translateX(50px)_x000D_
    }_x000D_
_x000D_
    80% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 0;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
}_x000D_
_x000D_
@-o-keyframes removed-item-animation {_x000D_
    0% {_x000D_
        opacity: 1;_x000D_
        -o-transform: translateX(0);_x000D_
        transform: translateX(0)_x000D_
    }_x000D_
_x000D_
    30% {_x000D_
        opacity: 1;_x000D_
        -o-transform: translateX(50px);_x000D_
        transform: translateX(50px)_x000D_
    }_x000D_
_x000D_
    80% {_x000D_
        opacity: 1;_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 0;_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
  _x000D_
  <table class="table table-striped table-bordered table-hover">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>id</th>_x000D_
        <th>firstname</th>_x000D_
        <th>lastname</th>_x000D_
        <th>@twitter</th>_x000D_
        <th>action</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      _x000D_
      <tr class="item">_x000D_
        <td>1</td>_x000D_
        <td>Nour-Eddine</td>_x000D_
        <td>ECH-CHEBABY</td>_x000D_
        <th>@__chebaby</th>_x000D_
        <td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
      </tr>_x000D_
      _x000D_
      <tr class="item">_x000D_
        <td>2</td>_x000D_
        <td>John</td>_x000D_
        <td>Doe</td>_x000D_
        <th>@johndoe</th>_x000D_
        <td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
      </tr>_x000D_
      _x000D_
      <tr class="item">_x000D_
        <td>3</td>_x000D_
        <td>Jane</td>_x000D_
        <td>Doe</td>_x000D_
        <th>@janedoe</th>_x000D_
        <td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
  _x000D_
<script src="https://code.jquery.com/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to convert a PIL Image into a numpy array?

If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.

In my case, I needed my images where stored in a blob column in a db table:

def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")    
    rows = cur.fetchall()    
    return rows

I then created a helper function to change my dataset into np.array:

X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):  
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

After this, I was able to use the byteArrays in my Neural Network.

plt.imshow(imagesList[0])

Difference Between Select and SelectMany

It's more clear when the query return a string (an array of char):

For example if the list 'Fruits' contains 'apple'

'Select' returns the string:

Fruits.Select(s=>s) 

[0]: "apple"

'SelectMany' flattens the string:

Fruits.SelectMany(s=>s)

[0]: 97  'a'
[1]: 112 'p'
[2]: 112 'p'
[3]: 108 'l'
[4]: 101 'e'

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

mysql_* functions have been removed in PHP 7.

You now have two alternatives: MySQLi and PDO.

The following is a before (-) and after (+) comparison of a migration to the MySQLi alternative, taken straight out of working code:

-if (!$dbLink = mysql_connect($dbHost, $dbUser, $dbPass))
+if (!$dbLink = mysqli_connect($dbHost, $dbUser, $dbPass))

-if (!mysql_select_db($dbName, $dbLink))
+if (!mysqli_select_db($dbLink, $dbName))

-if (!$result = mysql_query($query, $dbLink)) {
+if (!$result = mysqli_query($dbLink, $query)) {

-if (mysql_num_rows($result) > 0) {
+if (mysqli_num_rows($result) > 0) {

-while ($row = mysql_fetch_array( $result, MYSQL_ASSOC )) {
+while ($row = mysqli_fetch_array( $result, MYSQLI_ASSOC )) {

-mysql_close($dbLink);
+mysqli_close($dbLink);

How can I remove the extension of a filename in a shell script?

My recommendation is to use basename.
It is by default in Ubuntu, visually simple code and deal with majority of cases.

Here are some sub-cases to deal with spaces and multi-dot/sub-extension:

pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}

It usually get rid of extension from first ., but fail in our .. path

echo **"$(basename "${pathfile%.*}")"**  
space -file.tar     # I believe we needed exatly that

Here is an important note:

I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.

However, you still need to think of .hidden_files

hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")"  # will produce "~" !!!  

not the expected "" outcome. To make it happen use $HOME or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)

hidden2="$HOME/.bashrc" ;  echo '$(basename "${pathfile%.*}")'

Javascript Object push() function

Javascript programming language supports functional programming paradigm so you can do easily with these codes.

var data = [
    {"Id": "1", "Status": "Valid"},
    {"Id": "2", "Status": "Invalid"}
];
var isValid = function(data){
    return data.Status === "Valid";
};
var valids = data.filter(isValid);

Bootstrap: adding gaps between divs

Starting from Bootstrap v4 you can simply add the following to your div class attribute: mt-2 (margin top 2)

<div class="mt-2 col-md-12">
        This will have a two-point top margin!
</div>

More examples are given in the docs: Bootstrap v4 docs

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

how concatenate two variables in batch script?

Enabling delayed variable expansion solves you problem, the script produces "hi":

setlocal EnableDelayedExpansion

set var1=A
set var2=B

set AB=hi

set newvar=!%var1%%var2%!

echo %newvar%

How to initialize a list with constructor?

You can initialize it just like any list:

public List<ContactNumber> ContactNumbers { get; set; }

public Human(int id)
{
    Id = id;
    ContactNumbers = new List<ContactNumber>();
}

public Human(int id, string address, string name) :this(id)
{
    Address = address;
    Name = name;
    // no need to initialize the list here since you're
    // already calling the single parameter constructor
}       

However, I would even go a step further and make the setter private since you often don't need to set the list, but just access/modify its contents:

public List<ContactNumber> ContactNumbers { get; private set; }

Kafka consumer list

Use kafka-consumer-groups.sh

For example

bin/kafka-consumer-groups.sh  --list --bootstrap-server localhost:9092

bin/kafka-consumer-groups.sh --describe --group mygroup --bootstrap-server localhost:9092

Table with 100% width with equal size columns

Just add style="table-layout: fixed ; width: 100%;" inside <table> tag and also if you do not specify any styles and add just style=" width: 100%;" inside <table> You will be able to resolve it.

Use multiple custom fonts using @font-face?

If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.

The easiest way I found to find this out was to install the font and see what display name is given.

For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.

Hope that helps.

Limiting the number of characters per line with CSS

Depending on what font you're using you can set max-width on the paragraph with a calculated value. It will not be exact, but I've found that in most cases that does not matter.

p {
  max-width: calc(30em * 0.5);
}

The number you multiply with depends on what font it is, and how much a character takes up in a em square. More characters = less accurate.

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

That's a half-open interval.

  • A closed interval [a,b] includes the end points.
  • An open interval (a,b) excludes them.

In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".

Half-open intervals are useful in programming because they correspond to the common idiom for looping:

for (int i = 0; i < n; ++i) { ... } 

Here i is in the range [0, n).

How to convert date to timestamp in PHP?

Given that the function strptime() does not work for Windows and strtotime() can return unexpected results, I recommend using date_parse_from_format():

$date = date_parse_from_format('d-m-Y', '22-09-2008');
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);

check if a key exists in a bucket in s3 using boto3

import boto3
client = boto3.client('s3')
s3_key = 'Your file without bucket name e.g. abc/bcd.txt'
bucket = 'your bucket name'
content = client.head_object(Bucket=bucket,Key=s3_key)
    if content.get('ResponseMetadata',None) is not None:
        print "File exists - s3://%s/%s " %(bucket,s3_key) 
    else:
        print "File does not exist - s3://%s/%s " %(bucket,s3_key)

How to tell if homebrew is installed on Mac OS X

The standard way of figuring out if something is installed is to use which.

If Brew is installed.

>>> which brew
/usr/local/bin/brew

If Brew is not installed.

>>> which brew
brew not found

Note: The "not installed" message depends on your shell. zsh is shown above. bash will just not print anything. csh will say brew: Command not found. In the "installed" case, all shells will print the path.)

It works with all command line programs. Try which grep or which python. Since it tells you the program that you're running, it's helpful when debugging as well.

How to use Elasticsearch with MongoDB?

This answer should be enough to get you set up to follow this tutorial on Building a functional search component with MongoDB, Elasticsearch, and AngularJS.

If you're looking to use faceted search with data from an API then Matthiasn's BirdWatch Repo is something you might want to look at.

So here's how you can setup a single node Elasticsearch "cluster" to index MongoDB for use in a NodeJS, Express app on a fresh EC2 Ubuntu 14.04 instance.

Make sure everything is up to date.

sudo apt-get update

Install NodeJS.

sudo apt-get install nodejs
sudo apt-get install npm

Install MongoDB - These steps are straight from MongoDB docs. Choose whatever version you're comfortable with. I'm sticking with v2.4.9 because it seems to be the most recent version MongoDB-River supports without issues.

Import the MongoDB public GPG Key.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Update your sources list.

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Get the 10gen package.

sudo apt-get install mongodb-10gen

Then pick your version if you don't want the most recent. If you are setting your environment up on a windows 7 or 8 machine stay away from v2.6 until they work some bugs out with running it as a service.

apt-get install mongodb-10gen=2.4.9

Prevent the version of your MongoDB installation being bumped up when you update.

echo "mongodb-10gen hold" | sudo dpkg --set-selections

Start the MongoDB service.

sudo service mongodb start

Your database files default to /var/lib/mongo and your log files to /var/log/mongo.

Create a database through the mongo shell and push some dummy data into it.

mongo YOUR_DATABASE_NAME
db.createCollection(YOUR_COLLECTION_NAME)
for (var i = 1; i <= 25; i++) db.YOUR_COLLECTION_NAME.insert( { x : i } )

Now to Convert the standalone MongoDB into a Replica Set.

First Shutdown the process.

mongo YOUR_DATABASE_NAME
use admin
db.shutdownServer()

Now we're running MongoDB as a service, so we don't pass in the "--replSet rs0" option in the command line argument when we restart the mongod process. Instead, we put it in the mongod.conf file.

vi /etc/mongod.conf

Add these lines, subbing for your db and log paths.

replSet=rs0
dbpath=YOUR_PATH_TO_DATA/DB
logpath=YOUR_PATH_TO_LOG/MONGO.LOG

Now open up the mongo shell again to initialize the replica set.

mongo DATABASE_NAME
config = { "_id" : "rs0", "members" : [ { "_id" : 0, "host" : "127.0.0.1:27017" } ] }
rs.initiate(config)
rs.slaveOk() // allows read operations to run on secondary members.

Now install Elasticsearch. I'm just following this helpful Gist.

Make sure Java is installed.

sudo apt-get install openjdk-7-jre-headless -y

Stick with v1.1.x for now until the Mongo-River plugin bug gets fixed in v1.2.1.

wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb
sudo dpkg -i elasticsearch-1.1.1.deb

curl -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
sudo mv *servicewrapper*/service /usr/local/share/elasticsearch/bin/
sudo rm -Rf *servicewrapper*
sudo /usr/local/share/elasticsearch/bin/service/elasticsearch install
sudo ln -s `readlink -f /usr/local/share/elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch

Make sure /etc/elasticsearch/elasticsearch.yml has the following config options enabled if you're only developing on a single node for now:

cluster.name: "MY_CLUSTER_NAME"
node.local: true

Start the Elasticsearch service.

sudo service elasticsearch start

Verify it's working.

curl http://localhost:9200

If you see something like this then you're good.

{
  "status" : 200,
  "name" : "Chi Demon",
  "version" : {
    "number" : "1.1.2",
    "build_hash" : "e511f7b28b77c4d99175905fac65bffbf4c80cf7",
    "build_timestamp" : "2014-05-22T12:27:39Z",
    "build_snapshot" : false,
    "lucene_version" : "4.7"
  },
  "tagline" : "You Know, for Search"
}

Now install the Elasticsearch plugins so it can play with MongoDB.

bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb/1.6.0
bin/plugin --install elasticsearch/elasticsearch-mapper-attachments/1.6.0

These two plugins aren't necessary but they're good for testing queries and visualizing changes to your indexes.

bin/plugin --install mobz/elasticsearch-head
bin/plugin --install lukas-vlcek/bigdesk

Restart Elasticsearch.

sudo service elasticsearch restart

Finally index a collection from MongoDB.

curl -XPUT localhost:9200/_river/DATABASE_NAME/_meta -d '{
  "type": "mongodb",
  "mongodb": {
    "servers": [
      { "host": "127.0.0.1", "port": 27017 }
    ],
    "db": "DATABASE_NAME",
    "collection": "ACTUAL_COLLECTION_NAME",
    "options": { "secondary_read_preference": true },
    "gridfs": false
  },
  "index": {
    "name": "ARBITRARY INDEX NAME",
    "type": "ARBITRARY TYPE NAME"
  }
}'

Check that your index is in Elasticsearch

curl -XGET http://localhost:9200/_aliases

Check your cluster health.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

It's probably yellow with some unassigned shards. We have to tell Elasticsearch what we want to work with.

curl -XPUT 'localhost:9200/_settings' -d '{ "index" : { "number_of_replicas" : 0 } }'

Check cluster health again. It should be green now.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

Go play.

Get a list of all the files in a directory (recursive)

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}

Why does JPA have a @Transient annotation?

In laymen's terms, if you use the @Transient annotation on an attribute of an entity: this attribute will be singled out and will not be saved to the database. The rest of the attribute of the object within the entity will still be saved.

example:

Im saving the Object to the database using the jpa repository built in save method as so:

userRoleJoinRepository.save(user2);

How do I replace multiple spaces with a single space in C#?

myString = Regex.Replace(myString, " {2,}", " ");

Read CSV with Scanner()

Split nextLine() by this delimiter: (?=([^\"]*\"[^\"]*\")*[^\"]*$)").

Trying to start a service on boot on Android

I found out just now that it might be because of Fast Boot option in Settings > Power

When I have this option off, my application receives a this broadcast but not otherwise.

By the way, I have Android 2.3.3 on HTC Incredible S.

Hope it helps.

JSON to pandas DataFrame

Optimization of the accepted answer:

The accepted answer has some functioning problems, so I want to share my code that does not rely on urllib2:

import requests
from pandas import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'

response = requests.get(url)
dictr = response.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)

Output:

        _id                    HourUTC               HourDK  ... ElbasAveragePriceEUR  ElbasMaxPriceEUR  ElbasMinPriceEUR
0    264028  2019-01-01T00:00:00+00:00  2019-01-01T01:00:00  ...                  NaN               NaN               NaN
1    138428  2017-09-03T15:00:00+00:00  2017-09-03T17:00:00  ...                33.28              33.4              32.0
2    138429  2017-09-03T16:00:00+00:00  2017-09-03T18:00:00  ...                35.20              35.7              34.9
3    138430  2017-09-03T17:00:00+00:00  2017-09-03T19:00:00  ...                37.50              37.8              37.3
4    138431  2017-09-03T18:00:00+00:00  2017-09-03T20:00:00  ...                39.65              42.9              35.3
..      ...                        ...                  ...  ...                  ...               ...               ...
995  139290  2017-10-09T13:00:00+00:00  2017-10-09T15:00:00  ...                38.40              38.4              38.4
996  139291  2017-10-09T14:00:00+00:00  2017-10-09T16:00:00  ...                41.90              44.3              33.9
997  139292  2017-10-09T15:00:00+00:00  2017-10-09T17:00:00  ...                46.26              49.5              41.4
998  139293  2017-10-09T16:00:00+00:00  2017-10-09T18:00:00  ...                56.22              58.5              49.1
999  139294  2017-10-09T17:00:00+00:00  2017-10-09T19:00:00  ...                56.71              65.4              42.2 

PS: API is for Danish electricity prices

Continue For loop

you can do that by simple way, simply change the variable value that used in for loop to the end value as shown in example

_x000D_
_x000D_
Sub TEST_ONLY()
        For i = 1 To 10
            ActiveSheet.Cells(i, 1).Value = i
            If i = 5 Then
                i = 10
            End If
        Next i
End Sub
_x000D_
_x000D_
_x000D_

Get list of passed arguments in Windows batch script (.bat)

You can use For Commad,to get list of Arg.

Help : For /? Help : Setlocal /?

Here is my way =

@echo off
::For Run Use This = cmd /c ""Args.cmd" Hello USER Scientist etc"
setlocal EnableDelayedExpansion
set /a Count=0
for %%I IN (%*) DO (
 Echo Arg_!Count! = %%I
 set /a Count+=1 
)
Echo Count Of Args = !Count!
Endlocal

Do not need Shift command.

Accessing session from TWIG template

Setup twig

$twig = new Twig_Environment(...);    
$twig->addGlobal('session', $_SESSION);

Then within your template access session values for example

$_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template

How to differ sessions in browser-tabs?

How to differ sessions in browser-tabs?

The most straightforward way to differ sessions in browser tabs is to disallow your particular domain to set cookies. That way, you can have separate sessions from separate tabs. Say you disallow cookies from this domain: www.xyz.com. You open Tab 1, login and start browsing. Then you open Tab 2, and you can login either as a same user or a different one; either way, you will have a session separate from Tab 1. And so on.

But of course this is possible when you have control over the client side. Otherwise, the solutions prescribed by the folks here should apply.

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

Run PHP Task Asynchronously

Unfortunately PHP does not have any kind of native threading capabilities. So I think in this case you have no choice but to use some kind of custom code to do what you want to do.

If you search around the net for PHP threading stuff, some people have come up with ways to simulate threads on PHP.

Replace all whitespace with a line break/paragraph mark to make a word list

This should do the work:

sed -e 's/[ \t]+/\n/g'

[ \t] means a space OR an tab. If you want any kind of space, you could also use \s.

[ \t]+ means as many spaces OR tabs as you want (but at least one)

s/x/y/ means replace the pattern x by y (here \n is a new line)

The g at the end means that you have to repeat as many times it occurs in every line.

How To Add An "a href" Link To A "div"?

try to implement with javascript this:

<div id="mydiv" onclick="myhref('http://web.com');" >some stuff </div>
<script type="text/javascript">
    function myhref(web){
      window.location.href = web;}
</script>

Spring Boot: How can I set the logging level with application.properties?

With Springboot 2 you can set the root logging Level with an Environment Variable like this:

logging.level.root=DEBUG

Or you can set specific logging for packages like this:

logging.level.my.package.name=TRACE

Given final block not properly padded

I met this issue due to operation system, simple to different platform about JRE implementation.

new SecureRandom(key.getBytes())

will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);

"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.

In Java, how to find if first character in a string is upper case without regex

String yourString = "yadayada";
if (Character.isUpperCase(yourString.charAt(0))) {
    // print something
} else {
    // print something else
}

How to properly export an ES6 class in Node 4?

I had the same problem. What i found was i called my recieving object the same name as the class name. example:

const AspectType = new AspectType();

this screwed things up that way... hope this helps

Codeigniter $this->db->order_by(' ','desc') result is not complete

$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();

Read .csv file in C

Hopefully this would get you started

See it live on http://ideone.com/l23He (using stdin)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* getfield(char* line, int num)
{
    const char* tok;
    for (tok = strtok(line, ";");
            tok && *tok;
            tok = strtok(NULL, ";\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}

int main()
{
    FILE* stream = fopen("input", "r");

    char line[1024];
    while (fgets(line, 1024, stream))
    {
        char* tmp = strdup(line);
        printf("Field 3 would be %s\n", getfield(tmp, 3));
        // NOTE strtok clobbers tmp
        free(tmp);
    }
}

Output:

Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak

How to clear the cache of nginx?

There are already a lot of answers out there but I think I have a useful addition;

I'm running a Homestead box with Hyper-V and I had a laravel project up and running on nginx.

I didn't have a cache in my nginx folder in /etc/

When i visited my website, I was getting server old views and css files.

What solved it for me after searching a wasting a lot of time looking at my nginx config and trying things out was using PHP artisan.

Run the following command in the folder where artisan is installed [root dir of laravel project]: php artisan optimize:clear

this command clears all the caches, and when i refreshed my webpage, Finaly it updated with all the changes.

Hope this helps stranded souls like me :)

EDIT: I would have posted this as a comment to one of the already existing answers if I had 50 reputation.. [I have only 43 so far]

How to display binary data as image - extjs 4

The data URI format is:

data:<headers>;<encoding>,<data>

So, you need only append your data to the "data:image/jpeg;," string:

var your_binary_data = document.body.innerText.replace(/(..)/gim,'%$1'); // parse text data to URI format

window.open('data:image/jpeg;,'+your_binary_data);

How to do select from where x is equal to multiple values?

And even simpler using IN:

SELECT ads.*, location.county 
  FROM ads
  LEFT JOIN location ON location.county = ads.county_id
  WHERE ads.published = 1 
        AND ads.type = 13
        AND ads.county_id IN (2,5,7,9)

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

OK so here is how I actually forced the change on my Windows files regarding the permissions themselves on Win7: Find your ssh key in windows explorer: C:\Users[your_user_name_here].ssh\id_rsa

Right-click on file>Properties>Security tab>Advanced button>Change permissions

Now remove everyone that is not actually your username. This includes Administrator and System users. At this point you may get a dialogue about inheriting permissions- choose the option that DOESN'T inherit- since we only want to change this file.

Click OK and save till done.

I fought with this for days because my windows would not change the file permissions from the command line. This way it is also ACTUALLY done- instead of using exciting work arounds that make can have odd consequences.

How to enable external request in IIS Express?

This is insanely awesome and even covers HTTPS with pretty domain names:

http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx

The really awesome parts I couldn't find anywhere else on SO in case the above link ever goes away:

> C:\Program Files (x86)\IIS Express>IisExpressAdminCmd.exe Usage:
> iisexpressadmincmd.exe <command> <parameters> Supported commands:
>       setupFriendlyHostnameUrl -url:<url>
>       deleteFriendlyHostnameUrl -url:<url>
>       setupUrl -url:<url>
>       deleteUrl -url:<url>
>       setupSslUrl -url:<url> -CertHash:<value>
>       setupSslUrl -url:<url> -UseSelfSigned
>       deleteSslUrl -url:<url>
> 
> Examples: 1) Configure "http.sys" and "hosts" file for friendly
> hostname "contoso": iisexpressadmincmd setupFriendlyHostnameUrl
> -url:http://contoso:80/ 2) Remove "http.sys" configuration and "hosts" file entry for the friendly  hostname "contoso": iisexpressadmincmd
> deleteFriendlyHostnameUrl -url:http://contoso:80/

The above utility will register the SSL certificate for you! If you use the -UseSelfSigned option, it's super easy.

If you want to do things the hard way, the non-obvious part is you need to tell HTTP.SYS what certificate to use, like this:

netsh http add sslcert ipport=0.0.0.0:443 appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certhash=YOURCERTHASHHERE

Certhash is the "Thumbprint" you can get from the certificate properties in MMC.

WPF Datagrid set selected row

You don't need to iterate through the DataGrid rows, you can achieve your goal with a more simple solution. In order to match your row you can iterate through you collection that was bound to your DataGrid.ItemsSource property then assign this item to you DataGrid.SelectedItem property programmatically, alternatively you can add it to your DataGrid.SelectedItems collection if you want to allow the user to select more than one row. See the code below:

<Window x:Class="ProgGridSelection.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<StackPanel>
    <DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
    <TextBox Name="empNameTextBox"/>
    <Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>

public partial class MainWindow : Window
{
    public class Employee
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

    private ObservableCollection<Employee> _empCollection;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void OnWindowLoaded(object sender, RoutedEventArgs e)
    {
        // Generate test data
        _empCollection =
            new ObservableCollection<Employee>
                {
                    new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
                    new Employee {Code = "E013", Name = "Ahmed Yousif"},
                    new Employee {Code = "E431", Name = "Jasmin Kamal"},
                };

        /* Set the Window.DataContext, alternatively you can set your
         * DataGrid DataContext property to the employees collection.
         * on the other hand, you you have to bind your DataGrid
         * DataContext property to the DataContext (see the XAML code)
         */
        DataContext = _empCollection;
    }

    private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
    {
        /* select the employee that his name matches the
         * name on the TextBox
         */
        var emp = (from i in _empCollection
                   where i.Name == empNameTextBox.Text.Trim()
                   select i).FirstOrDefault();

        /* Now, to set the selected item on the DataGrid you just need
         * assign the matched employee to your DataGrid SeletedItem
         * property, alternatively you can add it to your DataGrid
         * SelectedItems collection if you want to allow the user
         * to select more than one row, e.g.:
         *    empDataGrid.SelectedItems.Add(emp);
         */
        if (emp != null)
            empDataGrid.SelectedItem = emp;
    }
}

What are the differences among grep, awk & sed?

Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.

Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.

Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.

Getting the parameters of a running JVM

You can use jps like

jps -lvm

prints something like

4050 com.intellij.idea.Main -Xms128m -Xmx512m -XX:MaxPermSize=250m -ea -Xbootclasspath/a:../lib/boot.jar -Djb.restart.code=88
4667 sun.tools.jps.Jps -lvm -Dapplication.home=/opt/java/jdk1.6.0_22 -Xms8m

Where does Anaconda Python install on Windows?

conda info will display information about the current install, including the active env location which is what you want.

Here's my output:

(base) C:\Users\USERNAME>conda info

     active environment : base
    active env location : C:\ProgramData\Miniconda3
            shell level : 1
       user config file : C:\Users\USERNAME\.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : not installed
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
       base environment : C:\ProgramData\Miniconda3  (read only)
           channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : C:\ProgramData\Miniconda3\pkgs
                          C:\Users\USERNAME\.conda\pkgs
                          C:\Users\USERNAME\AppData\Local\conda\conda\pkgs
       envs directories : C:\Users\USERNAME\.conda\envs
                          C:\ProgramData\Miniconda3\envs
                          C:\Users\USERNAME\AppData\Local\conda\conda\envs
               platform : win-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Windows/10 Windows/10.0.18362
          administrator : False
             netrc file : None
           offline mode : False

If your shell/prompt complains that it cannot find the command, it likely means that you installed Anaconda without adding it to the PATH environment variable.

If that's the case find and open the Anaconda Prompt and do it from there.

Alternatively reinstall Anaconda choosing to add it to the PATH. Or add the variable manually.

Anaconda Prompt should be available in your Start Menu (Win) or Applications Menu (macos)

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

Be sure you only have one version of NodeJS installed. Try these two:

node --version
sudo node --version

I initially installed NodeJS from source, but it was the incorrect version and 'upgraded' to the newest version using nvm, which doesn't remove any previous versions, and only installs the desired version in the /root/.nvm/versions/... directory. So sudo node was still pointing to the previous version, whilst node was pointing to the newer version.

Combining two lists and removing duplicates, without removing duplicates in original list

This might help

def union(a,b):
    for e in b:
        if e not in a:
            a.append(e)

The union function merges the second list into first, with out duplicating an element of a, if it's already in a. Similar to set union operator. This function does not change b. If a=[1,2,3] b=[2,3,4]. After union(a,b) makes a=[1,2,3,4] and b=[2,3,4]

What is the syntax to insert one list into another list in python?

foo = [1, 2, 3]
bar = [4, 5, 6]

foo.append(bar) --> [1, 2, 3, [4, 5, 6]]
foo.extend(bar) --> [1, 2, 3, 4, 5, 6]

http://docs.python.org/tutorial/datastructures.html

Resize Cross Domain Iframe Height

If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe container anytime the height of the framed content changes.

Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).

window.addEventListener("load", function(){
    if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe 
    send_height_to_parent_function = function(){
        var height = document.getElementsByTagName("html")[0].clientHeight;
        //console.log("Sending height as " + height + "px");
        parent.postMessage({"height" : height }, "*");
    }
    // send message to parent about height updates
    send_height_to_parent_function(); //whenever the page is loaded
    window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
    var observer = new MutationObserver(send_height_to_parent_function);           // whenever DOM changes PT1
    var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
    observer.observe(window.document, config);                                            // PT3 
});

Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.

<script>
window.addEventListener("message", function(e){
    var this_frame = document.getElementById("healthy_behavior_iframe");
    if (this_frame.contentWindow === e.source) {
        this_frame.height = e.data.height + "px";
        this_frame.style.height = e.data.height + "px";
    }
})
</script>

How to pass List from Controller to View in MVC 3

You can use the dynamic object ViewBag to pass data from Controllers to Views.

Add the following to your controller:

ViewBag.MyList = myList;

Then you can acces it from your view:

@ViewBag.MyList

// e.g.
@foreach (var item in ViewBag.MyList) { ... }

What is the proper way to check and uncheck a checkbox in HTML5?

In jQuery:

To check the checkbox:

$("#checkboxid").attr("checked","checked");

To uncheck the checkbox:

$("#checkboxid").removeAttr("checked");

The other answers hint at the solution and point you to documentation that after further digging will get you to this answer. Jukka K. Korpela has the reason this is the correct answer, basically I followed his link and then looked up the jQuery docs to get to that result. Just figured I'd save future people who find this article those extra steps.

How can I record a Video in my Android App.?

As of December 2017, there have been some updates, e.g. the usage of android.hardware.Camera is deprecated now. While the newer android.hardware.camera2 comes with handy things like a CameraManager.

I personally like this example a lot, which makes use of this current API and works like a charm: https://github.com/googlesamples/android-Camera2Video

It also includes asking the user for the required permissions at start and features video preview before starting the video recording.

(In addition, I find the code really beautiful (and this is very rare for me ^^), but that's just my subjective opinion.)

What is the difference between Select and Project Operations

Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate. The predicate is a user defined condition to select rows of user's choice.

Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT Operation.

See more : Relational Algebra and its operations

How to select from subquery using Laravel Query Builder?

In addition to @delmadord's answer and your comments:

Currently there is no method to create subquery in FROM clause, so you need to manually use raw statement, then, if necessary, you will merge all the bindings:

$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
    ->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
    ->count();

Mind that you need to merge bindings in correct order. If you have other bound clauses, you must put them after mergeBindings:

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )

    // ->where(..) wrong

    ->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder

    // ->where(..) correct

    ->count();

How to pass prepareForSegue: an object

Sometimes it is helpful to avoid creating a compile-time dependency between two view controllers. Here's how you can do it without caring about the type of the destination view controller:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.destinationViewController respondsToSelector:@selector(setMyData:)]) {
        [segue.destinationViewController performSelector:@selector(setMyData:) 
                                              withObject:myData];
    } 
}

So as long as your destination view controller declares a public property, e.g.:

@property (nonatomic, strong) MyData *myData;

you can set this property in the previous view controller as I described above.

Could not find a part of the path ... bin\roslyn\csc.exe

Issue

Be aware that the NuGet PM breaks the Rosalyn behavior. Click Tools > NuGet Package Manager > Manage NuGet Packages for Solution If an update Exists for Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Microsoft.Net.Compilers, or Microsoft.Net.Compilers.netcore, update them and the Solution will break! This occurs because the ASP Sites templates are set to use specific versions at project creation. To See the problem, click Show All Files in the Solution Explorer.

Fix

At project creation the $(WebProjectOutputDir)\bin doesn't exist, therefore when Rosalyn is added as a dependency by NuGet it installs it properly. After Updating the Solution Packages, the $(WebProjectOutputDir)\bin directory looks like so:

$(WebProjectOutputDir)\bin\bin\rosalyn

The easiest fix is to Cut & Paste rosalyn to the proper location, and then delete the extra bin folder. You can now Refresh the page and the site will load.

$watch an object

The reason why your code doesn't work is because $watch by default does reference check. So in a nutshell it make sure that the object which is passed to it is new object. But in your case you are just modifying some property of form object not creating a new one. In order to make it work you can pass true as the third parameter.

$scope.$watch('form', function(newVal, oldVal){
    console.log('invoked');
}, true);

It will work but You can use $watchCollection which will be more efficient then $watch because $watchCollection will watch for shallow properties on form object. E.g.

$scope.$watchCollection('form', function (newVal, oldVal) {
    console.log(newVal, oldVal);
});

Get the first item from an iterable that matches a condition

This question already has great answers. I'm only adding my two cents because I landed here trying to find a solution to my own problem, which is very similar to the OP.

If you want to find the INDEX of the first item matching a criteria using generators, you can simply do:

next(index for index, value in enumerate(iterable) if condition)

How to create a custom scrollbar on a div (Facebook style)

If you're looking for a Facebook like scroll bar, then I'd highly recommend you take a look at this one:

http://rocha.la/jQuery-slimScroll

android asynctask sending callbacks to ui

I will repeat what the others said, but will just try to make it simpler...

First, just create the Interface class

public interface PostTaskListener<K> {
    // K is the type of the result object of the async task 
    void onPostTask(K result);
}

Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.

public static class LoadData extends AsyncTask<Void, Void, String> {

    private PostTaskListener<String> postTaskListener;

    protected LoadData(PostTaskListener<String> postTaskListener){
        this.postTaskListener = postTaskListener;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null && postTaskListener != null)
            postTaskListener.onPostTask(result);
    }
}

Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:

...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
    @Override
    public void onPostTask(String result) {
        //Your post execution task code
    }
}

// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);

Done!

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

Or you could do this from NuGet Package Manager Console

 Install-Package Microsoft.AspNet.WebApi -Version 5.0.0

And then you will be able to add the reference to System.Web.Http.WebHost 5.0

Why is a ConcurrentModificationException thrown and how to debug it

I ran into this exception when try to remove x last items from list. myList.subList(lastIndex, myList.size()).clear(); was the only solution that worked for me.

Async/Await Class Constructor

You may immediately invoke an anonymous async function that returns message and set it to the message variable. You might want to take a look at immediately invoked function expressions (IEFES), in case you are unfamiliar with this pattern. This will work like a charm.

var message = (async function() { return await grabUID(uid) })()

HTML how to clear input using javascript?

instead of clearing the name text use placeholder attribute it is good practice

<input type="text" placeholder="name"  name="name">

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

PostgreSQL column 'foo' does not exist

You accidentally created the column name with a trailing space and presumably phpPGadmin created the column name with double quotes around it:

create table your_table (
    "foo " -- ...
)

That would give you a column that looked like it was called foo everywhere but you'd have to double quote it and include the space whenever you use it:

select ... from your_table where "foo " is not null

The best practice is to use lower case unquoted column names with PostgreSQL. There should be a setting in phpPGadmin somewhere that will tell it to not quote identifiers (such as table and column names) but alas, I don't use phpPGadmin so I don't where that setting is (or even if it exists).

Asserting successive calls to a mock method

Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call with an assertion about call_count.

>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
    '%s call not found' % expected_string
AssertionError: mock(4) call not found

I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.

If you do care about order or you expect multiple identical calls, assert_has_calls might be more appropriate.

Edit

Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.

Enable IIS7 gzip

If you are also trying to gzip dynamic pages (like aspx) and it isnt working, its probably because the option is not enabled (you need to install the Dynamic Content Compression module using Windows Features):

http://support.esri.com/en/knowledgebase/techarticles/detail/38616

How can I get table names from an MS Access Database?

Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.

See:

OpenSchema Method (ADO)

Supported Schema Rowsets

EC2 instance has no public DNS

There is a actually a setting in the VPC called "DNS Hostnames". You can modify the VPC in which the EC2 instance exists, and change this to "Yes". That should do the trick.

I ran into this issue yesterday and tried the above answer from Manny, which did not work. The VPC setting, however, did work for me.

Ultimately I added an EIP and I use that to connect.

SOAP-UI - How to pass xml inside parameter

Either encode the needed XML entities or use CDATA.

<arg0>
    <!--Optional:-->
    <parameter1>&lt;test>like this&lt;/test></parameter1>
    <!--Optional:-->
    <parameter2><![CDATA[<test>or like this</test>]]></parameter2>
 </arg0>

ArrayList vs List<> in C#

Simple Answer is,

ArrayList is Non-Generic

  • It is an Object Type, so you can store any data type into it.
  • You can store any values (value type or reference type) such string, int, employee and object in the ArrayList. (Note and)
  • Boxing and Unboxing will happen.
  • Not type safe.
  • It is older.

List is Generic

  • It is a Type of Type, so you can specify the T on run-time.
  • You can store an only value of Type T (string or int or employee or object) based on the declaration. (Note or)
  • Boxing and Unboxing will not happen.
  • Type safe.
  • It is newer.

Example:

ArrayList arrayList = new ArrayList();
List<int> list = new List<int>();

arrayList.Add(1);
arrayList.Add("String");
arrayList.Add(new object());


list.Add(1);
list.Add("String");                 // Compile-time Error
list.Add(new object());             // Compile-time Error

Please read the Microsoft official document: https://blogs.msdn.microsoft.com/kcwalina/2005/09/23/system-collections-vs-system-collection-generic-and-system-collections-objectmodel/

enter image description here

Note: You should know Generics before understanding the difference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

Is it possible to specify condition in Count()?

Assuming you do not want to restrict the rows that are returned because you are aggregating other values as well, you can do it like this:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount
from ...

Let's say within the same column you had values of Manager, Supervisor, and Team Lead, you could get the counts of each like this:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount,
    count(case when Position = 'Supervisor' then 1 else null end) as SupervisorCount,
    count(case when Position = 'Team Lead' then 1 else null end) as TeamLeadCount,
from ...

How can I set response header on express.js assets

There is at least one middleware on npm for handling CORS in Express: cors. [see @mscdex answer]

This is how to set custom response headers, from the ExpressJS DOC

res.set(field, [value])

Set header field to value

res.set('Content-Type', 'text/plain');

or pass an object to set multiple fields at once.

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  'ETag': '12345'
})

Aliased as

res.header(field, [value])

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

How to remove default mouse-over effect on WPF buttons?

The Muffin Man had a very simple answer which worked for me.

To add a little more specific direction, at least for VS 2013:

  • Right-click the control
  • Select Edit Template => Edit a copy...
  • I selected 'Application' for where to save the style
    • From here you can directly edit App.xaml and see the intuitively named properties. For my purposes, I just set RenderMouseOver="False"
  • Then, in the MainWindow.xaml or wherever your GUI is, you can paste the new style at the end of the Button tag, e.g. ... Style="{DynamicResource MouseOverNonDefault}"/>

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

Encode URL in JavaScript?

Here is a LIVE DEMO of encodeURIComponent() and decodeURIComponent() JS built in functions:

<!DOCTYPE html>
<html>
  <head>
    <style>
      textarea{
        width:30%;
        height:100px;
      }
    </style>
    <script>
      // encode string to base64
      function encode()
      {
        var txt = document.getElementById("txt1").value;
        var result = btoa(txt);
        document.getElementById("txt2").value = result;
      }
      // decode base64 back to original string
      function decode()
      {
        var txt = document.getElementById("txt3").value;
        var result = atob(txt);
        document.getElementById("txt4").value = result;
      }
    </script>
  </head>
  <body>
    <div>
      <textarea id="txt1">Some text to decode
      </textarea>
    </div>
    <div>
      <input type="button" id="btnencode" value="Encode" onClick="encode()"/>
    </div>
    <div>
      <textarea id="txt2">
      </textarea>
    </div>
    <br/>
    <div>
      <textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
      </textarea>
    </div>
    <div>
      <input type="button" id="btndecode" value="Decode" onClick="decode()"/>
    </div>
    <div>
      <textarea id="txt4">
      </textarea>
    </div>
  </body>
</html>

Pandas Replace NaN with blank/empty string

If you are reading the dataframe from a file (say CSV or Excel) then use :

  • df.read_csv(path , na_filter=False)
  • df.read_excel(path , na_filter=False)

This will automatically consider the empty fields as empty strings ''


If you already have the dataframe

  • df = df.replace(np.nan, '', regex=True)
  • df = df.fillna('')

How to check cordova android version of a cordova/phonegap project?

For getting all the info about the cordova package use this command:

npm info cordova

how to convert a string to a bool

bool b = str.Equals("1")? true : false;

Or even better, as suggested in a comment below:

bool b = str.Equals("1");

Unit testing with mockito for constructors

You can use PowerMockito

See the example:

Second second = Mockito.mock(Second.class);
whenNew(Second.class).withNoArguments().thenReturn(second);

But re-factoring is better decision.

Drawing a line/path on Google Maps

It is really easy with Google Maps Android API v2

Just copy the example from Developer documentation

(of course you have to init your map first)

GoogleMap map;
 // ... get a map.
 // Add a thin red line from London to New York.
 Polyline line = map.addPolyline(new PolylineOptions()
     .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
     .width(5)
     .color(Color.RED));

Has anyone gotten HTML emails working with Twitter Bootstrap?

What about Bootstrap Email? This seems to really nice and compatible with bootstrap 4.

Autonumber value of last inserted row - MS Access / VBA

In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:

  Dim query As String
  Dim newRow As Long  ' note change of data type
  Dim db As DAO.Database

  query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
  Set db = CurrentDB
  db.Execute(query)
  newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
  Set db = Nothing

I used to do INSERTs by opening an AddOnly recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

.Cells(.Rows.Count,"A").End(xlUp).row

I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:

.Cells(Rows.Count,"A").End(xlUp).row

Before the Cells, you can write your worksheet name, for example:

Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row

The worksheet name is not necessary when you operate on the same worksheet.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I'm consciously writing this answer to an old question with this in mind, because the other answers didn't help me.

I got the Illegal Instruction: 4 while running the binary on the same system I had compiled it on, so -mmacosx-version-min didn't help.

I was using gcc in Code Blocks 16 on Mac OS X 10.11.

However, turning off all of Code Blocks' compiler flags for optimization worked. So look at all the flags Code Blocks set (right-click on the Project -> "Build Properties") and turn off all the flags you are sure you don't need, especially -s and the -Oflags for optimization. That did it for me.

Make element fixed on scroll

I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.

window.addEventListener('scroll', function (evt) {

  // This value is your scroll distance from the top
  var distance_from_top = document.body.scrollTop;

  // The user has scrolled to the tippy top of the page. Set appropriate style.
  if (distance_from_top === 0) {

  }

  // The user has scrolled down the page.
  if(distance_from_top > 0) {

  }

});

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

Node is missing from the SYSTEM PATH, try this in your command line

SET PATH=C:\Program Files\Nodejs;%PATH%

and then try running node

To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm

To be very clean, create a new system variable NODEJS

NODEJS="C:\Program Files\Nodejs"

Then edit the PATH in system variables and add %NODEJS%

PATH=%NODEJS%;...

How to implement the Java comparable interface?

You need to:

  • Add implements Comparable<Animal> to the class declaration; and
  • Implement a int compareTo( Animal a ) method to perform the comparisons.

Like this:

public class Animal implements Comparable<Animal>{
    public String name;
    public int year_discovered; 
    public String population; 

    public Animal(String name, int year_discovered, String population){
        this.name = name;
        this.year_discovered = year_discovered;
        this.population = population;
    }

    public String toString(){
     String s = "Animal name: "+ name+"\nYear Discovered: "+year_discovered+"\nPopulation: "+population;
     return s;
    }

    @Override
    public int compareTo( final Animal o) {
        return Integer.compare(this.year_discovered, o.year_discovered);
    }
}

Eclipse/Maven error: "No compiler is provided in this environment"

Installed JRE In my case I solved the problem by removing duplicates of names, I kept only one with the name: jdk.1.8.0_101

Count number of lines in a git repository

The best solution, to me anyway, is buried in the comments of @ephemient's answer. I am just pulling it up here so that it doesn't go unnoticed. The credit for this should go to @FRoZeN (and @ephemient).

git diff --shortstat `git hash-object -t tree /dev/null`

returns the total of files and lines in the working directory of a repo, without any additional noise. As a bonus, only the source code is counted - binary files are excluded from the tally.

The command above works on Linux and OS X. The cross-platform version of it is

git diff --shortstat 4b825dc642cb6eb9a060e54bf8d69288fbee4904

That works on Windows, too.

For the record, the options for excluding blank lines,

  • -w/--ignore-all-space,
  • -b/--ignore-space-change,
  • --ignore-blank-lines,
  • --ignore-space-at-eol

don't have any effect when used with --shortstat. Blank lines are counted.

live output from subprocess command

TLDR for Python 3:

import subprocess
import sys
with open('test.log', 'wb') as f: 
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for c in iter(lambda: process.stdout.read(1), b''): 
        sys.stdout.buffer.write(c)
        f.buffer.write(c)

You have two ways of doing this, either by creating an iterator from the read or readline functions and do:

import subprocess
import sys
with open('test.log', 'w') as f:  # replace 'w' with 'wb' for Python 3
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for c in iter(lambda: process.stdout.read(1), ''):  # replace '' with b'' for Python 3
        sys.stdout.write(c)
        f.write(c)

or

import subprocess
import sys
with open('test.log', 'w') as f:  # replace 'w' with 'wb' for Python 3
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for line in iter(process.stdout.readline, ''):  # replace '' with b'' for Python 3
        sys.stdout.write(line)
        f.write(line)

Or you can create a reader and a writer file. Pass the writer to the Popen and read from the reader

import io
import time
import subprocess
import sys

filename = 'test.log'
with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader:
    process = subprocess.Popen(command, stdout=writer)
    while process.poll() is None:
        sys.stdout.write(reader.read())
        time.sleep(0.5)
    # Read the remaining
    sys.stdout.write(reader.read())

This way you will have the data written in the test.log as well as on the standard output.

The only advantage of the file approach is that your code doesn't block. So you can do whatever you want in the meantime and read whenever you want from the reader in a non-blocking way. When you use PIPE, read and readline functions will block until either one character is written to the pipe or a line is written to the pipe respectively.

Postgres and Indexes on Foreign Keys and Primary Keys

If you want to list the indexes of all the tables in your schema(s) from your program, all the information is on hand in the catalog:

select
     n.nspname  as "Schema"
    ,t.relname  as "Table"
    ,c.relname  as "Index"
from
          pg_catalog.pg_class c
     join pg_catalog.pg_namespace n on n.oid        = c.relnamespace
     join pg_catalog.pg_index i     on i.indexrelid = c.oid
     join pg_catalog.pg_class t     on i.indrelid   = t.oid
where
        c.relkind = 'i'
    and n.nspname not in ('pg_catalog', 'pg_toast')
    and pg_catalog.pg_table_is_visible(c.oid)
order by
     n.nspname
    ,t.relname
    ,c.relname

If you want to delve further (such as columns and ordering), you need to look at pg_catalog.pg_index. Using psql -E [dbname] comes in handy for figuring out how to query the catalog.

What does a question mark represent in SQL queries?

It's a parameter. You can specify it when executing query.

How to move/rename a file using an Ansible task on a remote system

I have found the creates option in the command module useful. How about this:

- name: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar

I used to do a 2 task approach using stat like Bruce P suggests. Now I do this as one task with creates. I think this is a lot clearer.

Can I have multiple Xcode versions installed?

  1. First, remove the current Xcode installation from your machine. You can probably skip this step but I wanted to start fresh. Plus — Xcode was behaving a little weird lately so this is a good opportunity to do that.
  2. Install Xcode 8 from the App Store. Make sure project files (.xcodeproj) and workspace files (.xcworkspace) can be opened with the new Xcode installation (remember to select the Later option whenever prompted).
  3. Download the Xcode 7.3.1 dmg file from Apple. Double-tap the newly downloaded dmg file in order to get the standard “Drag to install Xcode in your Applications folder”. Don’t do that. Instead, drag the Xcode icon to the desktop. Change the file name to Xcode 7.3.1. Now drag it to the Applications folder.

Now you have two versions of Xcode installed on your machine. Xcode 7.3.1 and Xcode 8.

Details: Install Xcode 7 & Xcode 8 side by side

Case insensitive 'in'

str.casefold is recommended for case-insensitive string matching. @nmichaels's solution can trivially be adapted.

Use either:

if 'MICHAEL89'.casefold() in (name.casefold() for name in USERNAMES):

Or:

if 'MICHAEL89'.casefold() in map(str.casefold, USERNAMES):

As per the docs:

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

How to set image to UIImage

Try this code to 100% work....

UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
imageview.image = [UIImage imageNamed:@"myimage.jpg"];
[self.view  addSubview:imageview];

Why can a function modify some arguments as perceived by the caller, but not others?

I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.

a = 'string'
a.replace('t', '_')
print(a)
>>> 'string'

a = a.replace('t', '_')
print(a)
>>> 's_ring'

b = 100
b + 1
print(b)
>>> 100

b = b + 1
print(b)
>>> 101

def test_id(arg):
    c = id(arg)
    arg = 123
    d = id(arg)
    return

a = 'test ids'
b = id(a)
test_id(a)
e = id(a)

# b = c  = e != d
# this function do change original value
del change_like_mutable(arg):
    arg.append(1)
    arg.insert(0, 9)
    arg.remove(2)
    return

test_1 = [1, 2, 3]
change_like_mutable(test_1)



# this function doesn't 
def wont_change_like_str(arg):
     arg = [1, 2, 3]
     return


test_2 = [1, 1, 1]
wont_change_like_str(test_2)
print("Doesn't change like a imutable", test_2)

This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.

Convert a Unicode string to an escaped ASCII string

class Program
{
        static void Main(string[] args)
        {
            char[] originalString = "This string contains the unicode character Pi(p)".ToCharArray();
            StringBuilder asAscii = new StringBuilder(); // store final ascii string and Unicode points
            foreach (char c in originalString)
            {
                // test if char is ascii, otherwise convert to Unicode Code Point
                int cint = Convert.ToInt32(c);
                if (cint <= 127 && cint >= 0)
                    asAscii.Append(c);
                else
                    asAscii.Append(String.Format("\\u{0:x4} ", cint).Trim());
            }
            Console.WriteLine("Final string: {0}", asAscii);
            Console.ReadKey();
        }
}

All non-ASCII chars are converted to their Unicode Code Point representation and appended to the final string.

Checking that a List is not empty in Hamcrest

This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));

But if you have to use older version - instead of bugged empty() you could use:

hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan; or
import static org.hamcrest.Matchers.greaterThan;)

Example:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));

The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.

SET versus SELECT when assigning variables?

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

Difference between javacore, thread dump and heap dump in Websphere

JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects.

JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads.

Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place. Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser.

Core dump is a os level memory usage of objects. It has more informaiton than a head dump. core dump is not created when we kill a process purposely.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

As I said in comment your crystaldecisions.reportappserver.commlayer.dll is not copied / present on your server. So for this you have to manually copy the dll and paste into you Bin folder

To copy a DLL from visual studio project follow the steps

1.Expand your Project's References hierarchy (Project should not be in debug mod)

2.Right Click on Particular Dll (in your case crystaldecisions.reportappserver.commlayer.dll) and select Properties and set 'Copy Local' attribute to TRUE

3 Build your project. The Dll should be there in your BIN Folder.

enter image description here

Adding one day to a date

Since you already have an answer to what's wrong with your code, I can bring another perspective on how you can play with datetimes generally, and solve your problem specifically.

Oftentimes you find yourself posing a problem in terms of solution. This is just one of the reasons you end up with an imperative code. It's great if it works though; there are just other, arguably more maintainable alternatives. One of them is a declarative code. The point is asking what you need, instead of how to get there.

In your particular case, this can look like the following. First, you need to find out what is it that you're looking for, that is, discover abstractions. In your case, it looks like you need a date. Not just any date, but the one having some standard representation. Say, ISO8601 date. There are at least two implementations: the first one is a date parsed from an ISO8601-formatted string (or a string in any other format actually), and the second is some future date which is a day later. Thus, the whole code could look like that:

(new Future(
    new DateTimeParsedFromISO8601('2009-09-30 20:24:00'),
    new OneDay()
))
    ->value();

For more examples with datetime juggling check out this one.

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

It is too late but might be it can help anyone

  1. Create unique name for every control
  2. Validate by using fromname[uniquname].$error

Sample code:

<input 
    ng-model="r.QTY" 
    class="span1" 
    name="QTY{{$index}}" 
    ng-pattern="/^[\d]*\.?[\d]*$/" required/>
<div ng-messages="formName['QTY' +$index].$error"
     ng-show="formName['QTY' +$index].$dirty || formName.$submitted">
   <div ng-message="required" class='error'>Required</div>
   <div ng-message="pattern" class='error'>Invalid Pattern</div>
</div>

See working demo here

Check if value exists in Postgres array

but if you have other ways to do it please share.

You can compare two arrays. If any of the values in the left array overlap the values in the right array, then it returns true. It's kind of hackish, but it works.

SELECT '{1}'   && '{1,2,3}'::int[];  -- true
SELECT '{1,4}' && '{1,2,3}'::int[];  -- true
SELECT '{4}'   && '{1,2,3}'::int[];  -- false
  • In the first and second query, value 1 is in the right array
  • Notice that the second query is true, even though the value 4 is not contained in the right array
  • For the third query, no values in the left array (i.e., 4) are in the right array, so it returns false

How to rotate a 3D object on axis three.js?

Somewhere around r59 this gets easier (rotate around x):

bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
    var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
    obj.position.applyEuler(euler);
}

Laravel: How do I parse this json data in view blade?

For such case, you can do like this

@foreach (json_decode($leads->member) as $member)
     {{ $genre }}
@endforeach

How to get response status code from jQuery.ajax?

I see the status field on the jqXhr object, here is a fiddle with it working:

http://jsfiddle.net/magicaj/55HQq/3/

$.ajax({
    //...        
    success: function(data, textStatus, xhr) {
        console.log(xhr.status);
    },
    complete: function(xhr, textStatus) {
        console.log(xhr.status);
    } 
});

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

How to Find Item in Dictionary Collection?

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

The basic solution would be:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

But that requires 2 lookups.

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

How to test if a double is an integer

Similar to SkonJeet's answer above, but the performance is better (at least in java):

Double zero = 0d;    
zero.longValue() == zero.doubleValue()

can you add HTTPS functionality to a python flask web server?

  • To run https functionality or SSL authentication in flask application you first install "pyOpenSSL" python package using:

     pip install pyopenssl
    
  • Next step is to create 'cert.pem' and 'key.pem' using following command on terminal :

     openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
    
  • Copy generated 'cert.pem' and 'kem.pem' in you flask application project

  • Add ssl_context=('cert.pem', 'key.pem') in app.run()

For example:

    from flask import Flask, jsonify

    app = Flask(__name__)

    @app.route('/')

    def index():

        return 'Flask is running!'


    @app.route('/data')

    def names():

        data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}

        return jsonify(data)

  if __name__ == '__main__':

        app.run(ssl_context=('cert.pem', 'key.pem'))

Improve subplot size/spacing with many subplots in matplotlib

Similar to tight_layout matplotlib now (as of version 2.2) provides constrained_layout. In contrast to tight_layout, which may be called any time in the code for a single optimized layout, constrained_layout is a property, which may be active and will optimze the layout before every drawing step.

Hence it needs to be activated before or during subplot creation, such as figure(constrained_layout=True) or subplots(constrained_layout=True).

Example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(4,4, constrained_layout=True)

plt.show()

enter image description here

constrained_layout may as well be set via rcParams

plt.rcParams['figure.constrained_layout.use'] = True

See the what's new entry and the Constrained Layout Guide

How do I create a MongoDB dump of my database?

You can also use gzip for taking backup of one collection and compressing the backup on the fly:

mongodump --db somedb --collection somecollection --out - | gzip > collectiondump.gz

or with a date in the file name:

mongodump --db somedb --collection somecollection --out - | gzip > dump_`date "+%Y-%m-%d"`.gz

Update:
Backup all collections of a database in a date folder. The files are gziped:

mongodump --db somedb --gzip --out /backups/`date +"%Y-%m-%d"`

Or for a single archive:

mongodump --db somedb --gzip --archive > dump_`date "+%Y-%m-%d"`.gz

Or when mongodb is running inside docker:

docker exec <CONTAINER> sh -c 'exec mongodump --db somedb --gzip --archive' > dump_`date "+%Y-%m-%d"`.gz

how to install tensorflow on anaconda python 3.6

conda create -n tensorflow_gpuenv tensorflow-gpu

Or

type the command pip install c:.*.whl in command prompt (cmd).

Replacing Spaces with Underscores

$name = str_replace(' ', '_', $name);

Android, How to read QR code in my application?

Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!

How to restart service using command prompt?

To restart a running service:

net stop "service name" && net start "service name"

However, if you don't know if the service is running in the first place and want to restart or start it, use this:

net stop "service name" & net start "service name"

This works if the service is already running or not.

For reference, here is the documentation on conditional processing symbols.

Using BufferedReader to read Text File

This is the problem:

while (br.readLine() != null) {
    System.out.println(br.readLine());
}

You've got two calls to readLine - the first only checks that there's a line (but reads it and throws it away) and the second reads the next line. You want:

String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

Now we're only calling readLine() once per loop iteration, and using the line that we've read both for the "have we finished?" and "print out the line" parts.

Setting onClickListener for the Drawable right of an EditText

I know this is quite old, but I recently had to do something very similar, and came up with a much simpler solution.

It boils down to the following steps:

  1. Create an XML layout that contains the EditText and Image
  2. Subclass FrameLayout and inflate the XML layout
  3. Add code for the click listener and any other behavior you want... without having to worry about positions of the click or any other messy code.

See this post for the full example: Handling click events on a drawable within an EditText

How to change maven logging level to display only warning and errors?

I have noticed when using the 2.20.1 version of the maven sunfire plugin, all warnings are written down to a dumpstream file. e.g. /myproject/target/surefire-reports/2017-11-11T23-02-19_850.dumpstream

Differences in boolean operators: & vs && and | vs ||

Maybe it can be useful to know that the bitwise AND and bitwise OR operators are always evaluated before conditional AND and conditional OR used in the same expression.

if ( (1>2) && (2>1) | true) // false!

Adding devices to team provisioning profile

As of Sept 2018, Apple seems to (or a bug) block the normal way to get your XS and XS Max's UDID. Even XCode could not properly register new phones for you.

After a couple hours of digging, I figure it out:

  • Connect your iPhone to your Mac.
  • Navigate to ? -> About This Mac.
  • Click on System Report and select USB.
  • Click on iPhone, and copy the value next to the Serial Number label.
  • Copy and paste the value. You then need to add a – after the 8th digit.
  • This is the UDID for the iPhone XS and iPhone XS Max.

Source

How do I tell CMake to link in a static library in the source directory?

CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}, doing the following should succeed:

add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

I use codeigniter 3+. I had the same problem and in my case I changed model file name starting from uppser case.

Logon_model.php

HTTP response code for POST when resource already exists

"302 Found" sounds logical for me. And the RFC 2616 says that it CAN be answered for other requests than GET and HEAD (and this surely includes POST)

But it still keeps the visitor going to this URL to get this "Found" resource, by the RFC. To make it to go directly to the real "Found" URL one should be using "303 See Other", which makes sense, but forces another call to GET its following URL. On the good side, this GET is cacheable.

I think that I would use "303 See Other". I dont know if I can respond with the "thing" found in the body, but I would like to do so to save one roundtrip to the server.

UPDATE: After re-reading the RFC, I still think that an inexistent "4XX+303 Found" code should be the correct. However, the "409 Conflict" is the best existing answer code (as pointed by @Wrikken), maybe including a Location header pointing to the existing resource.

unix diff side-to-side results?

You should have sdiff for side-by-side merge of file differences. Take a read of man sdiff for the full story.

Getting current date and time in JavaScript

You need to use getDate() to get the date part. The getDay() function returns the day number (Sunday = 0, Monday = 1...), and the getMonth() returns a 0 based index, so you need to increment it by 1.

 var currentdate = new Date(); 

 var datetime = "Last Sync: " + currentdate.getDate() + "/"+  (parseInt(currentdate.getMonth())    + 1)
   + "/" + currentdate.getFullYear() + " @ "  
   + currentdate.getHours() + ":"  
   + currentdate.getMinutes() + ":" + currentdate.getSeconds(); 

Oracle Differences between NVL and Coalesce

There is also difference is in plan handling.

Oracle is able form an optimized plan with concatenation of branch filters when search contains comparison of nvl result with an indexed column.

create table tt(a, b) as
select level, mod(level,10)
from dual
connect by level<=1e4;

alter table tt add constraint ix_tt_a primary key(a);
create index ix_tt_b on tt(b);

explain plan for
select * from tt
where a=nvl(:1,a)
  and b=:2;

explain plan for
select * from tt
where a=coalesce(:1,a)
  and b=:2;

nvl:

-----------------------------------------------------------------------------------------
| Id  | Operation                     | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT              |         |     2 |    52 |     2   (0)| 00:00:01 |
|   1 |  CONCATENATION                |         |       |       |            |          |
|*  2 |   FILTER                      |         |       |       |            |          |
|*  3 |    TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | IX_TT_B |     7 |       |     1   (0)| 00:00:01 |
|*  5 |   FILTER                      |         |       |       |            |          |
|*  6 |    TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  7 |     INDEX UNIQUE SCAN         | IX_TT_A |     1 |       |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   2 - filter(:1 IS NULL)
   3 - filter("A" IS NOT NULL)
   4 - access("B"=TO_NUMBER(:2))
   5 - filter(:1 IS NOT NULL)
   6 - filter("B"=TO_NUMBER(:2))
   7 - access("A"=:1)

coalesce:

---------------------------------------------------------------------------------------
| Id  | Operation                   | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |         |     1 |    26 |     1   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | IX_TT_B |    40 |       |     1   (0)| 00:00:01 |
---------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("A"=COALESCE(:1,"A"))
   2 - access("B"=TO_NUMBER(:2))

Credits go to http://www.xt-r.com/2012/03/nvl-coalesce-concatenation.html.

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Font awesome use SVG icons. So, you can resize it for your requirment.

just use CSS class for that,

    .large-icon{
       font-size:10em;
       //or
      font-size:200%;
      //or
      font-size:50px;
    }