Programs & Examples On #Embeddedwebserver

Either a light-weight web server for embedded systems, or a web server embedded within an application

How to use group by with union in t-sql

Identifying the column is easy:

SELECT  *
FROM    ( SELECT    id,
                    time
          FROM      dbo.a
          UNION
          SELECT    id,
                    time
          FROM      dbo.b
        )
GROUP BY id

But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION rather than UNION ALL, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).

So, for example, change the first line to SELECT id, MAX(time) or the like!

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.

How to start an application without waiting in a batch file?

If your exe takes arguments,

start MyApp.exe -arg1 -arg2

What is the python "with" statement designed for?

See PEP 343 - The 'with' statement, there is an example section at the end.

... new statement "with" to the Python language to make it possible to factor out standard uses of try/finally statements.

How to run Selenium WebDriver test cases in Chrome

You need to download the executable driver from: ChromeDriver Download

Then use the following before creating the driver object (already shown in the correct order):

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();

This was extracted from the most useful guide from the ChromeDriver Documentation.

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

I spent hours last night working out why my programmatically generated table crashed on [myTable setDataSource:self]; It was OK commenting out and popping up an empty table, but crashed every time I tried to reach the datasource;

I had the delegation set up in the h file: @interface myViewController : UIViewController

I had the data source code in my implementation and still BOOM!, crash every time! THANK YOU to "xxd" (nr 9): adding that line of code solved it for me! In fact I am launching a table from a IBAction button, so here is my full code:

    - (IBAction)tapButton:(id)sender {

    UIViewController* popoverContent = [[UIViewController alloc]init];

    UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];
    popoverView.backgroundColor = [UIColor greenColor];
    popoverContent.view = popoverView;

    //Add the table
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)         style:UITableViewStylePlain];

   // NEXT THE LINE THAT SAVED MY SANITY Without it the program built OK, but crashed when      tapping the button!

    [table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    table.delegate=self;
    [table setDataSource:self];
    [popoverView addSubview:table];
    popoverContent.contentSizeForViewInPopover =
    CGSizeMake(200, 300);

    //create a popover controller
    popoverController3 = [[UIPopoverController alloc]
                          initWithContentViewController:popoverContent];
    CGRect popRect = CGRectMake(self.tapButton.frame.origin.x,
                                self.tapButton.frame.origin.y,
                                self.tapButton.frame.size.width,
                                self.tapButton.frame.size.height);


    [popoverController3 presentPopoverFromRect:popRect inView:self.view   permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];



   }


   #Table view data source in same m file

   - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
   {
    NSLog(@"Sections in table");
    // Return the number of sections.
    return 1;
   }

   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
  {
    NSLog(@"Rows in table");

    // Return the number of rows in the section.
    return myArray.count;
   }

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath    *)indexPath
    {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSString *myValue;

    //This is just some test array I created:
    myValue=[myArray objectAtIndex:indexPath.row];

    cell.textLabel.text=myValue;
    UIFont *myFont = [ UIFont fontWithName: @"Arial" size: 12.0 ];
    cell.textLabel.font  = myFont;

    return cell;
   }

By the way: the button must be linked up with as an IBAction and as a IBOutlet if you want to anchor the popover to it.

UIPopoverController *popoverController3 is declared in the H file directly after @interface between {}

UIView touch event in controller

Swift 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Swift 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

How can I open a popup window with a fixed size using the HREF tag?

This should work

<a href="javascript:window.open('document.aspx','mywindowtitle','width=500,height=150')">open window</a>

How to start anonymous thread class

Leaving this here for future reference, but its an answer too.

new Thread(() -> whatever()).start();

calculating execution time in c++

I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..

Change the mouse pointer using JavaScript

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

For asp.net core version 2.1 make sure to add the following package to fix the problem. (At least this fix the issue using SQLite)

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

Here is the reference of the documentation using SQLite with entity framework core. https://docs.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite

How do I solve the INSTALL_FAILED_DEXOPT error?

I had this error testing on a real device. Clearing cache/uninstalling, restarting everything didn't work for me, deleting the contents of the build folder did :) (Android studio)

What USB driver should we use for the Nexus 5?

Everything else here failed for me initially (it kept coming up as an MTP device no matter how many times I uninstalled and restarted).

However, by going and enabling USB debugging, it worked. Just do this:

  1. Uninstall the Nexus 5 driver
  2. Disconnect from the computer
  3. Enable developer options, see How to Enable Developer Options on the Nexus 5 & KitKat.
  4. Enable USB debugging: Go to Settings -> Developer Options -> USB Debugging
  5. Reconnect
  6. It will probably fail to install all drivers. Go update the drivers as described in other answers.

PHPMailer character encoding issues

I was getting &oacute; in $mail->Subject /w PHPMailer.

So for me the complete solution is:

// Your Subject with tildes. Example.
$someSubjectWithTildes = 'Subscripción España';

$mailer->CharSet = 'UTF-8';
$mailer->Encoding = 'quoted-printable';
$mailer->Subject = html_entity_decode($someSubjectWithTildes);

Hope it helps.

Foreign key constraint may cause cycles or multiple cascade paths?

This is because Emplyee might have Collection of other entity say Qualifications and Qualification might have some other collection Universities e.g.

public class Employee{
public virtual ICollection<Qualification> Qualifications {get;set;}

}

public class Qualification{

public Employee Employee {get;set;}

public virtual ICollection<University> Universities {get;set;}

}

public class University{

public Qualification Qualification {get;set;}

}

On DataContext it could be like below

protected override void OnModelCreating(DbModelBuilder modelBuilder){

modelBuilder.Entity<Qualification>().HasRequired(x=> x.Employee).WithMany(e => e.Qualifications);
modelBuilder.Entity<University>.HasRequired(x => x.Qualification).WithMany(e => e.Universities);

}

in this case there is chain from Employee to Qualification and From Qualification to Universities. So it was throwing same exception to me.

It worked for me when I changed

    modelBuilder.Entity<Qualification>().**HasRequired**(x=> x.Employee).WithMany(e => e.Qualifications); 

To

    modelBuilder.Entity<Qualification>().**HasOptional**(x=> x.Employee).WithMany(e => e.Qualifications);

What's the difference between lists and tuples?

First of all, they both are the non-scalar objects (also known as a compound objects) in Python.

  • Tuples, ordered sequence of elements (which can contain any object with no aliasing issue)
    • Immutable (tuple, int, float, str)
    • Concatenation using + (brand new tuple will be created of course)
    • Indexing
    • Slicing
    • Singleton (3,) # -> (3) instead of (3) # -> 3
  • List (Array in other languages), ordered sequence of values
    • Mutable
    • Singleton [3]
    • Cloning new_array = origin_array[:]
    • List comprehension [x**2 for x in range(1,7)] gives you [1,4,9,16,25,36] (Not readable)

Using list may also cause an aliasing bug (two distinct paths pointing to the same object).

How to pretty print nested dictionaries?

From this link:

def prnDict(aDict, br='\n', html=0,
            keyAlign='l',   sortKey=0,
            keyPrefix='',   keySuffix='',
            valuePrefix='', valueSuffix='',
            leftMargin=0,   indent=1 ):
    '''
return a string representive of aDict in the following format:
    {
     key1: value1,
     key2: value2,
     ...
     }

Spaces will be added to the keys to make them have same width.

sortKey: set to 1 if want keys sorted;
keyAlign: either 'l' or 'r', for left, right align, respectively.
keyPrefix, keySuffix, valuePrefix, valueSuffix: The prefix and
   suffix to wrap the keys or values. Good for formatting them
   for html document(for example, keyPrefix='<b>', keySuffix='</b>'). 
   Note: The keys will be padded with spaces to have them
         equally-wide. The pre- and suffix will be added OUTSIDE
         the entire width.
html: if set to 1, all spaces will be replaced with '&nbsp;', and
      the entire output will be wrapped with '<code>' and '</code>'.
br: determine the carriage return. If html, it is suggested to set
    br to '<br>'. If you want the html source code eazy to read,
    set br to '<br>\n'

version: 04b52
author : Runsun Pan
require: odict() # an ordered dict, if you want the keys sorted.
         Dave Benjamin 
         http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/161403
    '''

    if aDict:

        #------------------------------ sort key
        if sortKey:
            dic = aDict.copy()
            keys = dic.keys()
            keys.sort()
            aDict = odict()
            for k in keys:
                aDict[k] = dic[k]

        #------------------- wrap keys with ' ' (quotes) if str
        tmp = ['{']
        ks = [type(x)==str and "'%s'"%x or x for x in aDict.keys()]

        #------------------- wrap values with ' ' (quotes) if str
        vs = [type(x)==str and "'%s'"%x or x for x in aDict.values()] 

        maxKeyLen = max([len(str(x)) for x in ks])

        for i in range(len(ks)):

            #-------------------------- Adjust key width
            k = {1            : str(ks[i]).ljust(maxKeyLen),
                 keyAlign=='r': str(ks[i]).rjust(maxKeyLen) }[1]

            v = vs[i]        
            tmp.append(' '* indent+ '%s%s%s:%s%s%s,' %(
                        keyPrefix, k, keySuffix,
                        valuePrefix,v,valueSuffix))

        tmp[-1] = tmp[-1][:-1] # remove the ',' in the last item
        tmp.append('}')

        if leftMargin:
          tmp = [ ' '*leftMargin + x for x in tmp ]

        if html:
            return '<code>%s</code>' %br.join(tmp).replace(' ','&nbsp;')
        else:
            return br.join(tmp)     
    else:
        return '{}'

'''
Example:

>>> a={'C': 2, 'B': 1, 'E': 4, (3, 5): 0}

>>> print prnDict(a)
{
 'C'   :2,
 'B'   :1,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, sortKey=1)
{
 'B'   :1,
 'C'   :2,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, keyPrefix="<b>", keySuffix="</b>")
{
 <b>'C'   </b>:2,
 <b>'B'   </b>:1,
 <b>'E'   </b>:4,
 <b>(3, 5)</b>:0
}

>>> print prnDict(a, html=1)
<code>{
&nbsp;'C'&nbsp;&nbsp;&nbsp;:2,
&nbsp;'B'&nbsp;&nbsp;&nbsp;:1,
&nbsp;'E'&nbsp;&nbsp;&nbsp;:4,
&nbsp;(3,&nbsp;5):0
}</code>

>>> b={'car': [6, 6, 12], 'about': [15, 9, 6], 'bookKeeper': [9, 9, 15]}

>>> print prnDict(b, sortKey=1)
{
 'about'     :[15, 9, 6],
 'bookKeeper':[9, 9, 15],
 'car'       :[6, 6, 12]
}

>>> print prnDict(b, keyAlign="r")
{
        'car':[6, 6, 12],
      'about':[15, 9, 6],
 'bookKeeper':[9, 9, 15]
}
'''

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

What is ".NET Core"?

From the .NET blog Announcing .NET 2015 Preview: A New Era for .NET:

.NET Core has two major components. It includes a small runtime that is built from the same codebase as the .NET Framework CLR. The .NET Core runtime includes the same GC and JIT (RyuJIT), but doesn’t include features like Application Domains or Code Access Security. The runtime is delivered via NuGet, as part of the [ASP.NET Core] package.

.NET Core also includes the base class libraries. These libraries are largely the same code as the .NET Framework class libraries, but have been factored (removal of dependencies) to enable us to ship a smaller set of libraries. These libraries are shipped as System.* NuGet packages on NuGet.org.

And:

[ASP.NET Core] is the first workload that has adopted .NET Core. [ASP.NET Core] runs on both the .NET Framework and .NET Core. A key value of [ASP.NET Core] is that it can run on multiple versions of [.NET Core] on the same machine. Website A and website B can run on two different versions of .NET Core on the same machine, or they can use the same version.

In short: first, there was the Microsoft .NET Framework, which consists of a runtime that executes application and library code, and a nearly fully documented standard class library.

The runtime is the Common Language Runtime, which implements the Common Language Infrastructure, works with The JIT compiler to run the CIL (formerly MSIL) bytecode.

Microsoft's specification and implementation of .NET were, given its history and purpose, very Windows- and IIS-centered and "fat". There are variations with fewer libraries, namespaces and types, but few of them were useful for web or desktop development or are troublesome to port from a legal standpoint.

So in order to provide a non-Microsoft version of .NET, which could run on non-Windows machines, an alternative had to be developed. Not only the runtime has to be ported for that, but also the entire Framework Class Library to become well-adopted. On top of that, to be fully independent from Microsoft, a compiler for the most commonly used languages will be required.

Mono is one of few, if not the only alternative implementation of the runtime, which runs on various OSes besides Windows, almost all namespaces from the Framework Class Library as of .NET 4.5 and a VB and C# compiler.

Enter .NET Core: an open-source implementation of the runtime, and a minimal base class library. All additional functionality is delivered through NuGet packages, deploying the specific runtime, framework libraries and third-party packages with the application itself.

ASP.NET Core is a new version of MVC and WebAPI, bundled together with a thin HTTP server abstraction, that runs on the .NET Core runtime - but also on the .NET Framework.

How to change the Text color of Menu item in Android?

If you are using the new Toolbar, with the theme Theme.AppCompat.Light.NoActionBar, you can style it in the following way.

 <style name="ToolbarTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:textColorPrimary">@color/my_color1</item>
    <item name="android:textColorSecondary">@color/my_color2</item>
    <item name="android:textColor">@color/my_color3</item>
 </style>`

According to the results I got,
android:textColorPrimary is the text color displaying the name of your activity, which is the primary text of the toolbar.

android:textColorSecondary is the text color for subtitle and more options (3 dot) button. (Yes, it changed its color according to this property!)

android:textColor is the color for all other text including the menu.

Finally set the theme to the Toolbar

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:theme="@style/ToolbarTheme"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"/>

How to make the checkbox unchecked by default always

An easy way , only HTML, no javascript, no jQuery

<input name="box1" type="hidden"   value="0" />
<input name="box1" type="checkbox" value="1" />

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

How to remove the hash from window.location (URL) with JavaScript without page refresh?

Here is another solution to change the location using href and clear the hash without scrolling.

The magic solution is explained here. Specs here.

const hash = window.location.hash;
history.scrollRestoration = 'manual';
window.location.href = hash;    
history.pushState('', document.title, window.location.pathname);

NOTE: The proposed API is now part of WhatWG HTML Living Standard

ng serve not detecting file changes automatically

try this. If you do like this you don't need to fire always any command You need to fire only one time

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

cat /proc/sys/fs/inotify/max_user_watches

fs.inotify.max_user_watches=524288

How do I delete all messages from a single queue using the CLI?

I guess its late but for others reference, this can be done with pika

import pika
host_ip = #host ip
channel = pika.BlockingConnection(pika.ConnectionParameters(host_ip,
                                                        5672,
                                                        "/",
credentials=pika.PlainCredentials("username","pwd"))).channel()
print "deleting queue..", channel.queue_delete(queue=queue_name)

Yarn: How to upgrade yarn version using terminal?

yarn policies set-version

will download the latest stable release

Referenced yarn docs https://yarnpkg.com/lang/en/docs/cli/policies/#toc-policies-set-version

round a single column in pandas

No need to use for loop. It can be directly applied to a column of a dataframe

sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)

Why does Maven have such a bad rep?

The short answer: I've found it very difficult to maintain a Maven build system, and I would like to switch to Gradle as soon as I can.

I've been working with Maven for over four years. I would call myself an expert on build systems because in the last (at least) five companies I've been in, I've done major renovations on the build/deploy infrastructure.

Some of the lessons I've learned:

  • Most developers tend not to spend a lot of time thinking about build systems; as a result, the build turns into a spaghetti mess of hacks, but they do appreciate it when that mess is cleaned up and rationalized.
  • In dealing with complexity, I would rather have a transparent system that exposes the complexity (like Ant) than one that tries to make complex things simple by imposing rigid restrictions, like Maven. Think of Linux vs. Windows.
  • Maven has a lot of holes in functionality which require byzantine workarounds. This leads to POM files that are incomprehensible and unmaintainable.
  • Ant is super-flexible and understandable, but Ant files can get pretty big too, because it's so low-level.
  • For any significant project, developers have to create their own build/deploy structure beyond what the tool provides; the suitability of the structure to the project has a lot to do with how easy it is to maintain. The best tools will support you in creating a structure and not fight you.

I've looked into Gradle a bit and it looks like it has the potential to be the best of both worlds, allowing a mix of declarative and procedural build description.

XML Serialize generic list of serializable objects

I think it's best if you use methods with generic arguments, like the following :

public static void SerializeToXml<T>(T obj, string fileName)
{
    using (var fileStream = new FileStream(fileName, FileMode.Create))
    { 
        var ser = new XmlSerializer(typeof(T)); 
        ser.Serialize(fileStream, obj);
    }
}

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    var ser = new XmlSerializer(typeof(T));
    using (var tr = new StringReader(xml))
    {
        result = (T)ser.Deserialize(tr);
    }
    return result;
}

php string to int

Use str_replace to remove the spaces first ?

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

are you running the example from the node_modules folder?

They are not supposed to be ran from there.

Create the following file on your project instead:

post-data.js

var Curl = require( 'node-libcurl' ).Curl,
   querystring = require( 'querystring' );

var curl = new Curl(),
  url  = 'http://posttestserver.com/post.php',
data = { //Data to send, inputName : value
    'input-arr[0]' : 'input-arr-val0',
    'input-arr[1]' : 'input-arr-val1',
    'input-arr[2]' : 'input-arr-val2',
    'input-name' : 'input-val'
};

//You need to build the query string, 
// node has this helper function, but it's limited for real use cases (no support for 
array values for example)
data = querystring.stringify( data );

 curl.setOpt( Curl.option.URL, url );
 curl.setOpt( Curl.option.POSTFIELDS, data );
 curl.setOpt( Curl.option.HTTPHEADER, ['User-Agent: node-libcurl/1.0'] );
 curl.setOpt( Curl.option.VERBOSE, true );

 console.log( querystring.stringify( data ) );

 curl.perform();

 curl.on( 'end', function( statusCode, body ) {

console.log( body );

this.close();
});

curl.on( 'error', curl.close.bind( curl ) );

Run with node post-data.js

ref:https://github.com/JCMais/node-libcurl/issues/98

Writing a Python list of lists to a csv file

If you don't want to import csv module for that, you can write a list of lists to a csv file using only Python built-ins

with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

Find position of a node using xpath

I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.

Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:

count(attr/value[.='$TARGET']/preceding-sibling::*)+1

Additionally it was pointed out that to save a few characters of space, the following would work as well:

count(attr/value[.='$TARGET']/preceding::*) + 1

I also posted a prettier version of this at Novell's Cool Solutions: Using XPATH to get the position node

How to remove trailing whitespace in code, using another script?

It seems, fileinput.FileInput is a generator. As such, you can only iterate over it once, then all items have been consumed and calling it's next method raises StopIteration. If you want to iterate over the lines more than once, you can put them in a list:

list(fileinput.FileInput('test.txt'))

Then call rstrip on them.

Can't specify the 'async' modifier on the 'Main' method of a console app

When the C# 5 CTP was introduced, you certainly could mark Main with async... although it was generally not a good idea to do so. I believe this was changed by the release of VS 2013 to become an error.

Unless you've started any other foreground threads, your program will exit when Main completes, even if it's started some background work.

What are you really trying to do? Note that your GetList() method really doesn't need to be async at the moment - it's adding an extra layer for no real reason. It's logically equivalent to (but more complicated than):

public Task<List<TvChannel>> GetList()
{
    return new GetPrograms().DownloadTvChannels();
}

How can I view live MySQL queries?

You can run the MySQL command SHOW FULL PROCESSLIST; to see what queries are being processed at any given time, but that probably won't achieve what you're hoping for.

The best method to get a history without having to modify every application using the server is probably through triggers. You could set up triggers so that every query run results in the query being inserted into some sort of history table, and then create a separate page to access this information.

Do be aware that this will probably considerably slow down everything on the server though, with adding an extra INSERT on top of every single query.


Edit: another alternative is the General Query Log, but having it written to a flat file would remove a lot of possibilities for flexibility of displaying, especially in real-time. If you just want a simple, easy-to-implement way to see what's going on though, enabling the GQL and then using running tail -f on the logfile would do the trick.

Linq to SQL .Sum() without group ... into

Try this:

var itemsInCart = from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select o.WishListItem.Price;

return Convert.ToDecimal(itemsInCart.Sum());

I think it's more simple!

C program to check little vs. big endian

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory
          ----->
    +----+----+----+----+
    |0x01|0x00|0x00|0x00|
    +----+----+----+----+
    A
    |
   &x

so (char*)(&x) == 1, and *y+48 == '1'.

If it is big endian, it will be:

    +----+----+----+----+
    |0x00|0x00|0x00|0x01|
    +----+----+----+----+
    A
    |
   &x

so this one will be '0'.

How to test if a file is a directory in a batch script?

Here's a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.

@echo off
if [%1]==[] goto usage

for /f "delims=" %%i in ("%~1") do set MYPATH="%%~fi"
pushd %MYPATH% 2>nul
if errorlevel 1 goto notdir
goto isdir

:notdir
echo not a directory
goto exit

:isdir
popd
echo is a directory
goto exit

:usage
echo Usage:  %0 DIRECTORY_TO_TEST

:exit

Sample output with the above saved as "isdir.bat":

C:\>isdir c:\Windows\system32
is a directory

C:\>isdir c:\Windows\system32\wow32.dll
not a directory

C:\>isdir c:\notadir
not a directory

C:\>isdir "C:\Documents and Settings"
is a directory

C:\>isdir \
is a directory

C:\>isdir \\ninja\SharedDocs\cpu-z
is a directory

C:\>isdir \\ninja\SharedDocs\cpu-z\cpuz.ini
not a directory

How do I install a plugin for vim?

I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.

Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).

Import existing source code to GitHub

Actually, if you opt for creating an empty repo on GitHub it gives you exact instructions that you can almost copy and paste into your terminal which are (at this point in time):

…or create a new repository on the command line

echo "# ..." >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin [email protected]:<user>/<repo>.git
git push -u origin master

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

Get current time in seconds since the Epoch on Linux, Bash

This is an extension to what @pellucide has done, but for Macs:

To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)

$ date -j -f "%b %d %Y %T" "Oct 21 1973 00:00:00" "+%s"
120034800

Please note, that for completeness, I have added the time part to the format. The reason being is that date will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the '00:00:00' part, it will add the time automatically. Such that "Oct 21 1973" will be parsed as "Oct 21 1973 16:19:00". That may not be what you want.

To convert your timestamp back to a date:

$ date -j -r 120034800
Sun Oct 21 00:00:00 PDT 1973

Apple's man page for the date implementation: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/date.1.html

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

I have this function...

var escapeURIparam = function(url) {
    if (encodeURIComponent) url = encodeURIComponent(url);
    else if (encodeURI) url = encodeURI(url);
    else url = escape(url);
    url = url.replace(/\+/g, '%2B'); // Force the replacement of "+"
    return url;
};

What's the most efficient way to test two integer ranges for overlap?

You have the most efficient representation already - it's the bare minimum that needs to be checked unless you know for sure that x1 < x2 etc, then use the solutions others have provided.

You should probably note that some compilers will actually optimise this for you - by returning as soon as any of those 4 expressions return true. If one returns true, so will the end result - so the other checks can just be skipped.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

PackagesNotFoundError: The following packages are not available from current channels:

It may be that your condas channels need a wakeup call... with

conda update --all

For me it worked. More information: https://www.anaconda.com/keeping-anaconda-date/

How do I assign a port mapping to an existing Docker container?

we an use handy tools like ssh to accomplish this easily.

I was using ubuntu host and ubuntu based docker image.

  1. Inside docker have openssh-client installed.
  2. Outside docker (host) have openssh-server server installed.

when a new port is needed to be mapped out,

inside the docker run the following command

ssh -R8888:localhost:8888 <username>@172.17.0.1

172.17.0.1 was the ip of the docker interface (you can get this by running ifconfig docker0 | grep "inet addr" | cut -f2 -d":" | cut -f1 -d" " on the host).

here I had local 8888 port mapped back to the hosts 8888. you can change the port as needed.

if you need one more port, you can kill the ssh and add one more line of -R to it with the new port.

I have tested this with netcat.

PHP Fatal error: Cannot access empty property

This way you can create a new object with a custom property name.

$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);

Now you can reach it like:

echo $a->foo;  //returns bar

Embedding DLLs in a compiled executable

Generally you would need some form of post build tool to perform an assembly merge like you are describing. There is a free tool called Eazfuscator (eazfuscator.blogspot.com/) which is designed for bytecode mangling that also handles assembly merging. You can add this into a post build command line with Visual Studio to merge your assemblies, but your mileage will vary due to issues that will arise in any non trival assembly merging scenarios.

You could also check to see if the build make untility NANT has the ability to merge assemblies after building, but I am not familiar enough with NANT myself to say whether the functionality is built in or not.

There are also many many Visual Studio plugins that will perform assembly merging as part of building the application.

Alternatively if you don't need this to be done automatically, there are a number of tools like ILMerge that will merge .net assemblies into a single file.

The biggest issue I've had with merging assemblies is if they use any similar namespaces. Or worse, reference different versions of the same dll (my problems were generally with the NUnit dll files).

How does the Spring @ResponseBody annotation work?

First of all, the annotation doesn't annotate List. It annotates the method, just as RequestMapping does. Your code is equivalent to

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Now what the annotation means is that the returned value of the method will constitute the body of the HTTP response. Of course, an HTTP response can't contain Java objects. So this list of accounts is transformed to a format suitable for REST applications, typically JSON or XML.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the @RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.

Visual Studio keyboard shortcut to display IntelliSense

In Visual Studio 2015 this shortcut opens a preview of the definition which even works through typedefs and #defines.

Ctrl + , (comma)

Enter image description here

Is there a way to set background-image as a base64 encoded image?

Try this, I have got success response ..it's working

$("#divId").css("background-image", "url('data:image/png;base64," + base64String + "')");

Should I use string.isEmpty() or "".equals(string)?

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

How do I install a color theme for IntelliJ IDEA 7.0.x

Themes downloaded from IntelliJ can be installed as a Plugin.

Take these steps:

Preferences -> Plugins -> GearIcon -> Install Plugin from disk -> Reset your IDE ->  Preferences -> Appearance -> Theme -> Select your theme.

Proxy with urllib2

To use the default system proxies (e.g. from the http_support environment variable), the following works for the current request (without installing it into urllib2 globally):

url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()

How to inject window into a service?

To get it to work on Angular 2.1.1 I had to @Inject window using a string

  constructor( @Inject('Window') private window: Window) { }

and then mock it like this

beforeEach(() => {
  let windowMock: Window = <any>{ };
  TestBed.configureTestingModule({
    providers: [
      ApiUriService,
      { provide: 'Window', useFactory: (() => { return windowMock; }) }
    ]
  });

and in the ordinary @NgModule I provide it like this

{ provide: 'Window', useValue: window }

Converting stream of int's to char's in java

If you want to simply convert int 5 to char '5': (Only for integers 0 - 9)

int i = 5;
char c = (char) ('0' + i); // c is now '5';

How do I see which version of Swift I'm using?

Updated answer for how to find which version of Swift your project is using in a few click in Xcode 12 to help out rookies like me.

  1. Click on your Project (top level Blue Icon in the left hand pane)
  2. Click on Build Settings (5th item in the Project > Header)
  3. Scroll down to Swift Compiler - Language, and look at the dropdown.

enter image description here

Cannot set property 'innerHTML' of null

Here Is my snippet try it. I hope it will helpfull for u.

_x000D_
_x000D_
<!DOCTYPE HTML>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  _x000D_
<div id="hello"></div>_x000D_
  _x000D_
<script type ="text/javascript">_x000D_
    what();_x000D_
    function what(){_x000D_
        document.getElementById('hello').innerHTML = 'hi';_x000D_
    };_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Searching word in vim?

like this:

/\<word\>

\< means beginning of a word, and \> means the end of a word,

Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*' to search forward in the file or '#' to search backwards.

How to move (and overwrite) all files from one directory to another?

mv -f source target

From the man page:

-f, --force
          do not prompt before overwriting

Docker - Cannot remove dead container

Running on Centos7 & Docker 1.8.2, I was unable to use Zgr3doo's solution to umount by devicemapper ( I think the response I got was that the volume wasn't mounted/found. )

I think I also had a similar thing happen with sk8terboi87 ? 's answer: I believe the message was that the volumes couldn't be unmounted, and it listed the specific volumes that it tried to umount in order to delete the dead containers.

What did work for me was stopping docker first, and then deleting the directories manually. I was able to determine which ones they were by the error output of previous command to delete all the dead containers.

Apologies for the vague descriptions above. I found this SO question days after I handled the dead containers. .. However, I noticed a similar pattern today:

$ sudo docker stop fervent_fermi; sudo docker rm fervent_fermi fervent_fermi
Error response from daemon: Cannot destroy container fervent_fermi: Driver devicemapper failed to remove root filesystem a11bae452da3dd776354aae311da5be5ff70ac9ebf33d33b66a24c62c3ec7f35: Device is Busy
Error: failed to remove containers: [fervent_fermi]

$ sudo systemctl docker stop
$ sudo rm -rf /var/lib/docker/devicemapper/mnt/a11bae452da3dd776354aae311da5be5ff70ac9ebf33d33b66a24c62c3ec7f35
$

I did notice, when using this approach that docker re-created the images with different names:

a11bae452da3     trend_av_docker   "bash"   2 weeks ago    Dead    compassionate_ardinghelli

This may have been due to the container being issued with restart=always, however, the container ID matches the ID of the container that previously used the volume that I force-deleted. There were no difficulties deleting this new container:

$ sudo docker rm -v compassionate_ardinghelli
compassionate_ardinghelli

Capture event onclose browser

http://docs.jquery.com/Events/unload#fn

jQuery:

$(window).unload( function () { alert("Bye now!"); } );

or javascript:

window.onunload = function(){alert("Bye now!");}

How to resolve the C:\fakepath?

If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.

Javascript Regex: How to put a variable inside a regular expression?

Here's an pretty useless function that return values wrapped by specific characters. :)

jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/

function getValsWrappedIn(str,c1,c2){
    var rg = new RegExp("(?<=\\"+c1+")(.*?)(?=\\"+c2+")","g"); 
    return str.match(rg);
    }

var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results =  getValsWrappedIn(exampleStr,"(",")")

// Will return array ["5","19","thingy"]
console.log(results)

MySQL Error 1215: Cannot add foreign key constraint

Check the collation of table, using SHOW TABLE STATUS you can check information about the tables, including the collation.

Both tables have to has the same collation.

It's happened to me.

How to use passive FTP mode in Windows command prompt?

Although this doesnt answer the question directly about command line, but from Windows OS, use the Windows Explorer ftp://username@server

this will use Passive Mode by default

For command line, active mode is the default

Linker command failed with exit code 1 - duplicate symbol __TMRbBp

For those that can't get the Thorax's answer to work, what I did was I closed out Xcode, ran pod update on my command line and then reopened the .xcworkspace file. After doing that, I was able to build and run the project.

I am using the Firebase Cocoapod and Xcode version 9.1.

How to join components of a path when you are constructing a URL in Python

You can use urllib.parse.urljoin:

>>> from urllib.parse import urljoin
>>> urljoin('/media/path/', 'js/foo.js')
'/media/path/js/foo.js'

But beware:

>>> urljoin('/media/path', 'js/foo.js')
'/media/js/foo.js'
>>> urljoin('/media/path', '/js/foo.js')
'/js/foo.js'

The reason you get different results from /js/foo.js and js/foo.js is because the former begins with a slash which signifies that it already begins at the website root.

On Python 2, you have to do

from urlparse import urljoin

Change the Value of h1 Element within a Form with JavaScript

Try:


document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";

Encrypt Password in Configuration Files?

Check out jasypt, which is a library offering basic encryption capabilities with minimum effort.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Convert char * to LPWSTR

You may use CString, CStringA, CStringW to do automatic conversions and convert between these types. Further, you may also use CStrBuf, CStrBufA, CStrBufW to get RAII pattern modifiable strings

Pass connection string to code-first DbContext

If you are constructing the connection string within the app then you would use your command of connString. If you are using a connection string in the web config. Then you use the "name" of that string.

How to add and remove classes in Javascript without jQuery

Add & Remove Classes (tested on IE8+)

Add trim() to IE (taken from: .trim() in JavaScript not working in IE)

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add and Remove Classes:

function addClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    element.setAttribute("class",currentClassName + " "+ className);
  }
  else {
    element.setAttribute("class",className); 
  }
}
function removeClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {

    var class2RemoveIndex = currentClassName.indexOf(className);
    if (class2RemoveIndex != -1) {
        var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
        var updatedClassName = currentClassName.replace(class2Remove,"").trim();
        element.setAttribute("class",updatedClassName);
    }
  }
  else {
    element.removeAttribute("class");   
  } 
}

Usage:

var targetElement = document.getElementById("myElement");

addClass(targetElement,"someClass");

removeClass(targetElement,"someClass");

A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

How to bring a window to the front?

There are numerous caveats in the javadoc for the toFront() method which may be causing your problem.

But I'll take a guess anyway, when "only the tab in the taskbar flashes", has the application been minimized? If so the following line from the javadoc may apply:

"If this Window is visible, brings this Window to the front and may make it the focused Window."

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

How to determine whether a year is a leap year?

The whole formula can be contained in a single expression:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

print n, " is a leap year" if is_leap_year(n) else " is not a leap year"

Set adb vendor keys

look at this url Android adb devices unauthorized else briefly do the following:

  1. look for adbkey with not extension in the platform-tools/.android and delete this file
  2. look at C:\Users\*username*\.android) and delete adbkey
  3. C:\Windows\System32\config\systemprofile\.android and delete adbkey

You may find it in one of the directories above. Or just search adbkey in the Parent folders above then locate and delete.

Read input from console in Ruby?

Are you talking about gets?

puts "Enter A"
a = gets.chomp
puts "Enter B"
b = gets.chomp
c = a.to_i + b.to_i
puts c

Something like that?

Update

Kernel.gets tries to read the params found in ARGV and only asks to console if not ARGV found. To force to read from console even if ARGV is not empty use STDIN.gets

Running python script inside ipython

for Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

Key value pairs using JSON

JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.

Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.

So if we have an object:

var myObj = {
    foo:   'bar',
    base:  'ball',
    deep:  {
       java:  'script'
    }
};

We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".

The other way around, we would call window.JSON.parse("a json string like the above");.

JSON.parse() returns a javascript object/array on success.

alert(myObj.deep.java);  // 'script'

window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.

How to change legend size with matplotlib.pyplot

using import matplotlib.pyplot as plt

Method 1: specify the fontsize when calling legend (repetitive)

plt.legend(fontsize=20) # using a size in points
plt.legend(fontsize="x-large") # using a named size

With this method you can set the fontsize for each legend at creation (allowing you to have multiple legends with different fontsizes). However, you will have to type everything manually each time you create a legend.

(Note: @Mathias711 listed the available named fontsizes in his answer)

Method 2: specify the fontsize in rcParams (convenient)

plt.rc('legend',fontsize=20) # using a size in points
plt.rc('legend',fontsize='medium') # using a named size

With this method you set the default legend fontsize, and all legends will automatically use that unless you specify otherwise using method 1. This means you can set your legend fontsize at the beginning of your code, and not worry about setting it for each individual legend.

If you use a named size e.g. 'medium', then the legend text will scale with the global font.size in rcParams. To change font.size use plt.rc(font.size='medium')

Delete specific values from column with where condition?

Try this SQL statement:

update Table set Column =( Column - your val )

How to use onBlur event on Angular2?

You can also use (focusout) event:

Use (eventName) for while binding event to DOM, basically () is used for event binding. Also you can use ngModel to get two way binding for your model. With the help of ngModel you can manipulate model variable value inside your component.

Do this in HTML file

<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">

And in your (component) .ts file

export class AppComponent { 
 model: any;
 constructor(){ }
 someMethodWithFocusOutEvent(){
   console.log('Your method called');
   // Do something here
 }
}

DateTime group by date and hour

Using MySQL I usually do it that way:

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

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

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

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

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

How to include multiple js files using jQuery $.getScript() method

Great answer, adeneo.

It took me a little while to figure out how to make your answer more generic (so that I could load an array of code-defined scripts). Callback gets called when all scripts have loaded and executed. Here is my solution:

    function loadMultipleScripts(scripts, callback){
        var array = [];

        scripts.forEach(function(script){
            array.push($.getScript( script ))
        });

        array.push($.Deferred(function( deferred ){
                    $( deferred.resolve );
                }));

        $.when.apply($, array).done(function(){
                if (callback){
                    callback();
                }
            });
    }

Getting absolute URLs using ASP.NET Core

In a new ASP.Net 5 MVC project in a controller action you can still do this.Context and this.Context.Request It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.

 public IActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        var schema = this.Context.Request.Scheme;

        return View();
    }

Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext

.gitignore for Visual Studio Projects and Solutions

Some project might want to add *.manifest to their visual studio gitignore.io file.

That is because some Visual Studio project properties of new projects are set to generate a manifest file.

See "Manifest Generation in Visual Studio"

But if you have generated them and they are static (not changing over time), then it is a good idea to remove them from the .gitignore file.

That is what a project like Git for Windows just did (for Git 2.24, Q4 2019)

See commit aac6ff7 (05 Sep 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 59438be, 30 Sep 2019)

.gitignore: stop ignoring .manifest files

On Windows, it is possible to embed additional metadata into an executable by linking in a "manifest", i.e. an XML document that describes capabilities and requirements (such as minimum or maximum Windows version).
These XML documents are expected to be stored in .manifest files.

At least some Visual Studio versions auto-generate .manifest files when none is specified explicitly, therefore we used to ask Git to ignore them.

However, we do have a beautiful .manifest file now: compat/win32/git.manifest, so neither does Visual Studio auto-generate a manifest for us, nor do we want Git to ignore the .manifest files anymore.

convert big endian to little endian in C [without using provided func]

As a joke:


#include <stdio.h>

int main (int argc, char *argv[])
{
    size_t sizeofInt = sizeof (int);
    int i;

    union
    {
        int x;
        char c[sizeof (int)];
    } original, swapped;

    original.x = 0x12345678;

    for (i = 0; i < sizeofInt; i++)
        swapped.c[sizeofInt - i - 1] = original.c[i];

    fprintf (stderr, "%x\n", swapped.x);

    return 0;
}

Remove part of string after "."

If the string should be of fixed length, then substr from base R can be used. But, we can get the position of the . with regexpr and use that in substr

substr(a, 1, regexpr("\\.", a)-1)
#[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"   

How do I read and parse an XML file in C#?

  public void ReadXmlFile()
    {
        string path = HttpContext.Current.Server.MapPath("~/App_Data"); // Finds the location of App_Data on server.
        XmlTextReader reader = new XmlTextReader(System.IO.Path.Combine(path, "XMLFile7.xml")); //Combines the location of App_Data and the file name
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    break;
                case XmlNodeType.Text:
                    columnNames.Add(reader.Value);
                    break;
                case XmlNodeType.EndElement:
                    break;
            }
        }
    }

You can avoid the first statement and just specify the path name in constructor of XmlTextReader.

How to embed images in email

As you are aware, everything passed as email message has to be textualized.

  • You must create an email with a multipart/mime message.
  • If you're adding a physical image, the image must be base 64 encoded and assigned a Content-ID (cid). If it's an URL, then the <img /> tag is sufficient (the url of the image must be linked to a Source ID).

A Typical email example will look like this:

From: foo1atbar.net
To: foo2atbar.net
Subject: A simple example
Mime-Version: 1.0
Content-Type: multipart/related; boundary="boundary-example"; type="text/html"

--boundary-example
Content-Type: text/html; charset="US-ASCII"

... text of the HTML document, which might contain a URI
referencing a resource in another body part, for example
through a statement such as:
<IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">

--boundary-example
Content-Location: CID:somethingatelse ; this header is disregarded
Content-ID: <foo4atfoo1atbar.net>
Content-Type: IMAGE/GIF
Content-Transfer-Encoding: BASE64

R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv
cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV
wbGljYXRpb24gcHJvaGliaXRlZC4A etc...

--boundary-example--

As you can see, the Content-ID: <foo4atfoo1atbar.net> ID is matched to the <IMG> at SRC="cid:foo4atfoo1atbar.net". That way, the client browser will render your image as a content and not as an attachement.

Hope this helps.

Renaming a directory in C#

There is no difference between moving and renaming; you should simply call Directory.Move.

In general, if you're only doing a single operation, you should use the static methods in the File and Directory classes instead of creating FileInfo and DirectoryInfo objects.

For more advice when working with files and directories, see here.

Why should you use strncpy instead of strcpy?

strncpy fills the destination up with '\0' for the size of source, eventhough the size of the destination is smaller....

manpage:

If the length of src is less than n, strncpy() pads the remainder of dest with null bytes.

and not only the remainder...also after this until n characters is reached. And thus you get an overflow... (see the man page implementation)

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

OAuth: how to test with local URLs?

I found xip.io which automatically converts a fixed url to a embedded localhost domain.

For example lets say your localhost server is running on 127.0.0.1:8000 You can go to http://www.127.0.0.1.xip.io:5555/ to access this server. You can then add this address to Oauth configuration for Facebook or Google.

What is a constant reference? (not a reference to a constant)

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

Passing parameters in Javascript onClick event

This happens because the i propagates up the scope once the function is invoked. You can avoid this issue using a closure.

for (var i = 0; i < 10; i++) {
   var link = document.createElement('a');
   link.setAttribute('href', '#');
   link.innerHTML = i + '';
   link.onclick = (function() {
      var currentI = i;
      return function() { 
          onClickLink(currentI + '');
      }
   })();
   div.appendChild(link);
   div.appendChild(document.createElement('BR'));
}

Or if you want more concise syntax, I suggest you use Nick Craver's solution.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

SOAP PHP fault parsing WSDL: failed to load external entity?

I had the same problem.

This php setting solved my problem:

allow_url_fopen -> 1

Is it possible to deserialize XML into List<T>?

I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.

Take a look (it works for me):

private void SerializeParams<T>(XDocument doc, List<T> paramList)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());

        System.Xml.XmlWriter writer = doc.CreateWriter();

        serializer.Serialize(writer, paramList);

        writer.Close();           
    }

private List<T> DeserializeParams<T>(XDocument doc)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));

        System.Xml.XmlReader reader = doc.CreateReader();

        List<T> result = (List<T>)serializer.Deserialize(reader);
        reader.Close();

        return result;
    }

So you can serialize whatever list you want! You don't need to specify the list type every time.

        List<AssemblyBO> list = new List<AssemblyBO>();
        list.Add(new AssemblyBO());
        list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
        XDocument doc = new XDocument();
        SerializeParams<T>(doc, list);
        List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);

Java: how can I split an ArrayList in multiple small ArrayLists?

Create a new list and add a sublist view of the source list using the addAll() method to create a new sublist

List<T> newList = new ArrayList<T>();
newList.addAll(sourceList.subList(startIndex, endIndex));

List files ONLY in the current directory

this can be done with os.walk()

python 3.5.2 tested;

import os
for root, dirs, files in os.walk('.', topdown=True):
    dirs.clear() #with topdown true, this will prevent walk from going into subs
    for file in files:
      #do some stuff
      print(file)

remove the dirs.clear() line and the files in sub folders are included again.

update with references;

os.walk documented here and talks about the triple list being created and topdown effects.

.clear() documented here for emptying a list

so by clearing the relevant list from os.walk you can effect its result to your needs.

Assign value from successful promise resolve to external variable

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

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

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

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

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

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Hers's what I used to get the day names (0-6 means monday - sunday):

public static String getFullDayName(int day) {
    Calendar c = Calendar.getInstance();
    // date doesn't matter - it has to be a Monday
    // I new that first August 2011 is one ;-)
    c.set(2011, 7, 1, 0, 0, 0);
    c.add(Calendar.DAY_OF_MONTH, day);
    return String.format("%tA", c);
}

public static String getShortDayName(int day) {
    Calendar c = Calendar.getInstance();
    c.set(2011, 7, 1, 0, 0, 0);
    c.add(Calendar.DAY_OF_MONTH, day);
    return String.format("%ta", c);
}

Why does Java have an "unreachable statement" compiler error?

It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Get div's offsetTop positions in React

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var n = ReactDOM.findDOMNode(this);
    console.log(n.offsetTop);
  }

You can just grab the offsetTop from the Node.

Split a vector into chunks

chunk2 <- function(x,n) split(x, cut(seq_along(x), n, labels = FALSE)) 

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

Using Newtonsoft.Json: In your Global.asax Application_Start method add this line:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

How do I set bold and italic on UILabel of iPhone/iPad?

Many times the bolded text is regarded in an information architecture way on another level and thus not have bolded and regular in one line, so you can split it to two labels/textViews, one regular and on bold italic. And use the editor to choose the font styles.

how to fix groovy.lang.MissingMethodException: No signature of method:

You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.

Array initialization syntax when not in a declaration

I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.

If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.

In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.

I would say that (and if someone knows better, please correct me) the first example

AClass[] array = {object1, object2}

actually means

AClass[] array = new AClass[]{object1, object2};

but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.

The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.

pip installing in global site-packages instead of virtualenv

I have to use 'sudo' for installing packages through pip on my ubuntu system for some reason. This is causing the packages to be installed in global site-packages. Putting this here for anyone who might face this issue in future.

Change grid interval and specify tick labels in Matplotlib

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which='both')

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

plt.show()

Output is this:

result

git with IntelliJ IDEA: Could not read from remote repository

The only thing that helped in my case (switch SSH-executabe did not work) was to deactivate the git and git-flow plugin, restart intellij and reactivate those plugins again...

Comment shortcut Android Studio

In android studio you can do single comment with (go to line then Ctrl+/) and block comment with ( select text then Ctrl+Shift+/)

Also if you want to change color of commented text go to File->Settings->IDE settings->Editor->Color & fonts->Java->(Line comment or block comment) and change properties. I prefer it to be green which is used in notepad++ editor.

TokenMismatchException in VerifyCsrfToken.php Line 67

Use like this

<form>
<input type="hidden" name="_token" value="<?= csrf_token(); ?>" />

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

Find distance between two points on map using Google Map API V2

simple util function to calculate distance between two geopoints:

public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {

    double l1 = toRadians(lat1);
    double l2 = toRadians(lat2);
    double g1 = toRadians(lng1);
    double g2 = toRadians(lng2);

    double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
    if(dist < 0) {
        dist = dist + Math.PI;
    }

    return Math.round(dist * 6378100);
}

Hex to ascii string conversion

strtol() is your friend here. The third parameter is the numerical base that you are converting.

Example:

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

int main(int argc, char **argv)
{
    long int num  = 0;
    long int num2 =0;
    char * str. = "f00d";
    char * str2 = "0xf00d";

    num = strtol( str, 0, 16);  //converts hexadecimal string to long.
    num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.

    printf( "%ld\n", num);
    printf( "%ld\n", num);
}

Using TortoiseSVN via the command line

There is a confusion that is causing a lot of TortoiseSVN users to use the wrong command line tools when they actually were looking for svn.exe command line client.

What should I do or can't TortoiseSVN be used from the command line?

svn.exe

If you want to run Subversion commands from the command prompt, you should run the svn.exe command line client. TortoiseSVN 1.6.x and older versions did not include SVN command-line tools, but modern versions do.

If you want to get SVN command line tools without having to install TortoiseSVN, check the SVN binary distributions page or simply download the latest version from VisualSVN downloads page.

If you have SVN command line tools installed on your system, but still get the error 'svn' is not recognized as an internal or external command, you should check %PATH% environment variable. %PATH% must include the path to SVN tools directory e.g. C:\Program Files (x86)\VisualSVN\bin.

TortoiseProc.exe

Apart from svn.exe, TortoiseSVN comes with TortoiseProc.exe that can be called from command prompt. In most cases, you do not need to use this tool, because it should be only used for GUI automation. TortoiseProc.exe is not a replacement for SVN command-line client.

What does localhost:8080 mean?

Option 1

localhost/web is equal to localhost:80/web OR to 127.0.0.1:80/web

Option 2

localhost:8080/web is equal to localhost:8080/web OR to 127.0.0.1:8080/web

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

System.Data.SqlClient.SqlException: Login failed for user

Just set Integrated Security=False and it will work ,according to a comment difference between True and False is:

True ignores User ID and Password if provided and uses those of the running process, SSPI(Security Support Provider Interface ) it will use them if provided which is why MS prefers this. They are equivalent in that they use the same security mechanism to authenticate but that is it.

How to use sed to remove all double quotes within a file

Try prepending the doublequote with a backslash in your expresssion:

sed 's/\"//g' [file name]

Saving timestamp in mysql table using php

If the timestamp is the current time, you could use the mysql NOW() function

Invalid attempt to read when no data is present

I was having 2 values which could contain null values.

while(dr.Read())
 {
    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()
 }

resolved the issue

What is the best JavaScript code to create an img element

As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).

handling dbnull data in vb.net

You can also use the Convert.ToString() and Convert.ToInteger() methods to convert items with DB null effectivly.

How to install ADB driver for any android device?

I have found a solution by myself. I use the PDANet tool to find the driver automatically.

http://www.junefabrics.com/android/download.php

Detect click event inside iframe

In my case there were two jQuery's, for the inner and outer HTML. I had four steps before I could attach inner events:

  1. wait for outer jQuery to be ready
  2. wait for iframe to load
  3. grab inner jQuery
  4. wait for inner jQuery to be ready

$(function() {   // 1. wait for the outer jQuery to be ready, aka $(document).ready
    $('iframe#filecontainer').on('load', function() {   // 2. wait for the iframe to load
        var $inner$ = $(this)[0].contentWindow.$;   // 3. get hold of the inner jQuery
        $inner$(function() {   // 4. wait for the inner jQuery to be ready
            $inner$.on('click', function () {   // Now I can intercept inner events.
                // do something
            });
        });
    });
});

The trick is to use the inner jQuery to attach events. Notice how I'm getting the inner jQuery:

        var $inner$ = $(this)[0].contentWindow.$;

I had to bust out of jQuery into the object model for it. The $('iframe').contents() approach in the other answers didn't work in my case because that stays with the outer jQuery. (And by the way returns contentDocument.)

How to change the foreign key referential action? (behavior)

ALTER TABLE DROP FOREIGN KEY fk_name;
ALTER TABLE ADD FOREIGN KEY fk_name(fk_cols)
            REFERENCES tbl_name(pk_names) ON DELETE RESTRICT;

Call async/await functions in parallel

In my case, I have several tasks I want to execute in parallel, but I need to do something different with the result of those tasks.

function wait(ms, data) {
    console.log('Starting task:', data, ms);
    return new Promise(resolve => setTimeout(resolve, ms, data));
}

var tasks = [
    async () => {
        var result = await wait(1000, 'moose');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(500, 'taco');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(5000, 'burp');
        // do something with result
        console.log(result);
    }
]

await Promise.all(tasks.map(p => p()));
console.log('done');

And the output:

Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done

kubectl apply vs kubectl create?

These are imperative commands :

kubectl run = kubectl create deployment

Advantages:

  • Simple, easy to learn and easy to remember.
  • Require only a single step to make changes to the cluster.

Disadvantages:

  • Do not integrate with change review processes.
  • Do not provide an audit trail associated with changes.
  • Do not provide a source of records except for what is live.
  • Do not provide a template for creating new objects.

These are imperative object config:

kubectl create -f your-object-config.yaml

kubectl delete -f your-object-config.yaml

kubectl replace -f your-object-config.yaml

Advantages compared to imperative commands:

  • Can be stored in a source control system such as Git.
  • Can integrate with processes such as reviewing changes before push and audit trails.
  • Provides a template for creating new objects.

Disadvantages compared to imperative commands:

  • Requires basic understanding of the object schema.
  • Requires the additional step of writing a YAML file.

Advantages compared to declarative object config:

  • Simpler and easier to understand.
  • More mature after Kubernetes version 1.5.

Disadvantages compared to declarative object configuration:

  • Works best on files, not directories.
  • Updates to live objects must be reflected in configuration files, or they will be lost during the next replacement.

These are declarative object config

kubectl diff -f configs/

kubectl apply -f configs/

Advantages compared to imperative object config:

  • Changes made directly to live objects are retained, even if they are not merged back into the configuration files.
  • Better support for operating on directories and automatically detecting operation types (create, patch, delete) per-object.

Disadvantages compared to imperative object configuration:

  • Harder to debug and understand results when they are unexpected.
  • Partial updates using diffs create complex merge and patch operations.

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

How to undo a SQL Server UPDATE query?

If you can catch this in time and you don't have the ability to ROLLBACK or use the transaction log, you can take a backup immediately and use a tool like Redgate's SQL Data Compare to generate a script to "restore" the affected data. This worked like a charm for me. :)

How do I calculate the date six months from the current date using the datetime Python module?

This doesn't answer the specific question (using datetime only) but, given that others suggested the use of different modules, here there is a solution using pandas.

import datetime as dt
import pandas as pd

date = dt.date.today() - \
       pd.offsets.DateOffset(months=6)

print(date)

2019-05-04 00:00:00

Which works as expected in leap years

date = dt.datetime(2019,8,29) - \
       pd.offsets.DateOffset(months=6)
print(date)

2019-02-28 00:00:00

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

CSS customized scroll bar in div

Custom scroll bars aren't possible with CSS, you'll need some JavaScript magic.

Some browsers support non-spec CSS rules, such as ::-webkit-scrollbar in Webkit but is not ideal since it'll only work in Webkit. IE had something like that too, but I don't think they support it anymore.

How can I regenerate ios folder in React Native project?

If you are lost with errors like module not found there is noway other the than following method if you have used react native CLI.I had faced similar issue as a result of openning xcode project from .xcodeproj file instead of .xcworkspace. Also please note that react-native eject only for Expo project.

The only workaround to regenarate ios and android folders within a react native project is the following.

  • Generate a project with same name using the command react-native init
  • Backup your old project ios and android directories into a backup location
  • Then copy ios and android directories from newly created project into your old not working project
  • Run pod install within the copied ios directory

Now your problem should be solved

How to call getResources() from a class which has no context?

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 block1 = new Droid(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic), 100, 10);
 //OR
 builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic));
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

This PL*SQL will write to DBMS_OUTPUT a script that will drop each constraint that does not have delete cascade and recreate it with delete cascade.

NOTE: running the output of this script is AT YOUR OWN RISK. Best to read over the resulting script and edit it before executing it.

DECLARE
      CURSOR consCols (theCons VARCHAR2, theOwner VARCHAR2) IS
        select * from user_cons_columns
            where constraint_name = theCons and owner = theOwner
            order by position;
      firstCol BOOLEAN := TRUE;
    begin
        -- For each constraint
        FOR cons IN (select * from user_constraints
            where delete_rule = 'NO ACTION'
            and constraint_name not like '%MODIFIED_BY_FK'  -- these constraints we do not want delete cascade
            and constraint_name not like '%CREATED_BY_FK'
            order by table_name)
        LOOP
            -- Drop the constraint
            DBMS_OUTPUT.PUT_LINE('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' DROP CONSTRAINT ' || cons.CONSTRAINT_NAME || ';');
            -- Re-create the constraint
            DBMS_OUTPUT.PUT('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' ADD CONSTRAINT ' || cons.CONSTRAINT_NAME 
                                        || ' FOREIGN KEY (');
            firstCol := TRUE;
            -- For each referencing column
            FOR consCol IN consCols(cons.CONSTRAINT_NAME, cons.OWNER)
            LOOP
                IF(firstCol) THEN
                    firstCol := FALSE;
                ELSE
                    DBMS_OUTPUT.PUT(',');
                END IF;
                DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
            END LOOP;                                    

            DBMS_OUTPUT.PUT(') REFERENCES ');

            firstCol := TRUE;
            -- For each referenced column
            FOR consCol IN consCols(cons.R_CONSTRAINT_NAME, cons.R_OWNER)
            LOOP
                IF(firstCol) THEN
                    DBMS_OUTPUT.PUT(consCol.OWNER);
                    DBMS_OUTPUT.PUT('.');
                    DBMS_OUTPUT.PUT(consCol.TABLE_NAME);        -- This seems a bit of a kluge.
                    DBMS_OUTPUT.PUT(' (');
                    firstCol := FALSE;
                ELSE
                    DBMS_OUTPUT.PUT(',');
                END IF;
                DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
            END LOOP;                                    

            DBMS_OUTPUT.PUT_LINE(')  ON DELETE CASCADE  ENABLE VALIDATE;');
        END LOOP;
    end;

How to mark a build unstable in Jenkins when running shell scripts

you should also be able to use groovy and do what textfinder did

marking a build as un-stable with groovy post-build plugin

if(manager.logContains("Could not login to FTP server")) {
    manager.addWarningBadge("FTP Login Failure")
    manager.createSummary("warning.gif").appendText("<h1>Failed to login to remote FTP Server!</h1>", false, false, false, "red")
    manager.buildUnstable()
}

Also see Groovy Postbuild Plugin

How can I get a side-by-side diff when I do "git diff"?

Here's an approach. If you pipe through less, the xterm width is set to 80, which ain't so hot. But if you proceed the command with, e.g. COLS=210, you can utilize your expanded xterm.

gitdiff()
{
    local width=${COLS:-$(tput cols)}
    GIT_EXTERNAL_DIFF="diff -yW$width \$2 \$5; echo >/dev/null" git diff "$@"
}

How do you determine what SQL Tables have an identity column programmatically

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1

MySQL - select data from database between two dates

Maybe use in between better. It worked for me to get range then filter it

How to get UTC timestamp in Ruby?

The proper way is to do a Time.now.getutc.to_i to get the proper timestamp amount as simply displaying the integer need not always be same as the utc timestamp due to time zone differences.

ORA-30926: unable to get a stable set of rows in the source tables

SQL Error: ORA-30926: unable to get a stable set of rows in the source tables
30926. 00000 -  "unable to get a stable set of rows in the source tables"
*Cause:    A stable set of rows could not be got because of large dml
           activity or a non-deterministic where clause.
*Action:   Remove any non-deterministic where clauses and reissue the dml.

This Error occurred for me because of duplicate records(16K)

I tried with unique it worked .

but again when I tried merge without unique same proble occurred Second time it was due to commit

after merge if commit is not done same Error will be shown.

Without unique, Query will work if commit is given after each merge operation.

React-Native: Module AppRegistry is not a registered callable module

If you are using some of the examples they might not work

Here is my version for scroll view

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image
} from 'react-native';

class AwesomeProject extends Component {
  render() {
    return (
        <View>
          <ScrollView
            ref={(scrollView) => { _scrollView = scrollView; }}
            automaticallyAdjustContentInsets={false}
            onScroll={() => { console.log('onScroll!'); }}
            scrollEventThrottle={200}
            style={styles.scrollView}>
            {THUMBS.map(createThumbRow)}
          </ScrollView>
          <TouchableOpacity
            style={styles.button}
            onPress={() => { _scrollView.scrollTo({y: 0}); }}>
            <Text>Scroll to top</Text>
          </TouchableOpacity>
        </View>
    );
  }
}

var Thumb = React.createClass({
  shouldComponentUpdate: function(nextProps, nextState) {
    return false;
  },
  render: function() {
    return (
      <View style={styles.button}>
        <Image style={styles.img} source={{uri:this.props.uri}} />
      </View>
    );
  }
});

var THUMBS = [
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1
];

THUMBS = THUMBS.concat(THUMBS); // double length of THUMBS
var createThumbRow = (uri, i) => <Thumb key={i} uri={uri} />;

var styles = StyleSheet.create({
  scrollView: {
    backgroundColor: '#6A85B1',
    height: 600,
  },
  horizontalScrollView: {
    height: 120,
  },
  containerPage: {
    height: 50,
    width: 50,
    backgroundColor: '#527FE4',
    padding: 5,
  },
  text: {
    fontSize: 20,
    color: '#888888',
    left: 80,
    top: 20,
    height: 40,
  },
  button: {
    margin: 7,
    padding: 5,
    alignItems: 'center',
    backgroundColor: '#eaeaea',
    borderRadius: 3,
  },
  buttonContents: {
    flexDirection: 'row',
    width: 64,
    height: 64,
  },
  img: {
    width: 321,
    height: 200,
  }
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

Using R to list all files with a specified extension

Peg the pattern to find "\\.dbf" at the end of the string using the $ character:

list.files(pattern = "\\.dbf$")

How to drop a PostgreSQL database if there are active connections to it?

Nothing worked for me except, I loggined using pgAdmin4 and on the Dashboard I disconnected all connections except pgAdmin4 and then was able to rename by right lick on the database and properties and typed new name.

Which HTML elements can receive focus?

There isn't a definite list, it's up to the browser. The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement and HTMLAnchorElement. This notably omits HTMLButtonElement and HTMLAreaElement.

Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of:

  • HTMLAnchorElement/HTMLAreaElement with an href
  • HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
  • HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
  • Any element with a tabindex

There are likely to be other subtle exceptions and additions to this behaviour depending on browser.

How to parse JSON using Node.js?

var fs = require('fs');

fs.readFile('ashish.json',{encoding:'utf8'},function(data,err) {

   if(err) 
      throw err;

   else {

   console.log(data.toString());

 }
})

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

Change placeholder text

This solution uses jQuery. If you want to use same placeholder text for all text inputs, you can use

$('input:text').attr('placeholder','Some New Text');

And if you want different placeholders, you can use the element's id to change placeholder

$('#element1_id').attr('placeholder','Some New Text 1');
$('#element2_id').attr('placeholder','Some New Text 2');

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How can I tell when a MySQL table was last updated?

I would create a trigger that catches all updates/inserts/deletes and write timestamp in custom table, something like tablename | timestamp

Just because I don't like the idea to read internal system tables of db server directly

update package.json version automatically

To give a more up-to-date approach.

package.json

  "scripts": {
    "eslint": "eslint index.js",
    "pretest": "npm install",
    "test": "npm run eslint",
    "preversion": "npm run test",
    "version": "",
    "postversion": "git push && git push --tags && npm publish"
  }

Then you run it:

npm version minor --force -m "Some message to commit"

Which will:

  1. ... run tests ...

  2. change your package.json to a next minor version (e.g: 1.8.1 to 1.9.0)

  3. push your changes

  4. create a new git tag release and

  5. publish your npm package.

--force is to show who is the boss! Jokes aside see https://github.com/npm/npm/issues/8620

What does .shape[] do in "for i in range(Y.shape[0])"?

shape is a tuple that gives you an indication of the number of dimensions in the array. So in your case, since the index value of Y.shape[0] is 0, your are working along the first dimension of your array.

From http://www.scipy.org/Tentative_NumPy_Tutorial#head-62ef2d3c0a5b4b7d6fdc48e4a60fe48b1ffe5006

 An array has a shape given by the number of elements along each axis:
 >>> a = floor(10*random.random((3,4)))

 >>> a
 array([[ 7.,  5.,  9.,  3.],
        [ 7.,  2.,  7.,  8.],
        [ 6.,  8.,  3.,  2.]])

 >>> a.shape
 (3, 4)

and http://www.scipy.org/Numpy_Example_List#shape has some more examples.

Remove All Event Listeners of Specific Type

You must override EventTarget.prototype.addEventListener to build an trap function for logging all 'add listener' calls. Something like this:

var _listeners = [];

EventTarget.prototype.addEventListenerBase = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, listener)
{
    _listeners.push({target: this, type: type, listener: listener});
    this.addEventListenerBase(type, listener);
};

Then you can build an EventTarget.prototype.removeEventListeners:

EventTarget.prototype.removeEventListeners = function(targetType)
{
    for(var index = 0; index != _listeners.length; index++)
    {
        var item = _listeners[index];

        var target = item.target;
        var type = item.type;
        var listener = item.listener;

        if(target == this && type == targetType)
        {
            this.removeEventListener(type, listener);
        }
    }
}

In ES6 you can use a Symbol, to hide the original function and the list of all added listener directly in the instantiated object self.

(function()
{
    let target = EventTarget.prototype;
    let functionName = 'addEventListener';
    let func = target[functionName];

    let symbolHidden = Symbol('hidden');

    function hidden(instance)
    {
        if(instance[symbolHidden] === undefined)
        {
            let area = {};
            instance[symbolHidden] = area;
            return area;
        }

        return instance[symbolHidden];
    }

    function listenersFrom(instance)
    {
        let area = hidden(instance);
        if(!area.listeners) { area.listeners = []; }
        return area.listeners;
    }

    target[functionName] = function(type, listener)
    {
        let listeners = listenersFrom(this);

        listeners.push({ type, listener });

        func.apply(this, [type, listener]);
    };

    target['removeEventListeners'] = function(targetType)
    {
        let self = this;

        let listeners = listenersFrom(this);
        let removed = [];

        listeners.forEach(item =>
        {
            let type = item.type;
            let listener = item.listener;

            if(type == targetType)
            {
                self.removeEventListener(type, listener);
            }
        });
    };
})();

You can test this code with this little snipper:

document.addEventListener("DOMContentLoaded", event => { console.log('event 1'); });
document.addEventListener("DOMContentLoaded", event => { console.log('event 2'); });
document.addEventListener("click", event => { console.log('click event'); });

document.dispatchEvent(new Event('DOMContentLoaded'));
document.removeEventListeners('DOMContentLoaded');
document.dispatchEvent(new Event('DOMContentLoaded'));
// click event still works, just do a click in the browser

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

In Android EditText, how to force writing uppercase?

Even better... one liner in Kotlin...

// gets your previous attributes in XML, plus adds AllCaps filter    
<your_edit_text>.setFilters(<your_edit_text>.getFilters() + InputFilter.AllCaps())

Done!

Creating a UICollectionView programmatically

colection view exam

    #import "CollectionViewController.h"
#import "BuyViewController.h"
#import "CollectionViewCell.h"

@interface CollectionViewController ()
{
    NSArray *mobiles;
    NSArray  *costumes;
    NSArray *shoes;
    NSInteger selectpath;
    NSArray *mobilerate;
    NSArray *costumerate;
    NSArray *shoerate;
}
@end

@implementation CollectionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = self.receivename;
    mobiles = [[NSArray alloc]initWithObjects:@"7.jpg",@"6.jpg",@"5.jpg", nil];
    costumes = [[NSArray alloc]initWithObjects:@"shirt.jpg",@"costume2.jpg",@"costume1.jpg", nil];
    shoes = [[NSArray alloc]initWithObjects:@"shoe.jpg",@"shoe1.jpg",@"shoe2.jpg", nil];
    mobilerate = [[NSArray alloc]initWithObjects:@"10000",@"11000",@"13000",nil];
    costumerate = [[NSArray alloc]initWithObjects:@"699",@"999",@"899", nil];
    shoerate = [[NSArray alloc]initWithObjects:@"599",@"499",@"300", nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];

    UIImageView *collectionImg = (UIImageView *)[cell viewWithTag:100];

    if ([self.receivename isEqualToString:@"Mobiles"])
    {
        collectionImg.image = [UIImage imageNamed:[mobiles objectAtIndex:indexPath.row]];
    }
    else if ([self.receivename isEqualToString:@"Costumes"])
    {
        collectionImg.image = [UIImage imageNamed:[costumes objectAtIndex:indexPath.row]];
    }
    else
    {
        collectionImg.image = [UIImage imageNamed:[shoes objectAtIndex:indexPath.row]];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{
    selectpath = indexPath.row;
    [self performSegueWithIdentifier:@"buynow" sender:self];
}

    // In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"buynow"])
    {
        BuyViewController *obj = segue.destinationViewController;
        if ([self.receivename isEqualToString:@"Mobiles"])
        {
            obj.reciveimg = [mobiles objectAtIndex:selectpath];
            obj.labelrecive = [mobilerate objectAtIndex:selectpath];

        }
        else if ([self.receivename isEqualToString:@"Costumes"])
        {
            obj.reciveimg = [costumes objectAtIndex:selectpath];
            obj.labelrecive = [costumerate objectAtIndex:selectpath];
        }
        else
        {
            obj.reciveimg = [shoes objectAtIndex:selectpath];
            obj.labelrecive = [shoerate objectAtIndex:selectpath];
        }
        //     Get the new view controller using [segue destinationViewController].
        //     Pass the selected object to the new view controller.
    }
}

@end

.h file

@interface CollectionViewController :
UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) NSString *receiveimg;
@property (strong,nonatomic) NSString *receivecostume;
@property (strong,nonatomic)NSString *receivename;

@end

remove script tag from HTML content

I had been struggling with this question. I discovered you only really need one function. explode('>', $html); The single common denominator to any tag is < and >. Then after that it's usually quotation marks ( " ). You can extract information so easily once you find the common denominator. This is what I came up with:

$html = file_get_contents('http://some_page.html');

$h = explode('>', $html);

foreach($h as $k => $v){

    $v = trim($v);//clean it up a bit

    if(preg_match('/^(<script[.*]*)/ius', $v)){//my regex here might be questionable

        $counter = $k;//match opening tag and start counter for backtrace

        }elseif(preg_match('/([.*]*<\/script$)/ius', $v)){//but it gets the job done

            $script_length = $k - $counter;

            $counter = 0;

            for($i = $script_length; $i >= 0; $i--){
                $h[$k-$i] = '';//backtrace and clear everything in between
                }
            }           
        }
for($i = 0; $i <= count($h); $i++){
    if($h[$i] != ''){
    $ht[$i] = $h[$i];//clean out the blanks so when we implode it works right.
        }
    }
$html = implode('>', $ht);//all scripts stripped.


echo $html;

I see this really only working for script tags because you will never have nested script tags. Of course, you can easily add more code that does the same check and gather nested tags.

I call it accordion coding. implode();explode(); are the easiest ways to get your logic flowing if you have a common denominator.

Convert an array to string

You can join your array using the following:

string.Join(",", Client);

Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

Using Git, show all commits that are in one branch, but not the other(s)

You can use this simple script to see commits that are not merged

#!/bin/bash
# Show commits that exists only on branch and not in current
# Usage:
#   git branch-notmerge <branchname>
#
# Setup git alias
#   git config alias.branch-notmerge [path/to/this/script]
grep -Fvf <(git log --pretty=format:'%H - %s') <(git log $1 --pretty=format:'%H - %s')

You can use also tool git-wtf that will display state of branches

How to do a batch insert in MySQL

Most of the time, you are not working in a MySQL client and you should batch inserts together using the appropriate API.

E.g. in JDBC:

connection con.setAutoCommit(false); 
PreparedStatement prepStmt = con.prepareStatement("UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
prepStmt.setString(1,mgrnum1);                 
prepStmt.setString(2,deptnum1);
prepStmt.addBatch();

prepStmt.setString(1,mgrnum2);                        
prepStmt.setString(2,deptnum2);
prepStmt.addBatch();

int [] numUpdates=prepStmt.executeBatch();

http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/tjvbtupd.htm

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

This is usually caused by truncation (the incoming value is too large to fit in the destination column). Unfortunately SSIS will not tell you the name of the offending column. I use a third-party component to get this information: http://naseermuhammed.wordpress.com/tips-tricks/getting-error-column-name-in-ssis/

How to check if a file exists in Go?

    _, err := os.Stat(file)
    if err == nil {
        log.Printf("file %s exists", file)
    } else if os.IsNotExist(err) {
        log.Printf("file %s not exists", file)
    } else {
        log.Printf("file %s stat error: %v", file, err)
    }

How do I execute a string containing Python code in Python?

eval and exec are the correct solution, and they can be used in a safer manner.

As discussed in Python's reference manual and clearly explained in this tutorial, the eval and exec functions take two extra parameters that allow a user to specify what global and local functions and variables are available.

For example:

public_variable = 10

private_variable = 2

def public_function():
    return "public information"

def private_function():
    return "super sensitive information"

# make a list of safe functions
safe_list = ['public_variable', 'public_function']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
# add any needed builtins back in
safe_dict['len'] = len

>>> eval("public_variable+2", {"__builtins__" : None }, safe_dict)
12

>>> eval("private_variable+2", {"__builtins__" : None }, safe_dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'private_variable' is not defined

>>> exec("print \"'%s' has %i characters\" % (public_function(), len(public_function()))", {"__builtins__" : None}, safe_dict)
'public information' has 18 characters

>>> exec("print \"'%s' has %i characters\" % (private_function(), len(private_function()))", {"__builtins__" : None}, safe_dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'private_function' is not defined

In essence you are defining the namespace in which the code will be executed.

Read a file in Node.js

To read the html file from server using http module. This is one way to read file from server. If you want to get it on console just remove http module declaration.

_x000D_
_x000D_
var http = require('http');_x000D_
var fs = require('fs');_x000D_
var server = http.createServer(function(req, res) {_x000D_
  fs.readFile('HTMLPage1.html', function(err, data) {_x000D_
    if (!err) {_x000D_
      res.writeHead(200, {_x000D_
        'Content-Type': 'text/html'_x000D_
      });_x000D_
      res.write(data);_x000D_
      res.end();_x000D_
    } else {_x000D_
      console.log('error');_x000D_
    }_x000D_
  });_x000D_
});_x000D_
server.listen(8000, function(req, res) {_x000D_
  console.log('server listening to localhost 8000');_x000D_
});
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <h1>My Header</h1>_x000D_
  <p>My paragraph.</p>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

Git diff -w ignore whitespace only at start & end of lines

This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

As stated, git diff -b or git diff --ignore-space-change will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:

git config --global core.whitespace trailing-space

In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:

git diff --ignore-cr-at-eol or git config --global core.whitespace cr-at-eol from here.

You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.

DB2 Date format

select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1

result: 20160510

Select all text inside EditText when it gets focus

SelectAllOnFocus works the first time the EditText gets focus, but if you want to select the text every time the user clicks on it, you need to call editText.clearFocus() in between times.

For example, if your app has one EditText and one button, clicking the button after changing the EditText leaves the focus in the EditText. Then the user has to use the cursor handle and the backspace key to delete what's in the EditText before they can enter a new value. So call editText.clearFocus() in the Button's onClick method.

Redirect to Action by parameter mvc

This should work!

[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index", "ProductImageManeger", new  { id = id });
}

[HttpGet]
public ViewResult Index(int id)
{
    return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}

Notice that you don't have to pass the name of view if you are returning the same view as implemented by the action.

Your view should inherit the model as this:

@model <Your class name>

You can then access your model in view as:

@Model.<property_name>

Excel VBA For Each Worksheet Loop

Try this more succinct code:

Sub LoopOverEachColumn()
    Dim WS As Worksheet
    For Each WS In ThisWorkbook.Worksheets
        ResizeColumns WS
    Next WS
End Sub

Private Sub ResizeColumns(WS As Worksheet)
    Dim StrSize As String
    Dim ColIter As Long
    StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
    For ColIter = 1 To 15
        WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
    Next ColIter
End Sub

If you want additional columns, just change 1 to 15 to 1 to X where X is the column index of the column you want, and append the column size you want to StrSize.

For example, if you want P:P to have a width of 25, just add ;25 to StrSize and change ColIter... to ColIter = 1 to 16.

Hope this helps.

Trying to use Spring Boot REST to Read JSON String from POST

I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761

But if you can't use a Java class you can use one of these two solutions.

Solution 1: you can do it receiving a Map<String, Object> from your controller:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object> payload) 
    throws Exception {

  System.out.println(payload);

}

Using your request:

curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process

Solution 2: otherwise you can get the POST payload as a String:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST,
    consumes = "text/plain")
public void process(@RequestBody String payload) throws Exception {

  System.out.println(payload);

}

Then parse the string as you want. Note that must be specified consumes = "text/plain" on your controller. In this case you must change your request with Content-type: text/plain:

curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \
-d '{"name":"value"}' http://localhost:8080/myservice/process

How do I pull my project from github?

First, you'll need to tell git about yourself. Get your username and token together from your settings page.

Then run:

git config --global github.user YOUR_USERNAME
git config --global github.token YOURTOKEN

You will need to generate a new key if you don't have a back-up of your key.

Then you should be able to run:

git clone [email protected]:YOUR_USERNAME/YOUR_PROJECT.git

Passing a variable to a powershell script via command line

Here's a good tutorial on Powershell params:

PowerShell ABC's - P is for Parameters

Basically, you should use a param statement on the first line of the script

param([type]$p1 = , [type]$p2 = , ...)

or use the $args built-in variable, which is auto-populated with all of the args.

Change header text of columns in a GridView

I Think this Works:

 testGV.HeaderRow.Cells[0].Text="Date"

Pushing empty commits to remote

As long as you clearly reference the other commit from the empty commit it should be fine. Something like:

Commit message errata for [commit sha1]

[new commit message]

As others have pointed out, this is often preferable to force pushing a corrected commit.

Serialize JavaScript object into JSON string

You can use a named function on the constructor.

MyClass1 = function foo(id, member) {
    this.id = id;
    this.member = member;
}

var myobject = new MyClass1("5678999", "text");

console.log( myobject.constructor );

//function foo(id, member) {
//    this.id = id;
//    this.member = member;
//}

You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

How can I clear an HTML file input with JavaScript?

What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked. Here is the code.

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.