Programs & Examples On #Signature files

A signature file contains information about the public signatures of a set of F# program elements, such as types, namespaces, and modules. It can be used to specify the accessibility of these program elements.

How do I list the symbols in a .so file

For C++ .so files, the ultimate nm command is nm --demangle --dynamic --defined-only --extern-only <my.so>

# nm --demangle --dynamic --defined-only --extern-only /usr/lib64/libqpid-proton-cpp.so | grep work | grep add
0000000000049500 T proton::work_queue::add(proton::internal::v03::work)
0000000000049580 T proton::work_queue::add(proton::void_function0&)
000000000002e7b0 W proton::work_queue::impl::add_void(proton::internal::v03::work)
000000000002b1f0 T proton::container::impl::add_work_queue()
000000000002dc50 T proton::container::impl::container_work_queue::add(proton::internal::v03::work)
000000000002db60 T proton::container::impl::connection_work_queue::add(proton::internal::v03::work)

source: https://stackoverflow.com/a/43257338

Change value of input placeholder via model?

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

For a more generic and extensible way check mergedict. It uses singledispatch and can merge values based on its types.

Example:

from mergedict import MergeDict

class SumDict(MergeDict):
    @MergeDict.dispatch(int)
    def merge_int(this, other):
        return this + other

d2 = SumDict({'a': 1, 'b': 'one'})
d2.merge({'a':2, 'b': 'two'})

assert d2 == {'a': 3, 'b': 'two'}

AES vs Blowfish for file encryption

It is a not-often-acknowledged fact that the block size of a block cipher is also an important security consideration (though nowhere near as important as the key size).

Blowfish (and most other block ciphers of the same era, like 3DES and IDEA) have a 64 bit block size, which is considered insufficient for the large file sizes which are common these days (the larger the file, and the smaller the block size, the higher the probability of a repeated block in the ciphertext - and such repeated blocks are extremely useful in cryptanalysis).

AES, on the other hand, has a 128 bit block size. This consideration alone is justification to use AES instead of Blowfish.

Can't find bundle for base name

If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .

Linq with group by having count

Below solution may help you.

var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
   UnmanagedAssetRegistryID = grouped.Key,
   Count = grouped.Count()
};

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

Write to file, but overwrite it if it exists

The >> redirection operator will append lines to the end of the specified file, where-as the single greater than > will empty and overwrite the file.

echo "text" > 'Users/Name/Desktop/TheAccount.txt'

.gitignore file for java eclipse project

put .gitignore in your main catalog

git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push

Compare given date with today

strtotime($var);

Turns it into a time value

time() - strtotime($var);

Gives you the seconds since $var

if((time()-(60*60*24)) < strtotime($var))

Will check if $var has been within the last day.

Openssl is not recognized as an internal or external command

Downloads and Unzip

You can download openssl for windows 32 and 64 bit from the respective links below:

https://code.google.com/archive/p/openssl-for-windows/downloads

OpenSSL for 64 Bits OpenSSL for 32 Bits

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | **"C:\Users\keshav.gera\openssl-0.9.8k_X64\bin**\openssl.exe" sha1 -binary | **"C:\Users\keshav.gera\openssl-0.9.8k_X64\bin**\openssl.exe" base64

Important change our path Here as well as install open ssl in your system

It's Working No Doubt

C:\Users\keshav.gera>keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | "C:\Users\keshav.gera\openssl-0.9.8k_X64\bin\openssl.exe" sha1 -binary | "C:\Users\keshav.gera\openssl-0.9.8k_X64\bin\openssl.exe" base64

Enter keystore password: android

**ZrRtxw36xWNYL+h3aJdcCeQQxi0=**

=============================================================

using Manually through Coding

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


private void PrintHashKey() {

        try {
            PackageInfo info = getPackageManager().getPackageInfo("**com.keshav.patanjalidemo  Your Package Name Here**", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");        
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

java.net.URL read stream to byte[]

Here's a clean solution:

private byte[] downloadUrl(URL toDownload) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        byte[] chunk = new byte[4096];
        int bytesRead;
        InputStream stream = toDownload.openStream();

        while ((bytesRead = stream.read(chunk)) > 0) {
            outputStream.write(chunk, 0, bytesRead);
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return outputStream.toByteArray();
}

How do I print a list of "Build Settings" in Xcode project?

In case you would like to read/check your Target Build Settings in runtime using code, here is the way:

1) Add a Run Script:

cp ${PROJECT_FILE_PATH}/project.pbxproj ${CONFIGURATION_BUILD_DIR}/${EXECUTABLE_NAME}.app/BuildSetting.pbxproj 

It will copy the Target Build Settings file into your Main Bundle (will be called BuildSetting.pbxproj).

2) You can now check the contents of that file at any time in code:

NSString *thePathString = [[NSBundle mainBundle] pathForResource:@"BuildSetting" ofType:@"pbxproj"];
NSDictionary *theDictionary = [NSDictionary dictionaryWithContentsOfFile:thePathString];

Write bytes to file

If I understand you correctly, this should do the trick. You'll need add using System.IO at the top of your file if you don't already have it.

public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
    try
    {
        using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            fs.Write(byteArray, 0, byteArray.Length);
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in process: {0}", ex);
        return false;
    }
}

Ubuntu apt-get unable to fetch packages

I recently had an issue with apt-get update getting stuck at 0%;

0% [Connecting to security.ubuntu.com (2001:67c:1360:8001::21)]

Could be some sort of DNS issue on ipv6. I just add this as a workaround;

-o Acquire::ForceIPv4=true

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

Select mysql query between date?

select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()

or using >= and <= :

select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()

How exactly to use Notification.Builder

It works even in API 8 you can use this code:

 Notification n = 
   new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe), 
System.currentTimeMillis());

PendingIntent i=PendingIntent.getActivity(this, 0,
             new Intent(this, NotifyActivity.class),
                               0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;

// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr = 
   (NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);

Or I suggest to follow an excellent tutorial about this

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

Unable to convert MySQL date/time value to System.DateTime

You must add Convert Zero Datetime=True to your connection string, for example:

server=localhost;User Id=root;password=mautauaja;Persist Security Info=True;database=test;Convert Zero Datetime=True

Unit Testing: DateTime.Now

Regarding to @crabcrusherclamcollector answer there is issue when using that approach in EF queries (System.NotSupportedException: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities). I modified implementation to that:

public static class SystemTime
    {
        private static Func<DateTime> UtcNowFunc = () => DateTime.UtcNow;

        public static void SetDateTime(DateTime dateTimeNow)
        {
            UtcNowFunc = () => dateTimeNow;
        }

        public static void ResetDateTime()
        {
            UtcNowFunc = () => DateTime.UtcNow;
        }

        public static DateTime UtcNow
        {
            get
            {
                DateTime now = UtcNowFunc.Invoke();
                return now;
            }
        }
    }

node.js require() cache - possible to invalidate?

I am not 100% certain of what you mean by 'invalidate', but you can add the following above the require statements to clear the cache:

Object.keys(require.cache).forEach(function(key) { delete require.cache[key] })

Taken from @Dancrumb's comment here

Java "user.dir" property - what exactly does it mean?

user.dir is the "User working directory" according to the Java Tutorial, System Properties

How can I install a local gem?

Go to the path in where the gem is and call gem install -l gemname.gem

Iterate over values of object

In the sense I think you intended, in ES5 or ES2015, no, not without some work on your part.

In ES2016, probably with object.values.

Mind you Arrays in JavaScript are effectively a map from an integer to a value, and the values in JavaScript arrays can be enumerated directly.

['foo', 'bar'].forEach(v => console.log(v)); // foo bar

Also, in ES2015, you can make an object iterable by placing a function on a property with the name of Symbol.iterator:

var obj = { 
    foo: '1', 
    bar: '2',
    bam: '3',
    bat: '4',
};

obj[Symbol.iterator] = iter.bind(null, obj);

function* iter(o) {
    var keys = Object.keys(o);
    for (var i=0; i<keys.length; i++) {
        yield o[keys[i]];
    }
}

for(var v of obj) { console.log(v); } // '1', '2', '3', '4'

Also, per other answers, there are other built-ins that provide the functionality you want, like Map (but not WeakMap because it is not iterable) and Set for example (but these are not present in all browsers yet).

How do I verify that a string only contains letters, numbers, underscores and dashes?

 pat = re.compile ('[^\w-]')

 def onlyallowed(s):
    return not pat.search (s)

How do I get the last word in each line with bash

tldr;

$ awk '{print $NF}' file.txt | paste -sd, | sed 's/,/, /g'

For a file like this

$ cat file.txt
The quick brown fox
jumps over
the lazy dog.

the given command will print

fox, over, dog.

How it works:

  • awk '{print $NF}' : prints the last field of every line
  • paste -sd, : reads stdin serially (-s, one file at a time) and writes fields comma-delimited (-d,)
  • sed 's/,/, /g' : substitutes "," with ", " globally (for all instances)

References:

PHP FPM - check if running

Assuming you are on Linux, check if php-fpm is running by searching through the process list:

ps aux | grep php-fpm

If running over IP (as opposed to over Unix socket) then you can also check for the port:

netstat -an | grep :9000

Or using nmap:

nmap localhost -p 9000

Lastly, I've read that you can request the status, but in my experience this has proven unreliable:

/etc/init.d/php5-fpm status

Oracle SQL: Update a table with data from another table

BEGIN
For i in (select id, name, desc from table2) 
LOOP
Update table1 set name = i.name, desc = i.desc where id = i.id and (name is null or desc is null);
END LOOP;
END;

Construct pandas DataFrame from items in nested dictionary

A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict, using the option orient='index':

user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
                  'Category 2': {'att_1': 23, 'att_2': 'another'}},
             15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
                  'Category 2': {'att_1': 30, 'att_2': 'bar'}}}

pd.DataFrame.from_dict({(i,j): user_dict[i][j] 
                           for i in user_dict.keys() 
                           for j in user_dict[i].keys()},
                       orient='index')


               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

An alternative approach would be to build your dataframe up by concatenating the component dataframes:

user_ids = []
frames = []

for user_id, d in user_dict.iteritems():
    user_ids.append(user_id)
    frames.append(pd.DataFrame.from_dict(d, orient='index'))

pd.concat(frames, keys=user_ids)

               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

How to check if pytorch is using the GPU?

Almost all answers here reference torch.cuda.is_available(). However, that's only one part of the coin. It tells you whether the GPU (actually CUDA) is available, not whether it's actually being used. In a typical setup, you would set your device with something like this:

device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

but in larger environments (e.g. research) it is also common to give the user more options, so based on input they can disable CUDA, specify CUDA IDs, and so on. In such case, whether or not the GPU is used is not only based on whether it is available or not. After the device has been set to a torch device, you can get its type property to verify whether it's CUDA or not.

if device.type == 'cuda':
    # do something

How can I center <ul> <li> into div

To center a block object (e.g. the ul) you need to set a width on it and then you can set that objects left and right margins to auto.

To center the inline content of block object (e.g. the inline content of li) you can set the css property text-align: center;.

Error on renaming database in SQL Server 2008 R2

  1. Set the database to single mode:

    ALTER DATABASE dbName
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    
  2. Try to rename the database:

    ALTER DATABASE dbName MODIFY NAME = NewName
    
  3. Set the database to Multiuser mode:

    ALTER DATABASE NewName
    SET MULTI_USER WITH ROLLBACK IMMEDIATE
    

Run a single migration file

Looks like at least in the latest Rails release (5.2 at the time of writing) there is one more way of filtering the migrations being ran. One can pass a filter in a SCOPE environment variable which would be then used to select migration files.

Assuming you have two migration files 1_add_foos.rb and 2_add_foos.run_this_one.rb running

SCOPE=run_this_one rails db:migrate:up

will select and run only 2_add_foos.run_this_one.rb. Keep in mind that all migration files matching the scope will be ran.

Receiving login prompt using integrated windows authentication

I had the same problem cause the user (Identity) that I used in the application pool was not belowing to IIS_IUSRS group. Added the user to the group and everything work

Fastest way to iterate over all the chars in a String

String.toCharArray() creates new char array, means allocation of memory of string length, then copies original char array of string using System.arraycopy() and then returns this copy to caller. String.charAt() returns character at position i from original copy, that's why String.charAt() will be faster than String.toCharArray(). Although, String.toCharArray() returns copy and not char from original String array, where String.charAt() returns character from original char array. Code below returns value at the specified index of this string.

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

code below returns a newly allocated character array whose length is the length of this string

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

Using Chrome's Element Inspector in Print Preview Mode?

If you are debugging your CSS using Print As PDF in Google Chrome and your CSS element background colors are not showing, then make sure the 'Background graphics' checkbox is ticked. I spent almost 30 minutes debugging my CSS and wondering what is causing my CSS background being ignored.

Google Chrome Print background color ignored

How to detect Windows 64-bit platform with .NET?

Using dotPeek helps to see how the framework actually does it. With that in mind, here's what I've come up with:

public static class EnvironmentHelper
{
    [DllImport("kernel32.dll")]
    static extern IntPtr GetCurrentProcess();

    [DllImport("kernel32.dll")]
    static extern IntPtr GetModuleHandle(string moduleName);

    [DllImport("kernel32")]
    static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32.dll")]
    static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);

    public static bool Is64BitOperatingSystem()
    {
        // Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.
        if (IntPtr.Size == 8)
            return true;
        // Check if this process is an x86 process running on an x64 environment.
        IntPtr moduleHandle = GetModuleHandle("kernel32");
        if (moduleHandle != IntPtr.Zero)
        {
            IntPtr processAddress = GetProcAddress(moduleHandle, "IsWow64Process");
            if (processAddress != IntPtr.Zero)
            {
                bool result;
                if (IsWow64Process(GetCurrentProcess(), out result) && result)
                    return true;
            }
        }
        // The environment must be an x86 environment.
        return false;
    }
}

Example usage:

EnvironmentHelper.Is64BitOperatingSystem();

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

if you just want it for a cell formula without code, here's a formula for it:

IF(COLUMN()>=26,CHAR(ROUND(COLUMN()/26,1)+64)&CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Add the "code" folder to the project properties within Visual Studio

Project->Properties->Configuration Properties->C/C++->Additional Include Directories

Django Cookies, how can I set them?

Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.

Here is an example with a Django view ...

def homepage(request):

    request.session.setdefault('how_many_visits', 0)
    request.session['how_many_visits'] += 1

    print(request.session['how_many_visits'])

    return render(request, 'home.html', {})

If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.

How do I clone a job in Jenkins?

if you want to copy in same Jenkins but in different subfolders, create new item -> use copy from. new Job will be cloned in same directory. Then use move option to move it in desired directory

To the power of in C?

#include <math.h>


printf ("%d", (int) pow (3, 4));

How to stop BackgroundWorker correctly

My answer is a bit different because I've tried these methods but they didn't work. My code uses an extra class that checks for a Boolean flag in a public static class as the database values are read or where I prefer it just before an object is added to a List object or something as such. See the change in the code below. I added the ThreadWatcher.StopThread property. for this explation I'm nog going to reinstate the current thread because it's not your issue but that's as easy as setting the property to false before accessing the next thread...

private void combobox2_TextChanged(object sender, EventArgs e)
 {
  //Stop the thread here with this
     ThreadWatcher.StopThread = true;//the rest of this thread will run normally after the database function has stopped.
     if (cmbDataSourceExtractor.IsBusy)
        cmbDataSourceExtractor.CancelAsync();

     while(cmbDataSourceExtractor.IsBusy)
        Application.DoEvents();

     var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
        V2 = combobox2.Text};
     cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
  }

all fine

private void cmbDataSourceExtractor_DoWork(object sender, DoWorkEventArgs e)
 {
      if (this.cmbDataSourceExtractor.CancellationPending)
      {
          e.Cancel = true;
          return;
      }
      // do stuff...
 }

Now add the following class

public static class ThreadWatcher
{
    public static bool StopThread { get; set; }
}

and in your class where you read the database

List<SomeObject>list = new List<SomeObject>();
...
if (!reader.IsDbNull(0))
    something = reader.getString(0);
someobject = new someobject(something);
if (ThreadWatcher.StopThread == true)
    break;
list.Add(something);
...

don't forget to use a finally block to properly close your database connection etc. Hope this helps! Please mark me up if you find it helpful.

Difference between one-to-many and many-to-one relationship

There's no practical difference. Just use the relationship which makes the most sense given the way you see your problem as Devendra illustrated.

JavaScript + Unicode regexes

Having also not found a good solution, I wrote a small script a long time ago, by downloading data from the unicode specification (v.5.0.0) and generating intervals for each unicode category and subcategory in the BMP (lately replaced by a small Java program that uses its own native Unicode support).

Basically it converts \p{...} to a range of values, much like the output of the tool mentioned by Tomalak, but the intervals can end up quite large (since it's not dealing with blocks, but with characters scattered through many different places).

For instance, a Regex written like this:

var regex = unicode_hack(/\p{L}(\p{L}|\p{Nd})*/g);

Will be converted to something like this:

/[\u0041-\u005a\u0061-\u007a...]([...]|[\u0030-\u0039\u0660-\u0669...])*/g

Haven't used it a lot in practice, but it seems to work fine from my tests, so I'm posting here in case someone find it useful. Despite the length of the resulting regexes (the example above has 3591 characters when expanded), the performance seems to be acceptable (see the tests at jsFiddle; thanks to @modiX and @Lwangaman for the improvements).

Here's the source (raw, 27.5KB; minified, 24.9KB, not much better...). It might be made smaller by unescaping the unicode characters, but OTOH will run the risk of encoding issues, so I'm leaving as it is. Hopefully with ES6 this kind of thing won't be necessary anymore.

Update: this looks like the same strategy adopted in the XRegExp Unicode plug-in mentioned by Tim Down, except that in this case regular JavaScript regexes are being used.

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

Best way is to find using log, it works always

int len = ceil(log10(num))+1;

JPA entity without id

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of "entity properties" to a List in entity.

You can create the EntityProperty type and annotate it with @Embeddable

Check if all checkboxes are selected

The search criteria is one of these:

input[type=checkbox].MyClass:not(:checked)
input[type=checkbox].MyClass:checked

You probably want to connect to the change event.

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

How do I parse JSON in Android?

Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.

Get your JSON:

Assume you have a json string

String result = "{\"someKey\":\"someValue\"}";

Create a JSONObject:

JSONObject jObject = new JSONObject(result);

If your json string is an array, e.g.:

String result = "[{\"someKey\":\"someValue\"}]"

then you should use JSONArray as demonstrated below and not JSONObject

To get a specific string

String aJsonString = jObject.getString("STRINGNAME");

To get a specific boolean

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");

To get a specific integer

int aJsonInteger = jObject.getInt("INTEGERNAME");

To get a specific long

long aJsonLong = jObject.getLong("LONGNAME");

To get a specific double

double aJsonDouble = jObject.getDouble("DOUBLENAME");

To get a specific JSONArray:

JSONArray jArray = jObject.getJSONArray("ARRAYNAME");

To get the items from the array

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}

Update Git submodule to latest commit on origin

Here's an awesome one-liner to update everything to the latest on master:

git submodule foreach 'git fetch origin --tags; git checkout master; git pull' && git pull && git submodule update --init --recursive

Thanks to Mark Jaquith

Scala list concatenation, ::: vs ++

::: works only with lists, while ++ can be used with any traversable. In the current implementation (2.9.0), ++ falls back on ::: if the argument is also a List.

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this

EDIT

As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link

The right way of setting <a href=""> when it's a local file

This can happen when you are running IIS and you run the html page through it, then the Local file system will not be accessible.

To make your link work locally the run the calling html page directly from file browser not visual studio F5 or IIS simply click it to open from the file system, and make sure you are using the link like this:

<a href="file:///F:/VS_2015_WorkSpace/Projects/xyz/Intro.html">Intro</a>

How to retrieve a single file from a specific revision in Git?

Using git show

To complete your own answer, the syntax is indeed

git show object
git show $REV:$FILE
git show somebranch:from/the/root/myfile.txt
git show HEAD^^^:test/test.py

The command takes the usual style of revision, meaning you can use any of the following:

  1. branch name (as suggested by ash)
  2. HEAD + x number of ^ characters
  3. The SHA1 hash of a given revision
  4. The first few (maybe 5) characters of a given SHA1 hash

Tip It's important to remember that when using "git show", always specify a path from the root of the repository, not your current directory position.

(Although Mike Morearty mentions that, at least with git 1.7.5.4, you can specify a relative path by putting "./" at the beginning of the path. For example:

git show HEAD^^:./test.py

)

Using git restore

With Git 2.23+ (August 2019), you can also use git restore which replaces the confusing git checkout command

git restore -s <SHA1>     -- afile
git restore -s somebranch -- afile

That would restore on the working tree only the file as present in the "source" (-s) commit SHA1 or branch somebranch.
To restore also the index:

git restore -s <SHA1> -SW -- afile

(-SW: short for --staged --worktree)

Using low-level git plumbing commands

Before git1.5.x, this was done with some plumbing:

git ls-tree <rev>
show a list of one or more 'blob' objects within a commit

git cat-file blob <file-SHA1>
cat a file as it has been committed within a specific revision (similar to svn cat). use git ls-tree to retrieve the value of a given file-sha1

git cat-file -p $(git-ls-tree $REV $file | cut -d " " -f 3 | cut -f 1)::

git-ls-tree lists the object ID for $file in revision $REV, this is cut out of the output and used as an argument to git-cat-file, which should really be called git-cat-object, and simply dumps that object to stdout.


Note: since Git 2.11 (Q4 2016), you can apply a content filter to the git cat-file output.

See commit 3214594, commit 7bcf341 (09 Sep 2016), commit 7bcf341 (09 Sep 2016), and commit b9e62f6, commit 16dcc29 (24 Aug 2016) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 7889ed2, 21 Sep 2016)

git config diff.txt.textconv "tr A-Za-z N-ZA-Mn-za-m <"
git cat-file --textconv --batch

Note: "git cat-file --textconv" started segfaulting recently (2017), which has been corrected in Git 2.15 (Q4 2017)

See commit cc0ea7c (21 Sep 2017) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfbc2fc, 28 Sep 2017)

Pretty Printing JSON with React

Just to extend on the WiredPrairie's answer a little, a mini component that can be opened and closed.

Can be used like:

<Pretty data={this.state.data}/>

enter image description here

export default React.createClass({

    style: {
        backgroundColor: '#1f4662',
        color: '#fff',
        fontSize: '12px',
    },

    headerStyle: {
        backgroundColor: '#193549',
        padding: '5px 10px',
        fontFamily: 'monospace',
        color: '#ffc600',
    },

    preStyle: {
        display: 'block',
        padding: '10px 30px',
        margin: '0',
        overflow: 'scroll',
    },

    getInitialState() {
        return {
            show: true,
        };
    },

    toggle() {
        this.setState({
            show: !this.state.show,
        });
    },

    render() {
        return (
            <div style={this.style}>
                <div style={this.headerStyle} onClick={ this.toggle }>
                    <strong>Pretty Debug</strong>
                </div>
                {( this.state.show ?
                    <pre style={this.preStyle}>
                        {JSON.stringify(this.props.data, null, 2) }
                    </pre> : false )}
            </div>
        );
    }
});

Update

A more modern approach (now that createClass is on the way out)

import styles from './DebugPrint.css'

import autoBind from 'react-autobind'
import classNames from 'classnames'
import React from 'react'

export default class DebugPrint extends React.PureComponent {
  constructor(props) {
    super(props)
    autoBind(this)
    this.state = {
      show: false,
    }
  }    

  toggle() {
    this.setState({
      show: !this.state.show,
    });
  }

  render() {
    return (
      <div style={styles.root}>
        <div style={styles.header} onClick={this.toggle}>
          <strong>Debug</strong>
        </div>
        {this.state.show 
          ? (
            <pre style={styles.pre}>
              {JSON.stringify(this.props.data, null, 2) }
            </pre>
          )
          : null
        }
      </div>
    )
  }
}

And your style file

.root { backgroundColor: '#1f4662'; color: '#fff'; fontSize: '12px'; }

.header { backgroundColor: '#193549'; padding: '5px 10px'; fontFamily: 'monospace'; color: '#ffc600'; }

.pre { display: 'block'; padding: '10px 30px'; margin: '0'; overflow: 'scroll'; }

Python urllib2, basic HTTP authentication, and tr.im

Same solutions as Python urllib2 Basic Auth Problem apply.

see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler to add the Authorization header to each request that matches the known url.

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

Change font-weight of FontAwesome icons?

2018 Update

Font Awesome 5 now features light, regular and solid variants. The icon featured in this question has the following style under the different variants:

fa-times variants

A modern answer to this question would be that different variants of the icon can be used to make the icon appear bolder or lighter. The only downside is that if you're already using solid you will have to fall back to the original answers here to make those bolder, and likewise if you're using light you'd have to do the same to make those lighter.

Font Awesome's How To Use documentation walks through how to use these variants.


Original Answer

Font Awesome makes use of the Private Use region of Unicode. For example, this .icon-remove you're using is added in using the ::before pseudo-selector, setting its content to \f00d (&#xF00D;):

.icon-remove:before {
    content: "\f00d";
}

Font Awesome does only come with one font-weight variant, however browsers will render this as they would render any font with only one variant. If you look closely, the normal font-weight isn't as bold as the bold font-weight. Unfortunately a normal font weight isn't what you're after.

What you can do however is change its colour to something less dark and reduce its font size to make it stand out a bit less. From your image, the "tags" text appears much lighter than the icon, so I'd suggest using something like:

.tag .icon-remove {
    color:#888;
    font-size:14px;
}

Here's a JSFiddle example, and here is further proof that this is definitely a font.

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Import existing source code to GitHub

Add a GitHub repository as remote origin (replace [] with your URL):

git remote add origin [[email protected]:...]

Switch to your master branch and copy it to develop branch:

git checkout master
git checkout -b develop

Push your develop branch to the GitHub develop branch (-f means force):

git push -f origin develop:develop

How do I change the root directory of an Apache server?

In Apache version 2.4.18 (Ubuntu).

  1. Open the file /etc/apache2/apache2.conf and search for <Directory /var/www/> and replace to your directory.

  2. Open file /etc/apache2/sites-available/000-default.conf, search for DocumentRoot /var/www/html and replace it with your DocumentRoot.

How can I write an anonymous function in Java?

Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).

A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.

private static String pretty(Node node) {
    return "Node: " + new Object() {
        String print(Node cur) {
            return cur.isTerminal() ?
                cur.name() :
                ("("+print(cur.left())+":"+print(cur.right())+")");
        }
    }.print(node);
}

(I originally wrote this using node rather than cur in the print method. Say NO to capturing "implicitly final" locals?)

Correct way to use get_or_create?

Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:

customer.source, _ = Source.objects.get_or_create(name="Website")

How to use sessions in an ASP.NET MVC 4 application?

This is how session state works in ASP.NET and ASP.NET MVC:

ASP.NET Session State Overview

Basically, you do this to store a value in the Session object:

Session["FirstName"] = FirstNameTextBox.Text;

To retrieve the value:

var firstName = Session["FirstName"];

How can I create an executable JAR with dependencies using Maven?

Ken Liu has it right in my opinion. The maven dependency plugin allows you to expand all the dependencies, which you can then treat as resources. This allows you to include them in the main artifact. The use of the assembly plugin creates a secondary artifact which can be difficult to modify - in my case I wanted to add custom manifest entries. My pom ended up as:

<project>
 ...
 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
     <execution>
      <id>unpack-dependencies</id>
      <phase>package</phase>
      <goals>
       <goal>unpack-dependencies</goal>
      </goals>
     </execution>
    </executions>
   </plugin>
  </plugins>
  ...
  <resources>
   <resource>
    <directory>${basedir}/target/dependency</directory>
    <targetPath>/</targetPath>
   </resource>
  </resources>
 </build>
 ...
</project>

How do I add the Java API documentation to Eclipse?

Eclipse doesn't pull the tooltips from the javadoc location. It only uses the javadoc location to prepend to the link if you say open in browser, you need to download and attach the source for the JDK in order to get the tooltips. For all the JARs under the JRE you should have the following for the javadoc location: http://java.sun.com/javase/6/docs/api/. For resources.jar, rt.jar, jsse.jar, jce.jar and charsets.jar you should attach the source available here.

Mercurial — revert back to old version and continue from there

After using hg update -r REV it wasn't clear in the answer about how to commit that change so that you can then push.

If you just try to commit after the update, Mercurial doesn't think there are any changes.

I had to first make a change to any file (say in a README) so Mercurial recognized that I made a new change, then I could commit that.

This then created two heads as mentioned.

To get rid of the other head before pushing, I then followed the No-Op Merges step to remedy that situation.

I was then able to push.

How do I change select2 box height

Seems the stylesheet selectors have changed over time. I'm using select2-4.0.2 and the correct selector to set the box height is currently:

.select2-container--default .select2-results > .select2-results__options {
    max-height: 200px
}

Pass a reference to DOM object with ng-click

While you do the following, technically speaking:

<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
  //reference to the button that triggered the function:
  $event.target
};

This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.

You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796

How can getContentResolver() be called in Android?

You can use like this:

getApplicationContext().getContentResolver()

with the proper context.

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

Filtering a spark dataframe based on date

I find the most readable way to express this is using a sql expression:

df.filter("my_date < date'2015-01-01'")

we can verify this works correctly by looking at the physical plan from .explain()

+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))

How to detect my browser version and operating system using JavaScript?

For Firefox, Chrome, Opera, Internet Explorer and Safari

var ua="Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)";
//ua = navigator.userAgent;
var b;
var browser;
if(ua.indexOf("Opera")!=-1) {

    b=browser="Opera";
}
if(ua.indexOf("Firefox")!=-1 && ua.indexOf("Opera")==-1) {
    b=browser="Firefox";
    // Opera may also contains Firefox
}
if(ua.indexOf("Chrome")!=-1) {
    b=browser="Chrome";
}
if(ua.indexOf("Safari")!=-1 && ua.indexOf("Chrome")==-1) {
    b=browser="Safari";
    // Chrome always contains Safari
}

if(ua.indexOf("MSIE")!=-1 && (ua.indexOf("Opera")==-1 && ua.indexOf("Trident")==-1)) {
    b="MSIE";
    browser="Internet Explorer";
    //user agent with MSIE and Opera or MSIE and Trident may exist.
}

if(ua.indexOf("Trident")!=-1) {
    b="Trident";
    browser="Internet Explorer";
}

// now for version


var version=ua.match(b+"[ /]+[0-9]+(.[0-9]+)*")[0];

console.log("broswer",browser);
console.log("version",version);

Regular expression for extracting tag attributes

I'd reconsider the strategy to use only a single regular expression. Sure it's a nice game to come up with one single regular expression that does it all. But in terms of maintainabilty you are about to shoot yourself in both feet.

How can I change the text inside my <span> with jQuery?

$('#abc span').text('baa baa black sheep');
$('#abc span').html('baa baa <strong>black sheep</strong>');

text() if just text content. html() if it contains, well, html content.

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

How to overcome "datetime.datetime not JSON serializable"?

if you are using python3.7, then the best solution is using datetime.isoformat() and datetime.fromisoformat(); they work with both naive and aware datetime objects:

#!/usr/bin/env python3.7

from datetime import datetime
from datetime import timezone
from datetime import timedelta
import json

def default(obj):
    if isinstance(obj, datetime):
        return { '_isoformat': obj.isoformat() }
    return super().default(obj)

def object_hook(obj):
    _isoformat = obj.get('_isoformat')
    if _isoformat is not None:
        return datetime.fromisoformat(_isoformat)
    return obj

if __name__ == '__main__':
    #d = { 'now': datetime(2000, 1, 1) }
    d = { 'now': datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=-8))) }
    s = json.dumps(d, default=default)
    print(s)
    print(d == json.loads(s, object_hook=object_hook))

output:

{"now": {"_isoformat": "2000-01-01T00:00:00-08:00"}}
True

if you are using python3.6 or below, and you only care about the time value (not the timezone), then you can use datetime.timestamp() and datetime.fromtimestamp() instead;

if you are using python3.6 or below, and you do care about the timezone, then you can get it via datetime.tzinfo, but you have to serialize this field by yourself; the easiest way to do this is to add another field _tzinfo in the serialized object;

finally, beware of precisions in all these examples;

How to control size of list-style-type disc in CSS?

try to use diffrent font-size for li and a

.farParentDiv ul li {
   list-style-type: disc;
   font-size:20px;
}

.farParentDiv ul li a {
   font-size:10px;
}

this saved me from using images

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

Your problem is that you have declare twice the exec-maven-plugin :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-  
      integration\src\main\java\example\Main< /mainClass>
    </configuration>
</plugin>

...

< plugin>
    < groupId>org.codehaus.mojo</groupId>
    < artifactId>exec-maven-plugin</artifactId>
    < version>1.2</version>
< /plugin>

IDENTITY_INSERT is set to OFF - How to turn it ON?

The Reference: http://technet.microsoft.com/en-us/library/aa259221%28v=sql.80%29.aspx

My table is named Genre with the 3 columns of Id, Name and SortOrder

The code that I used is as:

SET IDENTITY_INSERT Genre ON

INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

NULL value for int in Update statement

If this is nullable int field then yes.

update TableName
set FiledName = null
where Id = SomeId

Convert Decimal to Varchar

You might need to convert the decimal to money (or decimal(8,2)) to get that exact formatting. The convert method can take a third parameter that controls the formatting style:

convert(varchar, cast(price as money))       12345.67
convert(varchar, cast(price as money), 0)    12345.67
convert(varchar, cast(price as money), 1)    12,345.67

How can I build a recursive function in python?

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

How to maintain aspect ratio using HTML IMG tag

Wrap the image in a div with dimensions 64x64 and set width: inherit to the image:

<div style="width: 64px; height: 64px;">
    <img src="Runtime path" style="width: inherit" />
</div>

Add a reference column migration in Rails 4

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID

Reading rows from a CSV file in Python

Reading it columnwise is harder?

Anyway this reads the line and stores the values in a list:

for line in open("csvfile.csv"):
    csv_row = line.split() #returns a list ["1","50","60"]

Modern solution:

# pip install pandas
import pandas as pd 
df = pd.read_table("csvfile.csv", sep=" ")

POI setting Cell Background to a Custom Color

Slot free in NPOI excel indexedcolors from 57+

            Color selColor;

        var wb = new HSSFWorkbook();

        var sheet = wb.CreateSheet("NPOI");
        var style = wb.CreateCellStyle();
        var font = wb.CreateFont();
        var palette = wb.GetCustomPalette();

        short indexColor = 57; 
        palette.SetColorAtIndex(indexColor, (byte)selColor.R, (byte)selColor.G, (byte)selColor.B);

        font.Color = palette.GetColor(indexColor).Indexed;

Find CRLF in Notepad++

The way I found it to work is by using the Replace function, and using "\n", with the "Extended" mode. I'm using version 5.8.5.

SSL InsecurePlatform error when using Requests package

For me no work i need upgrade pip....

Debian/Ubuntu

install dependencies

sudo apt-get install libpython-dev libssl-dev libffi-dev

upgrade pip and install packages

sudo pip install -U pip
sudo pip install -U pyopenssl ndg-httpsclient pyasn1

If you want remove dependencies

sudo apt-get remove --purge libpython-dev libssl-dev libffi-dev
sudo apt-get autoremove

In plain English, what does "git reset" do?

Please be aware, this is a simplified explanation intended as a first step in seeking to understand this complex functionality.

May be helpful for visual learners who want to visualise what their project state looks like after each of these commands:


For those who use Terminal with colour turned on (git config --global color.ui auto):

git reset --soft A and you will see B and C's stuff in green (staged and ready to commit)

git reset --mixed A (or git reset A) and you will see B and C's stuff in red (unstaged and ready to be staged (green) and then committed)

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)


Or for those who use a GUI program like 'Tower' or 'SourceTree'

git reset --soft A and you will see B and C's stuff in the 'staged files' area ready to commit

git reset --mixed A (or git reset A) and you will see B and C's stuff in the 'unstaged files' area ready to be moved to staged and then committed

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)

React.createElement: type is invalid -- expected a string

I was getting this error as well.

I was using:

import ReactDOM from 'react-dom';

Fix was doing this, instead:

import {ReactDOM} from 'react-dom';

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

What does the Ellipsis object do?

In Python 3, you can¹ use the Ellipsis literal ... as a “nop” placeholder for code that hasn't been written yet:

def will_do_something():
    ...

This is not magic; any expression can be used instead of ..., e.g.:

def will_do_something():
    1

(Can't use the word “sanctioned”, but I can say that this use was not outrightly rejected by Guido.)

¹ 'can' not in {'must', 'should'}

Fit background image to div

You can achieve this with the background-size property, which is now supported by most browsers.

To scale the background image to fit inside the div:

background-size: contain;

To scale the background image to cover the whole div:

background-size: cover;

JSFiddle example

There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.

Query grants for a table in postgres

Here is a script which generates grant queries for a particular table. It omits owner's privileges.

SELECT 
    format (
      'GRANT %s ON TABLE %I.%I TO %I%s;',
      string_agg(tg.privilege_type, ', '),
      tg.table_schema,
      tg.table_name,
      tg.grantee,
      CASE
        WHEN tg.is_grantable = 'YES' 
        THEN ' WITH GRANT OPTION' 
        ELSE '' 
      END
    )
  FROM information_schema.role_table_grants tg
  JOIN pg_tables t ON t.schemaname = tg.table_schema AND t.tablename = tg.table_name
  WHERE
    tg.table_schema = 'myschema' AND
    tg.table_name='mytable' AND
    t.tableowner <> tg.grantee
  GROUP BY tg.table_schema, tg.table_name, tg.grantee, tg.is_grantable;

What's the best way to determine the location of the current PowerShell script?

It took me a while to develop something that took the accepted answer and turned it into a robust function.

I am not sure about others, but I work in an environment with machines on both PowerShell version 2 and 3, so I needed to handle both. The following function offers a graceful fallback:

Function Get-PSScriptRoot
{
    $ScriptRoot = ""

    Try
    {
        $ScriptRoot = Get-Variable -Name PSScriptRoot -ValueOnly -ErrorAction Stop
    }
    Catch
    {
        $ScriptRoot = Split-Path $script:MyInvocation.MyCommand.Path
    }

    Write-Output $ScriptRoot
}

It also means that the function refers to the Script scope rather than the parent's scope as outlined by Michael Sorens in one of his blog posts.

Best way to add Gradle support to IntelliJ Project

Add:

build.gradle 

in your root project folder, and use plugin for example:

apply plugin: 'idea'
//and standard one
apply plugin: 'java'

and with this fire from command line:

gradle cleanIdea 

and after that:

gradle idea

After that everything should work

How do I use floating-point division in bash?

While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part. Rounding as needed.

#!/bin/bash

n=$1
d=$2

# because of rounding this should be 10^{i+1}
# where i is the number of decimal digits wanted
i=4
P=$((10**(i+1)))
Pn=$(($P / 10))
# here we 'fix' the decimal place, divide and round tward zero
t=$(($n * $P / $d + ($n < 0 ? -5 : 5)))
# then we print the number by dividing off the interger part and
# using the modulo operator (after removing the rounding digit) to get the factional part.
printf "%d.%0${i}d\n" $(($t / $P)) $(((t < 0 ? -t : t) / 10 % $Pn))

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

iPhone viewWillAppear not firing

If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked.

You need to use the navigation controller delegate methods instead:

navigationController:willShowViewController:animated:
navigationController:didShowViewController:animated:

Set margins in a LinearLayout programmatically

 MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
 layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

How to make an ng-click event conditional?

Basically ng-click first checks the isDisabled and based on its value it will decide whether the function should be called or not.

<span ng-click="(isDisabled) || clicked()">Do something</span>

OR read it as

<span ng-click="(if this value is true function clicked won't be called. and if it's false the clicked will be called) || clicked()">Do something</span>

Provisioning Profiles menu item missing from Xcode 5

After searching a few times in google, i found one software for provisioning profiles.

Install this iPhone configuration utility software and manage your all provisioning profiles in MAC.

Pycharm does not show plot

With me the problem was the fact that matplotlib was using the wrong backend. I am using Debian Jessie.

In a console I did the following:

import matplotlib
matplotlib.get_backend()

The result was: 'agg', while this should be 'TkAgg'.

The solution was simple:

  1. Uninstall matplotlib via pip
  2. Install the appropriate libraries: sudo apt-get install tcl-dev tk-dev python-tk python3-tk
  3. Install matplotlib via pip again.

An existing connection was forcibly closed by the remote host - WCF

I had this issue start happening when debugging from one web project to a web service in the same solution. The web service was returning responses that the web project couldnt understand. It would kind of work again at some points, then stop again.

It was because there was not an explicit reference between these projects, so the web service was not getting built when hitting F5 to start debugging. Once I added that, the errors went away.

Android: long click on a button -> perform actions

Initially when i implemented a longClick and a click to perform two separate events the problem i face was that when i had a longclick , the application also performed the action to be performed for a simple click . The solution i realized was to change the return type of the longClick to true which is normally false by default . Change it and it works perfectly .

How to read file from relative path in Java project? java.io.File cannot find the path specified

The following line can be used if we want to specify the relative path of the file.

File file = new File("./properties/files/ListStopWords.txt");  

Remove '\' char from string c#

You could use:

line.Replace(@"\", "");

or

line.Replace(@"\", string.Empty);

What is a plain English explanation of "Big O" notation?

It is very difficult to measure the speed of software programs, and when we try, the answers can be very complex and filled with exceptions and special cases. This is a big problem, because all those exceptions and special cases are distracting and unhelpful when we want to compare two different programs with one another to find out which is "fastest".

As a result of all this unhelpful complexity, people try to describe the speed of software programs using the smallest and least complex (mathematical) expressions possible. These expressions are very very crude approximations: Although, with a bit of luck, they will capture the "essence" of whether a piece of software is fast or slow.

Because they are approximations, we use the letter "O" (Big Oh) in the expression, as a convention to signal to the reader that we are making a gross oversimplification. (And to make sure that nobody mistakenly thinks that the expression is in any way accurate).

If you read the "Oh" as meaning "on the order of" or "approximately" you will not go too far wrong. (I think the choice of the Big-Oh might have been an attempt at humour).

The only thing that these "Big-Oh" expressions try to do is to describe how much the software slows down as we increase the amount of data that the software has to process. If we double the amount of data that needs to be processed, does the software need twice as long to finish it's work? Ten times as long? In practice, there are a very limited number of big-Oh expressions that you will encounter and need to worry about:

The good:

  • O(1) Constant: The program takes the same time to run no matter how big the input is.
  • O(log n) Logarithmic: The program run-time increases only slowly, even with big increases in the size of the input.

The bad:

  • O(n) Linear: The program run-time increases proportionally to the size of the input.
  • O(n^k) Polynomial: - Processing time grows faster and faster - as a polynomial function - as the size of the input increases.

... and the ugly:

  • O(k^n) Exponential The program run-time increases very quickly with even moderate increases in the size of the problem - it is only practical to process small data sets with exponential algorithms.
  • O(n!) Factorial The program run-time will be longer than you can afford to wait for anything but the very smallest and most trivial-seeming datasets.

How do I delete specific characters from a particular String in Java?

You can use replaceAll() method :

String.replaceAll(",", "");
String.replaceAll("\\.", "");
String.replaceAll("\\(", "");

etc..

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

Look for GSpread.NET. It's also an OpenSource project and it doesn't require Office installed. You can work with Google Spreadsheets by using API from Microsoft Excel. If you want to re-use the old code to get access to Google Spreadsheets, GSpread.NET is the best way. You need to add a few row:

Set objExcel = CreateObject("GSpreadCOM.Application")
// Name             - User name, any you like
// ClientIdAndSecret - `client_id|client_secret` format
// ScriptId         - Google Apps script ID
app.MailLogon(Name, ClientIdAndSecret, ScriptId);

Further code remain unchanged.

http://scand.com/products/gspread/index.html

C# - Making a Process.Start wait until the process has start-up

public static class WinApi
{

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    public static class Windows
    {
        public const int NORMAL = 1;
        public const int HIDE = 0;
        public const int RESTORE = 9;
        public const int SHOW = 5;
        public const int MAXIMIXED = 3;
    }

}

App

String process_name = "notepad"
Process process;
process = Process.Start( process_name );

while (!WinApi.ShowWindow(process.MainWindowHandle, WinApi.Windows.NORMAL))
{
    Thread.Sleep(100);
    process.Refresh();
}

// Done!
// Continue your code here ...

What is parsing in terms that a new programmer would understand?

I'd explain parsing as the process of turning some kind of data into another kind of data.

In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.

For example, turning

":Nick!User@Host PRIVMSG #channel :Hello!"

into (C)

struct irc_line {
    char *nick;
    char *user;
    char *host;
    char *command;
    char **arguments;
    char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }

How do I create a new line in Javascript?

In html page:

document.write("<br>"); 

but if you are in JavaScript file, then this will work as new line:

document.write("\n");

.gitignore for Visual Studio Projects and Solutions

Here is what I use in my .NET Projects for my .gitignore file.

[Oo]bj/
[Bb]in/
*.suo
*.user
/TestResults
*.vspscc
*.vssscc

This is pretty much an all MS approach, that uses the built in Visual Studio tester, and a project that may have some TFS bindings in there too.

Generate preview image from Video file?

Solution #1 (Older) (not recommended)

Firstly install ffmpeg-php project (http://ffmpeg-php.sourceforge.net/)

And then you can use of this simple code:

<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
    $gd_image = $frame->toGDImage();
    if ($gd_image) {
        imagepng($gd_image, $thumbnail);
        imagedestroy($gd_image);
        echo '<img src="'.$thumbnail.'">';
    }
}
?>

Description: This project use binary extension .so file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg or PHP.


Solution #2 (Update 2018) (recommended)

Firstly install PHP-FFMpeg project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg)

And then you can use of this simple code:

<?php
require 'vendor/autoload.php';

$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';

Description: It's newer and more modern project and works with latest version of FFMpeg and PHP. Note that it's required to proc_open() PHP function.

Android on-screen keyboard auto popping up

InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
        imm.ShowSoftInput(_enterPin.FindFocus(), 0);

*This is for Android.xamarin and FindFocus()-it searches for the view in hierarchy rooted at this view that currently has focus,as i have _enterPin.RequestFocus() before the above code thus it shows keyboard for _enterPin EditText *

Python and pip, list all versions of a package that's available?

This is Py3.9+ version of Limmy+EricChiang 's solution.

import json
import urllib.request
from distutils.version import StrictVersion


# print PyPI versions of package
def versions(package_name):
    url = "https://pypi.org/pypi/%s/json" % (package_name,)
    data = json.load(urllib.request.urlopen(url))
    versions = list(data["releases"])
    sortfunc = lambda x: StrictVersion(x.replace('rc', 'b').translate(str.maketrans('cdefghijklmn', 'bbbbbbbbbbbb')))
    versions.sort(key=sortfunc)
    return versions

How can I upload fresh code at github?

You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)

Check Creating github repositories with command line | Do it yourself Android for example usage.

How to parse this string in Java?

String s = "prefix/dir1/dir2/dir3/dir4"

String parts[] = s.split("/");

System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...

How to get current date time in milliseconds in android

try this

  Calendar c = Calendar.getInstance(); 
  int mseconds = c.get(Calendar.MILLISECOND)

an alternative would be

 Calendar rightNow = Calendar.getInstance();

 long offset = rightNow.get(Calendar.ZONE_OFFSET) +
        rightNow.get(Calendar.DST_OFFSET);
 long sinceMid = (rightNow.getTimeInMils() + offset) %
       (24 * 60 * 60 * 1000);

  System.out.println(sinceMid + " milliseconds since midnight");

How to get thread id of a pthread in linux c program?

You can also write in this manner and it does the same. For eg:

for(int i=0;i < total; i++)
{
    pthread_join(pth[i],NULL);
    cout << "SUM of thread id " << pth[i] << " is " << args[i].sum << endl;
}

This program sets up an array of pthread_t and calculate sum on each. So it is printing the sum of each thread with thread id.

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

Parsing JSON array into java.util.List with Gson

I was able to get the list mapping to work with just using @SerializedName for all fields.. no logic around Type was necessary.

Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data

Here's an example:

1. The JSON

   {
    "name": "Some House",
    "gallery": [
      {
        "description": "Nice 300sqft. den.jpg",
        "photo_url": "image/den.jpg"
      },
      {
        "description": "Floor Plan",
        "photo_url": "image/floor_plan.jpg"
      }
    ]
  }

2. Java class with the List

public class FocusArea {

    @SerializedName("name")
    private String mName;

    @SerializedName("gallery")
    private List<ContentImage> mGalleryImages;
}

3. Java class for the List items

public class ContentImage {

    @SerializedName("description")
    private String mDescription;

    @SerializedName("photo_url")
    private String mPhotoUrl;

    // getters/setters ..
}

4. The Java code that processes the JSON

    for (String key : focusAreaKeys) {

        JsonElement sectionElement = sectionsJsonObject.get(key);
        FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
    }

Getting Error "Form submission canceled because the form is not connected"

if you are seeing this error in React JS when you try to submit the form by pressing enter, make sure all your buttons in the form that do not submit the form have a type="button".

If you have only one button with type="submit" pressing Enter will submit the form as expected.

References:
https://dzello.com/blog/2017/02/19/demystifying-enter-key-submission-for-react-forms/ https://github.com/facebook/react/issues/2093

C# Base64 String to JPEG Image

So with the code you have provided.

var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
    imageFile.Write(bytes ,0, bytes.Length);
    imageFile.Flush();
}

How to create a project from existing source in Eclipse and then find it?

Follow this instructions from standard eclipse docs.

  1. From the main menu bar, select command link File > Import.... The Import wizard opens.
  2. Select General > Existing Project into Workspace and click Next.
  3. Choose either Select root directory or Select archive file and click the associated Browse to locate the directory or file containing the projects.
  4. Under Projects select the project or projects which you would like to import.
  5. Click Finish to start the import.

How can I add additional PHP versions to MAMP

Found a quick fix in the MAMP forums.

Basically it seems MAMP is only allowing 2 versions of PHP to show up. Quick fix, rename the folders you're not bothered about using, for me this meant adding an "X" to my /Applications/MAMP/bin/php/php5.4.10_X folder. Now 5.2.17 and 5.3.20 show up in the mamp prefs.

Done!

Edit - if the PHP version you require isn't in the PHP folder, you can download the version you require from http://www.mamp.info/en/downloads/

Edit - MAMP don't seem to provide links to the alternative PHP versions on the download page any more. Use WayBackMachine https://web.archive.org/web/20180131074715/http://www.mamp.info/en/downloads/

Create request with POST, which response codes 200 or 201 and content

In a few words:

  • 200 when an object is created and returned
  • 201 when an object is created but only its reference is returned (such as an ID or a link)

Create a File object in memory from a string in Java

Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.

An example:

try {
    // Create temp file.
    File temp = File.createTempFile("pattern", ".suffix");

    // Delete temp file when program exits.
    temp.deleteOnExit();

    // Write to temp file
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("aString");
    out.close();
} catch (IOException e) {
}

Propagate all arguments in a bash shell script

Use "$@" (works for all POSIX compatibles).

[...] , bash features the "$@" variable, which expands to all command-line parameters separated by spaces.

From Bash by example.

How to word wrap text in HTML?

The only one that works across IE, Firefox, chrome, safari and opera if there are no spaces in the word (such as a long URL) is:

div{
    width: 200px;  
    word-break: break-all;
}

I found this to be bullet-proof.

Multiple github accounts on the same computer?

just figured this out for Windows, using credentials for each repo:

cd c:\User1\SomeRepo
git config --local credential.https://github.com.user1 user1
git config --local credential.useHttpPath true
git config --local credential.helper manager
git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

The format of credential.https://github.com. tells the credential helper the URL for the credential. The 'useHttpPath' tells the credential manager to use the path for the credential. If useHttpPath is omitted then the credential manager will store one credential for https://github.com. If it is included then the credential manager will store multiple credentials, which is what I really wanted.

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Besides changing it to Console (/SUBSYSTEM:CONSOLE) as others have said, you may need to change the entry point in Properties -> Linker -> Advanced -> Entry Point. Set it to mainCRTStartup.

It seems that Visual Studio might be searching for the WinMain function instead of main, if you don't specify otherwise.

exception in thread 'main' java.lang.NoClassDefFoundError:

Here is what finally worked.

`@echo off
set path=%path%;C:\Program Files\Java\jdk1.7.0_71\bin;
set classpath=C:\Program Files\Java\jdk1.7.0_71\lib;
cd <packageDirectoryName>
javac .\trainingPackage\HelloWorld.java
cd ..
java trainingPackage.HelloWorld 
REM (Make sure you are on the parent directory of the PackageName and not inside the    Packagedirectory when executing java).`

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

How I do it with Django 1.11 :

class ItemForm(ModelForm):
    disabled_fields = ('added_by',)

    class Meta:
        model = Item
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        for field in self.disabled_fields:
            self.fields[field].disabled = True

Setting dropdownlist selecteditem programmatically

Here is the code I was looking for :

DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));

Or

DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));

Show default value in Spinner in android

I found a solution by extending ArrayAdapter and Overriding the getView method.

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * A SpinnerAdapter which does not show the value of the initial selection initially,
 * but an initialText.
 * To use the spinner with initial selection instead call notifyDataSetChanged().
 */
public class SpinnerAdapterWithInitialText<T> extends ArrayAdapter<T> {

    private Context context;
    private int resource;

    private boolean initialTextWasShown = false;
    private String initialText = "Please select";

    /**
     * Constructor
     *
     * @param context The current context.
     * @param resource The resource ID for a layout file containing a TextView to use when
     *                 instantiating views.
     * @param objects The objects to represent in the ListView.
     */
    public SpinnerAdapterWithInitialText(@NonNull Context context, int resource, @NonNull T[] objects) {
        super(context, resource, objects);
        this.context = context;
        this.resource = resource;
    }

    /**
     * Returns whether the user has selected a spinner item, or if still the initial text is shown.
     * @param spinner The spinner the SpinnerAdapterWithInitialText is assigned to.
     * @return true if the user has selected a spinner item, false if not.
     */
    public boolean selectionMade(Spinner spinner) {
        return !((TextView)spinner.getSelectedView()).getText().toString().equals(initialText);
    }

    /**
     * Returns a TextView with the initialText the first time getView is called.
     * So the Spinner has an initialText which does not represent the selected item.
     * To use the spinner with initial selection instead call notifyDataSetChanged(),
     * after assigning the SpinnerAdapterWithInitialText.
     */
    @Override
    public View getView(int position, View recycle, ViewGroup container) {
        if(initialTextWasShown) {
            return super.getView(position, recycle, container);
        } else {
            initialTextWasShown = true;
            LayoutInflater inflater = LayoutInflater.from(context);
            final View view = inflater.inflate(resource, container, false);

            ((TextView) view).setText(initialText);

            return view;
        }
    }
}

What Android does when initialising the Spinner, is calling getView for the selected item before calling getView for all items in T[] objects. The SpinnerAdapterWithInitialText returns a TextView with the initialText, the first time it is called. All the other times it calls super.getView which is the getView method of ArrayAdapter which is called if you are using the Spinner normally.

To find out whether the user has selected a spinner item, or if the spinner still displays the initialText, call selectionMade and hand over the spinner the adapter is assigned to.

How to check list A contains any value from list B?

For faster and short solution you can use HashSet instead of List.

a.Overlaps(b);

Overlaps documentation

This method is an O(n) instead of O(n^2) with two lists.

Query-string encoding of a Javascript Object

Here's a concise & recursive version with Object.entries. It handles arbitrarily nested arrays, but not nested objects. It also removes empty elements:

const format = (k,v) => v !== null ? `${k}=${encodeURIComponent(v)}` : ''

const to_qs = (obj) => {
    return [].concat(...Object.entries(obj)
                       .map(([k,v]) => Array.isArray(v) 
                          ? v.map(arr => to_qs({[k]:arr})) 
                          : format(k,v)))
           .filter(x => x)
           .join('&');
}

E.g.:

let json = { 
    a: [1, 2, 3],
    b: [],              // omit b
    c: 1,
    d: "test&encoding", // uriencode
    e: [[4,5],[6,7]],   // flatten this
    f: null,            // omit nulls
    g: 0
};

let qs = to_qs(json)

=> "a=1&a=2&a=3&c=1&d=test%26encoding&e=4&e=5&e=6&e=7&g=0"

A field initializer cannot reference the nonstatic field, method, or property

you can use like this

private dynamic defaultReminder => reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; 

How to pass url arguments (query string) to a HTTP request on Angular?

My example

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

My method

  getUserByName(name: string): Observable<MyObject[]> {
    //set request params
    let params: URLSearchParams = new URLSearchParams();
    params.set("name", name);
    //params.set("surname", surname); for more params
    this.options.search = params;

    let url = "http://localhost:8080/test/user/";
    console.log("url: ", url);

    return this.http.get(url, this.options)
      .map((resp: Response) => resp.json() as MyObject[])
      .catch(this.handleError);
  }

  private handleError(err) {
    console.log(err);
    return Observable.throw(err || 'Server error');
  }

in my component

  userList: User[] = [];
  this.userService.getUserByName(this.userName).subscribe(users => {
      this.userList = users;
    });

By postman

http://localhost:8080/test/user/?name=Ethem

Simple int to char[] conversion

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

But you probably meant "i want to stringify a number", so ignore this response :-)

What is a good alternative to using an image map generator?

There is also Mappa - http://mappatool.com/.

It only supports polygons, but they are definitely the hardest parts :)

TypeError: unhashable type: 'list' when using built-in set function

Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
    thing = tuple(thing)
    mylist2.append(thing)
set(mylist2)

Convert a String representation of a Dictionary to a dictionary?

You can use the built-in ast.literal_eval:

>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}

This is safer than using eval. As its own docs say:

>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.

For example:

>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
    onerror(os.listdir, path, sys.exc_info())
  File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
    names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

Close Bootstrap Modal

This works well

$(function () {
   $('#modal').modal('toggle');
});

However, when you have multiple modals stacking on top one another it is not effective, so instead , this works

data-dismiss="modal"

What is the easiest way to get the current day of the week in Android?

If you do not want to use Calendar class at all you can use this

String weekday_name = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(System.currentTimeMillis());

i.e., result is,

"Sunday"

JavaScript ES6 promise for loop

here's my 2 cents worth:

  • resuable function forpromise()
  • emulates a classic for loop
  • allows for early exit based on internal logic, returning a value
  • can collect an array of results passed into resolve/next/collect
  • defaults to start=0,increment=1
  • exceptions thrown inside loop are caught and passed to .catch()

_x000D_
_x000D_
    function forpromise(lo, hi, st, res, fn) {_x000D_
        if (typeof res === 'function') {_x000D_
            fn = res;_x000D_
            res = undefined;_x000D_
        }_x000D_
        if (typeof hi === 'function') {_x000D_
            fn = hi;_x000D_
            hi = lo;_x000D_
            lo = 0;_x000D_
            st = 1;_x000D_
        }_x000D_
        if (typeof st === 'function') {_x000D_
            fn = st;_x000D_
            st = 1;_x000D_
        }_x000D_
        return new Promise(function(resolve, reject) {_x000D_
_x000D_
            (function loop(i) {_x000D_
                if (i >= hi) return resolve(res);_x000D_
                const promise = new Promise(function(nxt, brk) {_x000D_
                    try {_x000D_
                        fn(i, nxt, brk);_x000D_
                    } catch (ouch) {_x000D_
                        return reject(ouch);_x000D_
                    }_x000D_
                });_x000D_
                promise._x000D_
                catch (function(brkres) {_x000D_
                    hi = lo - st;_x000D_
                    resolve(brkres)_x000D_
                }).then(function(el) {_x000D_
                    if (res) res.push(el);_x000D_
                    loop(i + st)_x000D_
                });_x000D_
            })(lo);_x000D_
_x000D_
        });_x000D_
    }_x000D_
_x000D_
_x000D_
    //no result returned, just loop from 0 thru 9_x000D_
    forpromise(0, 10, function(i, next) {_x000D_
        console.log("iterating:", i);_x000D_
        next();_x000D_
    }).then(function() {_x000D_
_x000D_
_x000D_
        console.log("test result 1", arguments);_x000D_
_x000D_
        //shortform:no result returned, just loop from 0 thru 4_x000D_
        forpromise(5, function(i, next) {_x000D_
            console.log("counting:", i);_x000D_
            next();_x000D_
        }).then(function() {_x000D_
_x000D_
            console.log("test result 2", arguments);_x000D_
_x000D_
_x000D_
_x000D_
            //collect result array, even numbers only_x000D_
            forpromise(0, 10, 2, [], function(i, collect) {_x000D_
                console.log("adding item:", i);_x000D_
                collect("result-" + i);_x000D_
            }).then(function() {_x000D_
_x000D_
                console.log("test result 3", arguments);_x000D_
_x000D_
                //collect results, even numbers, break loop early with different result_x000D_
                forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
                    console.log("adding item:", i);_x000D_
                    if (i === 8) return break_("ending early");_x000D_
                    collect("result-" + i);_x000D_
                }).then(function() {_x000D_
_x000D_
                    console.log("test result 4", arguments);_x000D_
_x000D_
                    // collect results, but break loop on exception thrown, which we catch_x000D_
                    forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
                        console.log("adding item:", i);_x000D_
                        if (i === 4) throw new Error("failure inside loop");_x000D_
                        collect("result-" + i);_x000D_
                    }).then(function() {_x000D_
_x000D_
                        console.log("test result 5", arguments);_x000D_
_x000D_
                    })._x000D_
                    catch (function(err) {_x000D_
_x000D_
                        console.log("caught in test 5:[Error ", err.message, "]");_x000D_
_x000D_
                    });_x000D_
_x000D_
                });_x000D_
_x000D_
            });_x000D_
_x000D_
_x000D_
        });_x000D_
_x000D_
_x000D_
_x000D_
    });
_x000D_
_x000D_
_x000D_

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

path = pd.read_csv(**'C:\Users\mravi\Desktop\filename'**)

The error is because of the path that is mentioned

Add 'r' before the path

path = pd.read_csv(**r'C:\Users\mravi\Desktop\filename'**)

This would work fine.

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

Did the following for a spring application running static, rest and websocket content.

The Apache is used as Proxy and SSL Endpoint for the following URIs:

  • /app → static content
  • /api → REST API
  • /api/ws → websocket

Apache configuration

<VirtualHost *:80>
    ServerName xxx.xxx.xxx    

    ProxyRequests Off
    ProxyVia Off
    ProxyPreserveHost On

    <Proxy *>
         Require all granted
    </Proxy>

    RewriteEngine On

    # websocket 
    RewriteCond %{HTTP:Upgrade}         =websocket                      [NC]
    RewriteRule ^/api/ws/(.*)           ws://localhost:8080/api/ws/$1   [P,L]

    # rest
    ProxyPass /api http://localhost:8080/api
    ProxyPassReverse /api http://localhost:8080/api

    # static content    
    ProxyPass /app http://localhost:8080/app
    ProxyPassReverse /app http://localhost:8080/app 
</VirtualHost>

I use the same vHost config for the SSL configuration, no need to change anything proxy related.

Spring configuration

server.use-forward-headers: true

Change size of axes title and labels in ggplot2

If you are creating many graphs, you could be tired of typing for each graph the lines of code controlling for the size of the titles and texts. What I typically do is creating an object (of class "theme" "gg") that defines the desired theme characteristics. You can do that at the beginning of your code.

My_Theme = theme(
  axis.title.x = element_text(size = 16),
  axis.text.x = element_text(size = 14),
  axis.title.y = element_text(size = 16))

Next, all you will have to do is adding My_Theme to your graphs.

g + My_Theme
if you have another graph, g1, just write:
g1 + My_Theme 
and so on.

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

Filter by process/PID in Wireshark

You could match the port numbers from wireshark up to port numbers from, say, netstat which will tell you the PID of a process listening on that port.

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

What is external linkage and internal linkage?

When you write an implementation file (.cpp, .cxx, etc) your compiler generates a translation unit. This is the source file from your implementation plus all the headers you #included in it.

Internal linkage refers to everything only in scope of a translation unit.

External linkage refers to things that exist beyond a particular translation unit. In other words, accessible through the whole program, which is the combination of all translation units (or object files).

how to modify the size of a column

Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter statement exactly the way you originally had it works perfectly:

ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);

You only need to add parenthesis if you need to alter more than one column at once, such as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));

How to delete a selected DataGridViewRow and update a connected database table?

have a look this way:

if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
  foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
  {
      bindingSource1.RemoveAt(item.Index);
  }
      adapter.Update(ds);
 }

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

Yes, I wrote a little groovy script which does the trick You should add a 'Dynamic Choice Parameter' to your job and customize the following groovy script to your needs :

#!/usr/bin/groovy

def gitURL = "git repo url"
def command = "git ls-remote --heads --tags ${gitURL}"

def proc = command.execute()
proc.waitFor()              

if ( proc.exitValue() != 0 ) {
   println "Error, ${proc.err.text}"
   System.exit(-1)
}

def text = proc.in.text
# put your version string match
def match = /<REGEX>/
def tags = []

text.eachMatch(match) { tags.push(it[1]) }
tags.unique()
tags.sort( { a, b ->
         def a1 = a.tokenize('._-')
         def b1 = b.tokenize('._-')
         try {
            for (i in 1..<[a1.size(), b1.size()].min()) { 
                 if (a1[i].toInteger() != b1[i].toInteger()) return a1[i].toInteger() <=> b1[i].toInteger()
            }
            return 1
         } catch (e) {
            return -1;
         }
} )
tags.reverse()

I my case the version string was in the following format X.X.X.X and could have user branches in the format X.X.X-username ,etc... So I had to write my own sort function. This was my first groovy script so if there are better ways of doing thing I would like to know.

Git Server Like GitHub?

You can also install Indefero, it is a GPL clone of GoogleCode, as it supports both Subversion and Git, you can have a smooth transition. I am the author of Indefero.

Get current scroll position of ScrollView in React Native

Disclaimer: what follows is primarily the result of my own experimentation in React Native 0.50. The ScrollView documentation is currently missing a lot of the information covered below; for instance onScrollEndDrag is completely undocumented. Since everything here relies upon undocumented behaviour, I can unfortunately make no promises that this information will remain correct a year or even a month from now.

Also, everything below assumes a purely vertical scrollview whose y offset we are interested in; translating to x offsets, if needed, is hopefully an easy exercise for the reader.


Various event handlers on a ScrollView take an event and let you get the current scroll position via event.nativeEvent.contentOffset.y. Some of these handlers have slightly different behaviour between Android and iOS, as detailed below.

onScroll

On Android

Fires every frame while the user is scrolling, on every frame while the scroll view is gliding after the user releases it, on the final frame when the scroll view comes to rest, and also whenever the scroll view's offset changes as a result of its frame changing (e.g. due to rotation from landscape to portrait).

On iOS

Fires while the user is dragging or while the scroll view is gliding, at some frequency determined by scrollEventThrottle and at most once per frame when scrollEventThrottle={16}. If the user releases the scroll view while it has enough momentum to glide, the onScroll handler will also fire when it comes to rest after gliding. However, if the user drags and then releases the scroll view while it is stationary, onScroll is not guaranteed to fire for the final position unless scrollEventThrottle has been set such that onScroll fires every frame of scrolling.

There is a performance cost to setting scrollEventThrottle={16} that can be reduced by setting it to a larger number. However, this means that onScroll will not fire every frame.

onMomentumScrollEnd

Fires when the scroll view comes to a stop after gliding. Does not fire at all if the user releases the scroll view while it is stationary such that it does not glide.

onScrollEndDrag

Fires when the user stops dragging the scroll view - regardless of whether the scroll view is left stationary or begins to glide.


Given these differences in behaviour, the best way to keep track of the offset depends upon your precise circumstances. In the most complicated case (you need to support Android and iOS, including handling changes in the ScrollView's frame due to rotation, and you don't want to accept the performance penalty on Android from setting scrollEventThrottle to 16), and you need to handle changes to the content in the scroll view too, then it's a right damn mess.

The simplest case is if you only need to handle Android; just use onScroll:

<ScrollView
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
>

To additionally support iOS, if you're happy to fire the onScroll handler every frame and accept the performance implications of that, and if you don't need to handle frame changes, then it's only a little bit more complicated:

<ScrollView
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
  scrollEventThrottle={16}
>

To reduce the performance overhead on iOS while still guaranteeing that we record any position that the scroll view settles on, we can increase scrollEventThrottle and additionally provide an onScrollEndDrag handler:

<ScrollView
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
  onScrollEndDrag={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
  scrollEventThrottle={160}
>

But if we want to handle frame changes (e.g. because we allow the device to be rotated, changing the available height for the scroll view's frame) and/or content changes, then we must additionally implement both onContentSizeChange and onLayout to keep track of the height of both the scroll view's frame and its contents, and thereby continually calculate the maximum possible offset and infer when the offset has been automatically reduced due to a frame or content size change:

<ScrollView
  onLayout={event => {
    this.frameHeight = event.nativeEvent.layout.height;
    const maxOffset = this.contentHeight - this.frameHeight;
    if (maxOffset < this.yOffset) {
      this.yOffset = maxOffset;
    }
  }}
  onContentSizeChange={(contentWidth, contentHeight) => {
    this.contentHeight = contentHeight;
    const maxOffset = this.contentHeight - this.frameHeight;
    if (maxOffset < this.yOffset) {
      this.yOffset = maxOffset;
    }
  }}
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y;
  }}
  onScrollEndDrag={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y;
  }}
  scrollEventThrottle={160}
>

Yeah, it's pretty horrifying. I'm also not 100% certain that it'll always work right in cases where you simultaneously change the size of both the frame and content of the scroll view. But it's the best I can come up with, and until this feature gets added within the framework itself, I think this is the best that anyone can do.

Multiple IF AND statements excel

With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs

=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))

although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))

To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula

=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))

How to print a list in Python "nicely"

A quick hack while debugging that works without having to import pprint would be to join the list on '\n'.

>>> lst = ['foo', 'bar', 'spam', 'egg']
>>> print '\n'.join(lst)
foo
bar
spam
egg

How to send file contents as body entity using cURL

I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:

curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

What are the most useful Intellij IDEA keyboard shortcuts?

Yes, Ctrl + Shift + A is the most useful one. It's a meta shortcut

How do I know the script file name in a Bash script?

I've found this line to always work, regardless of whether the file is being sourced or run as a script.

echo "${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}"

If you want to follow symlinks use readlink on the path you get above, recursively or non-recursively.

The reason the one-liner works is explained by the use of the BASH_SOURCE environment variable and its associate FUNCNAME.

BASH_SOURCE

An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}.

FUNCNAME

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.

[Source: Bash manual]

Android "Only the original thread that created a view hierarchy can touch its views."

I was working with a class that did not contain a reference to the context. So it was not possible for me to use runOnUIThread(); I used view.post(); and it was solved.

timer.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        final int currentPosition = mediaPlayer.getCurrentPosition();
        audioMessage.seekBar.setProgress(currentPosition / 1000);
        audioMessage.tvPlayDuration.post(new Runnable() {
            @Override
            public void run() {
                audioMessage.tvPlayDuration.setText(ChatDateTimeFormatter.getDuration(currentPosition));
            }
        });
    }
}, 0, 1000);

Java 8: Lambda-Streams, Filter by Method with Exception

It can be resolved by below simple code with Stream and Try in AbacusUtil:

Stream.of(accounts).filter(a -> Try.call(a::isActive)).map(a -> Try.call(a::getNumber)).toSet();

Disclosure: I'm the developer of AbacusUtil.

PHP function ssh2_connect is not working

For WHM Panel

Menu > Server Configuration > Terminal:

yum install libssh2-devel -y

Menu > Software > Module Installers

  1. PHP PECL Manage Click
  2. ssh2 Install Now Click

Menu > Restart Services > HTTP Server (Apache)

Are you sure you wish to restart this service?

Yes

ssh2_connect() Work!

Calculate mean and standard deviation from a vector of samples in C++ using Boost

Create your own container:

template <class T>
class statList : public std::list<T>
{
    public:
        statList() : std::list<T>::list() {}
        ~statList() {}
        T mean() {
           return accumulate(begin(),end(),0.0)/size();
        }
        T stddev() {
           T diff_sum = 0;
           T m = mean();
           for(iterator it= begin(); it != end(); ++it)
               diff_sum += ((*it - m)*(*it -m));
           return diff_sum/size();
        }
};

It does have some limitations, but it works beautifully when you know what you are doing.

Android studio Gradle icon error, Manifest Merger

The answer of shimi_tap is enough. What to be remembered is that choosing only what you need. Choose from {icon, name, theme, label}. I added tools:replace="android:icon,android:theme", it does not work. I added tools:replace="android:icon,android:theme,android:label,android:name", it does not work. It works when I added tools:replace="android:icon,android:theme,android:label". So find out what the conflict exactly is in your manifest files.

Page scroll when soft keyboard popped up

This only worked for me:

android:windowSoftInputMode="adjustPan"

How do you specify table padding in CSS? ( table, not cell padding )

CSS doesn't really allow you to do this on a table level. Generally, I specify cellspacing="3" when I want to achieve this effect. Obviously not a css solution, so take it for what it's worth.

Have border wrap around text

Not sure, if that's what you want, but you could make the inner div an inline-element. This way the border should be wrapped only around the text. Even better than that is to use an inline-element for your title.

Solution 1

<div id="page" style="width: 600px;">
    <div id="title" style="display: inline; border...">Title</div>
</div>

Solution 2

<div id="page" style="width: 600px;">
    <span id="title" style="border...">Title</span>
</div>

Edit: Strange, SO doesn't interpret my code-examples correctly as block, so I had to use inline-code-method.

Expected response code 220 but got code "", with message "" in Laravel

if you are using Swift Mailer: please ensure that your $transport variable is similar to the below, based on tests i have done, that error results from ssl and port misconfiguration. note: you must include 'ssl' or 'tls' in the transport variable.

EXAMPLE CODE:

// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
  ->setUsername([email protected])
  ->setPassword(password)
;

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('News Letter Subscription'))
  ->setFrom(['[email protected]' => 'A Name'])
  ->setTo(['[email protected]' => 'A Name'])
  ->setBody('your message body')
  ;

// Send the message
$result = $mailer->send($message);

Composer update memory limit

I made this on Windows 10 and worked with me:

php -d memory_limit=-1 C:/ProgramData/ComposerSetup/bin/composer.phar update

You can change xx Value that you want

 memory_limit=XX

How to get a complete list of ticker symbols from Yahoo Finance?

I may be able to help with a list of ticker symbols for (U.S. and non-U.S.) stocks and for ETFs.

Yahoo provides an Earnings Calendar that lists all the stocks that announce earnings for a given day. This includes non-US stocks.

For example, here is today's: http://biz.yahoo.com/research/earncal/20120710.html

the last part of the URL is the date (in YYYYMMDD format) for which you want the Earnings Calendar. You can loop through several days and scrape the Symbols of all stocks that reported earnings on those days.

There is no guarantee that yahoo has data for all stocks that report earnings, especially since some stocks no longer exist (bankruptcy, acquisition, etc.), but this is probably a decent starting point.

If you are familiar with R, you can use the qmao package to do this. (See this post) if you have trouble installing it.

ec <- getEarningsCalendar(from="2011-01-01", to="2012-07-01") #this may take a while
s <- unique(ec$Symbol)
length(s)
#[1] 12223
head(s, 20) #look at the first 20 Symbols
# [1] "CVGW"    "ANGO"    "CAMP"    "LNDC"    "MOS"     "NEOG"    "SONC"   
# [8] "TISI"    "SHLM"    "FDO"     "FC"      "JPST.PK" "RECN"    "RELL"   
#[15] "RT"      "UNF"     "WOR"     "WSCI"    "ZEP"     "AEHR"   

This will not include any ETFs, futures, options, bonds, forex or mutual funds.

You can get a list of ETFs from yahoo here: http://finance.yahoo.com/etf/browser/mkt That only shows the first 20. You need the URL of the "Show All" link at the bottom of that page. You can scrape the page to find out how many ETFs there are, then construct a URL.

L <- readLines("http://finance.yahoo.com/etf/browser/mkt")
# Sorry for the ugly regex
n <- gsub("^(\\w+)\\s?(.*)$", "\\1", 
          gsub("(.*)(Showing 1 - 20 of )(.*)", "\\3",  
               L[grep("Showing 1 - 20", L)]))
URL <- paste0("http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=", n)
#http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=1442

Now, you can extract the Tickers from the table on that page

library(XML)
tbl <- readHTMLTable(URL, stringsAsFactors=FALSE)
dat <- tbl[[tail(grep("Ticker", tbl), 1)]][-1, ]
colnames(dat) <- dat[1, ]
dat <- dat[-1, ]
etfs <- dat$Ticker # All ETF tickers from yahoo
length(etfs)
#[1] 1442
head(etfs)
#[1] "DGAZ" "TAGS" "GASX" "KOLD" "DWTI" "RTSA"

That's about all the help I can offer, but you could do something similar to get some of the futures they offer by scraping these pages (These are only U.S. futures)

http://finance.yahoo.com/indices?e=futures, http://finance.yahoo.com/futures?t=energy, http://finance.yahoo.com/futures?t=metals, http://finance.yahoo.com/futures?t=grains, http://finance.yahoo.com/futures?t=livestock, http://finance.yahoo.com/futures?t=softs, http://finance.yahoo.com/futures?t=indices,

And, for U.S. and non-U.S. indices, you could scrape these pages

http://finance.yahoo.com/intlindices?e=americas, http://finance.yahoo.com/intlindices?e=asia, http://finance.yahoo.com/intlindices?e=europe, http://finance.yahoo.com/intlindices?e=africa, http://finance.yahoo.com/indices?e=dow_jones, http://finance.yahoo.com/indices?e=new_york, http://finance.yahoo.com/indices?e=nasdaq, http://finance.yahoo.com/indices?e=sp, http://finance.yahoo.com/indices?e=other, http://finance.yahoo.com/indices?e=treasury, http://finance.yahoo.com/indices?e=commodities

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I believe this error caused because of downloading SRC instead of BINARY from Maven site. Please make sure to download Binary zip.

Because the below path, you will get only when you download SRC:

M2_HOME C:\apache-maven-3.0.4\apache-maven\src

enter image description here

How to check if an object is a list or tuple (but not string)?

Generally speaking, the fact that a function which iterates over an object works on strings as well as tuples and lists is more feature than bug. You certainly can use isinstance or duck typing to check an argument, but why should you?

That sounds like a rhetorical question, but it isn't. The answer to "why should I check the argument's type?" is probably going to suggest a solution to the real problem, not the perceived problem. Why is it a bug when a string is passed to the function? Also: if it's a bug when a string is passed to this function, is it also a bug if some other non-list/tuple iterable is passed to it? Why, or why not?

I think that the most common answer to the question is likely to be that developers who write f("abc") are expecting the function to behave as though they'd written f(["abc"]). There are probably circumstances where it makes more sense to protect developers from themselves than it does to support the use case of iterating across the characters in a string. But I'd think long and hard about it first.

How to create permanent PowerShell Aliases

Just to add to this list of possible locations...

This didn't work for me: \Users\{ME}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

However this did: \Users\{ME}\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

If you don't have a profile or you're looking to set one up, run the following command, it will create the folder/files necessary and even tell you where it lives! New-Item -path $profile -type file -force

Android view layout_width - how to change programmatically?

I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.

View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);

Make elasticsearch only return certain fields?

A REST API GET request could be made with '_source' parameter.

Example Request

http://localhost:9200/opt_pr/_search?q=SYMBOL:ITC AND OPTION_TYPE=CE AND TRADE_DATE=2017-02-10 AND EXPIRY_DATE=2017-02-23&_source=STRIKE_PRICE

Response

{
"took": 59,
"timed_out": false,
"_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
},
"hits": {
    "total": 104,
    "max_score": 7.3908954,
    "hits": [
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLc",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 160
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLh",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 185
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLi",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 190
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLm",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 210
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLp",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 225
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLr",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 235
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLw",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 260
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uL5",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 305
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLd",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 165
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLy",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 270
            }
        }
    ]
}

}

Cannot implicitly convert type 'int?' to 'int'.

You can change the last line to following (assuming you want to return 0 when there is nothing in db):

return OrdersPerHour == null ? 0 : OrdersPerHour.Value;

Add disabled attribute to input element using Javascript

Working code from my sources:

HTML WORLD

<select name="select_from" disabled>...</select>

JS WORLD

var from = jQuery('select[name=select_from]');

//add disabled
from.attr('disabled', 'disabled');



//remove it
from.removeAttr("disabled");

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

Foreign key constraints: When to use ON UPDATE and ON DELETE

Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.

For example if you delete a record using ORM, and your DELETE CASCADE will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.

How to save traceback / sys.exc_info() values in a variable?

Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.

Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.

Remember to import traceback.

Here's the output from traceback.extract_stack(). Formatting added for readability.

>>> traceback.extract_stack()
[
   ('<string>', 1, '<module>', None),
   ('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
   ('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
   ('<pyshell#1>', 1, '<module>', None)
]

Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.

>>> ''.join(traceback.format_stack())
'  File "<string>", line 1, in <module>\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
       ret = method(*args, **kwargs)\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
       exec(code, self.locals)\n  File "<pyshell#2>", line 1, in <module>\n'

Rails where condition using NOT NIL

With Rails 4 it's easy:

 Foo.includes(:bar).where.not(bars: {id: nil})

See also: http://guides.rubyonrails.org/active_record_querying.html#not-conditions