Programs & Examples On #Freetds

FreeTDS is a set of libraries for Unix and Linux that allows your programs to natively talk to Microsoft SQL Server and Sybase databases.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

It sounds like you have a problem with your dsn or odbc data source.

Try bypassing the dsn first and connect using:

TDSVER=8.0 tsql -S *serverIPAddress* -U *username* -P *password*

If that works, you know its an issue with your dsn or with freetds using your dsn. Also, it is possible that your tds version is not compatible with your server. You might want to try other TDSVER settings (5.0, 7.0, 7.1).

Compare if BigDecimal is greater than zero

it is safer to use the method compareTo()

    BigDecimal a = new BigDecimal(10);
    BigDecimal b = BigDecimal.ZERO;

    System.out.println(" result ==> " + a.compareTo(b));

console print

    result ==> 1

compareTo() returns

  • 1 if a is greater than b
  • -1 if b is less than b
  • 0 if a is equal to b

now for your problem you can use

if (value.compareTo(BigDecimal.ZERO) > 0)

or

if (value.compareTo(new BigDecimal(0)) > 0)

I hope it helped you.

How to display UTF-8 characters in phpMyAdmin?

Its realy simple to add multilanguage in myphpadmin if you got garbdata showing in myphpadmin, just go to myphpadmin click your database go to operations tab in operation tab page see collation section set it to utf8_general_ci, after that all your garbdata will show correctly. a simple and easy trick

Converting file size in bytes to human-readable string

Here's one I wrote:

_x000D_
_x000D_
/**
 * Format bytes as human-readable text.
 * 
 * @param bytes Number of bytes.
 * @param si True to use metric (SI) units, aka powers of 1000. False to use 
 *           binary (IEC), aka powers of 1024.
 * @param dp Number of decimal places to display.
 * 
 * @return Formatted string.
 */
function humanFileSize(bytes, si=false, dp=1) {
  const thresh = si ? 1000 : 1024;

  if (Math.abs(bytes) < thresh) {
    return bytes + ' B';
  }

  const units = si 
    ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] 
    : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  let u = -1;
  const r = 10**dp;

  do {
    bytes /= thresh;
    ++u;
  } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);


  return bytes.toFixed(dp) + ' ' + units[u];
}


console.log(humanFileSize(1551859712))  // 1.4 GiB
console.log(humanFileSize(5000, true))  // 5.0 kB
console.log(humanFileSize(5000, false))  // 4.9 KiB
console.log(humanFileSize(-10000000000000000000000000000))  // -8271.8 YiB
console.log(humanFileSize(999949, true))  // 999.9 kB
console.log(humanFileSize(999950, true))  // 1.0 MB
console.log(humanFileSize(999950, true, 2))  // 999.95 kB
console.log(humanFileSize(999500, true, 0))  // 1 MB
_x000D_
_x000D_
_x000D_

How to override the properties of a CSS class using another CSS class

LIFO is the way browser parses CSS properties..If you are using Sass declare a variable called as

"$header-background: red;"

use it instead of directly assigning values like red or blue. When you want to override just reassign the value to

"$header-background:blue"

then

background-color:$header-background;

it should smoothly override. Using "!important" is not always the right choice..Its just a hotfix

How do I enable NuGet Package Restore in Visual Studio?

Package Manager console (Visual Studio, Tools > NuGet Package Manager > Package Manager Console): Run the Update-Package -reinstall -ProjectName command where is the name of the affected project as it appears in Solution Explorer. Use Update-Package -reinstall by itself to restore all packages in the solution. See Update-Package. You can also reinstall a single package, if desired.

from https://docs.microsoft.com/en-us/nuget/quickstart/restore

Include an SVG (hosted on GitHub) in MarkDown

Update 2020: how they made it work while avoiding XSS attacks

GitHub appears to use two security approaches, this is a good article: https://digi.ninja/blog/svg_xss.php see also: https://security.stackexchange.com/questions/148507/how-to-prevent-xss-in-svg-file-upload

Update 2017

A GitHub dev is currently looking into this: https://github.com/github/markup/issues/556#issuecomment-306103203

Update 2014-12: GitHub now renders SVG on blob show, so I don't see any reason why not to render on README renderings:

Also note that that SVG does have an XSS attempt but it does not run: https://raw.githubusercontent.com/cirosantilli/test/2144a93333be144152e8b0d4144b77b211afce63/svg.svg

The billion laugh SVG does make Firefox 44 Freeze, but Chromium 48 is OK: https://github.com/cirosantilli/web-cheat/blob/master/svg-billion-laughs.svg

Petah mentioned that blobs are fine because the SVG is inside an iframe.

Possible rationale for GitHub not serving SVG images

The following questions asks about the risks of SVG in general: https://security.stackexchange.com/questions/11384/exploits-or-other-security-risks-with-svg-upload

How to assign string to bytes array

Besides the methods mentioned above, you can also do a trick as

s := "hello"
b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))

Go Play: http://play.golang.org/p/xASsiSpQmC

You should never use this :-)

Biggest advantage to using ASP.Net MVC vs web forms

Anyone old enough to remember classic ASP will remember the nightmare of opening a page with code mixed in with html and javascript - even the smallest page was a pain to figure out what the heck it was doing. I could be wrong, and I hope I am, but MVC looks like going back to those bad old days.

When ASP.Net came along it was hailed as the savior, separating code from content and allowing us to have web designers create the html and coders work on the code behind. If we didn't want to use ViewState, we turned it off. If we didn't want to use code behind for some reason, we could place our code inside the html just like classic ASP. If we didn't want to use PostBack we redirected to another page for processing. If we didn't want to use ASP.Net controls we used standard html controls. We could even interrogate the Response object if we didn't want to use ASP.Net runat="server" on our controls.

Now someone in their great wisdom (probably someone who never programmed classic ASP) has decided it's time to go back to the days of mixing code with content and call it "separation of concerns". Sure, you can create cleaner html, but you could with classic ASP. To say "you are not programming correctly if you have too much code inside your view" is like saying "if you wrote well structured and commented code in classic ASP it is far cleaner and better than ASP.NET"

If I wanted to go back to mixing code with content I'd look at developing using PHP which has a far more mature environment for that kind of development. If there are so many problems with ASP.NET then why not fix those issues?

Last but not least the new Razor engine means it is even harder to distinguish between html and code. At least we could look for opening and closing tags i.e. <% and %> in ASP but now the only indication will be the @ symbol.

It might be time to move to PHP and wait another 10 years for someone to separate code from content once again.

How do I ignore files in a directory in Git?

It would be the former. Go by extensions as well instead of folder structure.

I.e. my example C# development ignore file:

#OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

Update

I thought I'd provide an update from the comments below. Although not directly answering the OP's question, see the following for more examples of .gitignore syntax.

Community wiki (constantly being updated):

.gitignore for Visual Studio Projects and Solutions

More examples with specific language use can be found here (thanks to Chris McKnight's comment):

https://github.com/github/gitignore

What's the difference between struct and class in .NET?

To add to the other answers, there is one fundamental difference that is worth noting, and that is how the data is stored within arrays as this can have a major effect on performance.

  • With a struct, the array contains the instance of the struct
  • With a class, the array contains a pointer to an instance of the class elsewhere in memory

So an array of structs looks like this in memory

[struct][struct][struct][struct][struct][struct][struct][struct]

Whereas an array of classes looks like this

[pointer][pointer][pointer][pointer][pointer][pointer][pointer][pointer]

With an array of classes, the values you're interested in are not stored within the array, but elsewhere in memory.

For a vast majority of applications this difference doesn't really matter, however, in high performance code this will affect locality of data within memory and have a large impact on the performance of the CPU cache. Using classes when you could/should have used structs will massively increase the number of cache misses on the CPU.

The slowest thing a modern CPU does is not crunching numbers, it's fetching data from memory, and an L1 cache hit is many times faster than reading data from RAM.

Here's some code you can test. On my machine, iterating through the class array takes ~3x longer than the struct array.

    private struct PerformanceStruct
    {
        public int i1;
        public int i2;
    }

    private class PerformanceClass
    {
        public int i1;
        public int i2;
    }

    private static void DoTest()
    {
        var structArray = new PerformanceStruct[100000000];
        var classArray = new PerformanceClass[structArray.Length];

        for (var i = 0; i < structArray.Length; i++)
        {
            structArray[i] = new PerformanceStruct();
            classArray[i] = new PerformanceClass();
        }

        long total = 0;
        var sw = new Stopwatch();
        sw.Start();
        for (var loops = 0; loops < 100; loops++)
        for (var i = 0; i < structArray.Length; i++)
        {
            total += structArray[i].i1 + structArray[i].i2;
        }

        sw.Stop();
        Console.WriteLine($"Struct Time: {sw.ElapsedMilliseconds}");
        sw = new Stopwatch();
        sw.Start();
        for (var loops = 0; loops < 100; loops++)
        for (var i = 0; i < classArray.Length; i++)
        {
            total += classArray[i].i1 + classArray[i].i2;
        }

        Console.WriteLine($"Class Time: {sw.ElapsedMilliseconds}");
    }

Debugging "Element is not clickable at point" error

I am facing the same issue and I used delay and it is working fine my side. Page was getting refresh and getting the other locators.

Thread.sleep(2000);
        Click(By.xpath("//*[@id='instructions_container']/a"));

Differences between MySQL and SQL Server

@Cebjyre. The IDE whether Enterprise Manager or Management Studio is better than anything I have seen so far for MySQL. I say 'easier to use' because I can do many things in MSSQL where MySQL has no counterparts. In MySQL I have no idea how to tune the queries by simply looking at the query plan or looking at the statistics. The index tuning wizard in MSSQL takes most of the guess work on what indexes are missing or misplaced.

One shortcoming of MySQL is there's no max size for a database. The database would just increase in size till it fills up the disk. Imagine if this disk is sharing databases with other users and suddenly all of their queries are failing because their databases can't grow. I have reported this issue to MySQL long time ago. I don't think it's fixed yet.

how to end ng serve or firebase serve

You can use the following command to end an ongoing process:

ctrl + c

Creating a new ArrayList in Java

You are looking for Java generics

List<MyClass> list = new ArrayList<MyClass>();

Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html

Visual Studio Code: format is not using indent settings

I sometimes have this same problem. VSCode will just suddenly lose it's mind and completely ignore any indentation setting I tell it, even though it's been indenting the same file just fine all day.

I have editor.tabSize set to 2 (as well as editor.formatOnSave set to true). When VSCode messes up a file, I use the options at the bottom of the editor to change indentation type and size, hoping something will work, but VSCode insists on actually using an indent size of 4.

The fix? Restart VSCode. It should come back with the indent status showing something wrong (in my case, 4). For me, I had to change the setting and then save for it to actually make the change, but that's probably because of my editor.formatOnSave setting.

I haven't figured out why it happens, but for me it's usually when I'm editing a nested object in a JS file. It will suddenly do very strange indentation within the object, even though I've been working in that file for a while and it's been indenting just fine.

Why rgb and not cmy?

The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).

The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK

A bit more information from the extract about them:

Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.

Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.

Change SVN repository URL

If U want commit to a new empty Repo ,You can checkout the new empty Repo and commit to new remote repo.
chekout a new empty Repo won't delete your local files.
try this: for example, remote repo url : https://example.com/SVNTest cd [YOUR PROJECT PATH] rm -rf .svn svn co https://example.com/SVNTest ../[YOUR PROJECT DIR NAME] svn add ./* svn ci -m"changed repo url"

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

Simple:

function HasSpecialChars(string yourString)
{
    return yourString.Any( ch => ! Char.IsLetterOrDigit( ch ) )
}

linq where list contains any in list

If you use HashSet instead of List for listofGenres you can do:

var genres = new HashSet<Genre>() { "action", "comedy" };   
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));

How to find rows that have a value that contains a lowercase letter

mysql> SELECT '1234aaaa578' REGEXP '^[a-z]';

Set angular scope variable in markup

You can set values from html like this. I don't think there is a direct solution from angular yet.

 <div style="visibility: hidden;">{{activeTitle='home'}}</div>

How to find the largest file in a directory and its subdirectories?

There is no simple command available to find out the largest files/directories on a Linux/UNIX/BSD filesystem. However, combination of following three commands (using pipes) you can easily find out list of largest files:

# du -a /var | sort -n -r | head -n 10

If you want more human readable output try:

$ cd /path/to/some/var
$ du -hsx * | sort -rh | head -10

Where,

  • Var is the directory you wan to search
  • du command -h option : display sizes in human readable format (e.g., 1K, 234M, 2G).
  • du command -s option : show only a total for each argument (summary).
  • du command -x option : skip directories on different file systems.
  • sort command -r option : reverse the result of comparisons.
  • sort command -h option : compare human readable numbers. This is GNU sort specific option only.
  • head command -10 OR -n 10 option : show the first 10 lines.

Editor does not contain a main type in Eclipse

For me, classpath entry in .classpath file isn't pointing to the right location. After modifying it to <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/> fixed the issue

HTTP GET request in JavaScript?

Prototype makes it dead simple

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});

HTML anchor tag with Javascript onclick event

If your onclick function returns false the default browser behaviour is cancelled. As such:

<a href='http://www.google.com' onclick='return check()'>check</a>

<script type='text/javascript'>

function check()
{
    return false;
}

</script>

Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.

How to insert programmatically a new line in an Excel cell in C#?

Internally Excel uses U+000D U+000A (CR+LF, \r\n) for a line break, at least in its XML representation. I also couldn't find the value directly in a cell. It was migrated to another XML file containing shared strings. Maybe cells that contain line breaks are handled differently by the file format and your library doesn't know about this.

Detecting a mobile browser

As many have stated, relying on the moving target of the user agent data is problematic. The same can be said for counting on screen size.

My approach is borrowed from a CSS technique to determine if the interface is touch:

Using only javascript (support by all modern browsers), a media query match can easily infer whether the device is mobile.

function isMobile() {
    var match = window.matchMedia || window.msMatchMedia;
    if(match) {
        var mq = match("(pointer:coarse)");
        return mq.matches;
    }
    return false;
}

WPF Check box: Check changed handling

As a checkbox click = a checkbox change the following will also work:

<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    // ... do some stuff
}

It has the additional advantage of working when IsThreeState="True" whereas just handling Checked and Unchecked does not.

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

Python regular expressions return true/false

Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):

Twitter Bootstrap carousel different height images cause bouncing arrows

Here is the solution that worked for me; I did it this way as the content in the carousel was dynamically generated from user-submitted content (so we could not use a static height in the stylesheet) - This solution should also work with different sized screens:

function updateCarouselSizes(){
  jQuery(".carousel").each(function(){
    // I wanted an absolute minimum of 10 pixels
    var maxheight=10; 
    if(jQuery(this).find('.item,.carousel-item').length) {
      // We've found one or more item within the Carousel...
      jQuery(this).carousel(); // Initialise the carousel (include options as appropriate)
      // Now we iterate through each item within the carousel...
      jQuery(this).find('.item,.carousel-item').each(function(k,v){ 
        if(jQuery(this).outerHeight()>maxheight) {
          // This item is the tallest we've found so far, so store the result...
          maxheight=jQuery(this).outerHeight();
        }
      });
      // Finally we set the carousel's min-height to the value we've found to be the tallest...
      jQuery(this).css("min-height",maxheight+"px");
    }
  });
}

jQuery(function(){
  jQuery(window).on("resize",updateCarouselSizes);
  updateCarouselSizes();
}

Technically this is not responsive, but for my purposes the on window resize makes this behave responsively.

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

How to get the background color code of an element in hex?

In fact, if there is no definition of background-color under some element, Chrome will output its background-color as rgba(0, 0, 0, 0), while Firefox outputs is transparent.

How do I merge a specific commit from one branch into another in Git?

SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work

The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:

enter image description here

If you want to pull commit e43a6 into your master branch, you can run

$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
 3 files changed, 17 insertions(+), 3 deletions(-)

This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:

enter image description here

Now you can remove your topic branch and drop the commits you didn’t want to pull in.

Getting data from Yahoo Finance

Since Yahoo Finances API was disabled, I found Alpha Vantage API

This a stock query sample that I'm using with Excel's Power Query:

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo

cannot connect to pc-name\SQLEXPRESS

If you have Microsoft Windows 10:

  1. Type Control Panel on Cortana search bar (which is says by default 'Type here to search'). Or click on Windows icon and type Control Panel
  2. Click on Administrative Tools
  3. Then double click on Services
  4. Scroll down and look for: SQL Server (SQLEXPRESS), after that right click
  5. And then in the pop out windows click on Start

Now you should be able to connect to your pc-name\SQLEXPRESS

ReactJS - .JS vs .JSX

As other mentioned JSX is not a standard Javascript extension. It's better to name your entry point of Application based on .js and for the rest components, you can use .jsx.

I have an important reason for why I'm using .JSX for all component's file names. Actually, In a large scale project with huge bunch of code, if we set all React's component with .jsx extension, It'll be easier while navigating to different javascript files across the project(like helpers, middleware, etc.) and you know this is a React Component and not other types of the javascript file.

How to use a class from one C# project with another C# project

If you have two projects in one solution folder.Just add the Reference of the Project into another.using the Namespace you can get the classes. While Creating the object for that the requried class. Call the Method which you want.

FirstProject:

class FirstClass()
{
   public string Name()
   {
      return "James";
   }
}

Here add reference to the Second Project

SecondProject:

class SeccondClass
{
    FirstProject.FirstClass obj=new FirstProject.FirstClass();
    obj.Name();
}

addClass and removeClass in jQuery - not removing class

Try this :

$('.close-button').on('click', function(){
  $('.element').removeClass('grown');
  $('.element').addClass('spot');
});

$('.element').on('click', function(){
  $(this).removeClass('spot');
  $(this).addClass('grown');
});

I hope I understood your question.

Where is debug.keystore in Android Studio

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

in standart File Explorer:

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

in standart File Explorer:

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

open View tab and check Hidden items :

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

open view tab and check Hidden

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

Now you can see your .android folder

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

Now you can see your .android folder

Windows batch - concatenate multiple text files into one

At its most basic, concatenating files from a batch file is done with 'copy'.

copy file1.txt + file2.txt + file3.txt concattedfile.txt

How to escape double quotes in JSON

When and where to use \\\" instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.

If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\" is the one you're looking for.

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1: since it's a JavaScript text string, a double backslash double quote \\" would work too; because the double quote does not need escaped within a single quoted string eg '\"' and '"' result in the same JS string.

FPDF utf-8 encoding (HOW-TO)

There's an extention to FPDF called UFDPF http://acko.net/blog/ufpdf-unicode-utf-8-extension-for-fpdf/

But, imho, it's better to use mpdf if you're it's possible for you to change class.

Java collections maintaining insertion order

  • The insertion order is inherently not maintained in hash tables - that's just how they work (read the linked-to article to understand the details). It's possible to add logic to maintain the insertion order (as in the LinkedHashMap), but that takes more code, and at runtime more memory and more time. The performance loss is usually not significant, but it can be.
  • For TreeSet/Map, the main reason to use them is the natural iteration order and other functionality added in the SortedSet/Map interface.

UILabel font size?

Check that your labels aren't set to automatically resize. In IB, it's called "Autoshrink" and is right beside the font setting. Programmatically, it's called adjustsFontSizeToFitWidth.

Write a number with two decimal places SQL Server

Try this:

 declare @MyFloatVal float;

    set @MyFloatVal=(select convert(decimal(10, 2), 10.254000))

    select  @MyFloatVal

    Convert(decimal(18,2),r.AdditionAmount) as AdditionAmount

To switch from vertical split to horizontal split fast in Vim

Ctrl-w followed by H, J, K or L (capital) will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.

The lower case equivalents move focus instead of moving the window.

Swift programmatically navigate to another view controller/scene

You should push the new viewcontroller by using current navigation controller, not present.

self.navigationController.pushViewController(nextViewController, animated: true)

Javascript | Set all values of an array

The other answers are Ok, but a while loop seems more appropriate:

function setAll(array, value) {
  var i = array.length;
  while (i--) {
    array[i] = value;
  }
}

A more creative version:

function replaceAll(array, value) {
  var re = new RegExp(value, 'g');
  return new Array(++array.length).toString().replace(/,/g, value).match(re);
}

May not work everywhere though. :-)

What is perm space?

PermGen Space stands for memory allocation for Permanent generation All Java immutable objects come under this category, like String which is created with literals or with String.intern() methods and for loading the classes into memory. PermGen Space speeds up our String equality searching.

Finding rows containing a value (or values) in any column

How about

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

Setting font on NSAttributedString on UITextView disregards line spacing

Attributed String Programming Guide:

UIFont *font = [UIFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
                                forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil" attributes:attrsDictionary];

Update: I tried to use addAttribute: method in my own app, but it seemed to be not working on the iOS 6 Simulator:

NSLog(@"%@", textView.attributedText);

The log seems to show correctly added attributes, but the view on iOS simulator was not display with attributes.

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

How do I convert a IPython Notebook into a Python file via commandline?

Jupytext is nice to have in your toolchain for such conversions. It allows not only conversion from a notebook to a script, but you can go back again from the script to notebook as well. And even have that notebook produced in executed form.

jupytext --to py notebook.ipynb                 # convert notebook.ipynb to a .py file
jupytext --to notebook notebook.py              # convert notebook.py to an .ipynb file with no outputs
jupytext --to notebook --execute notebook.py    # convert notebook.py to an .ipynb file and run it 

How can I encode a string to Base64 in Swift?

After thorough research I found the solution

Encoding

    let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
    println(base64String) // bXkgcGxhbmkgdGV4dA==

Decoding

    let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
    let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)    
    println(decodedString) // my plain data

More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/

XmlSerializer: remove unnecessary xsi and xsd namespaces

Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.


After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To whit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the default namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.


This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label> is part of the same namespace as the rest of the document, in this case urn:Abracadabra:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:

// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the 
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
    });
}

[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
    get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;

Then, later, in your code that uses the MyTypeWithNamespaces object to serialize it, you would call it as I did above:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

...

// Above, you'd setup your XmlTextWriter.

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

And the XmlSerializer would spit back out the same XML as shown immediately above with no additional namespaces in the output:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Android WebView, how to handle redirects in app instead of opening a browser

Please use the below kotlin code

webview.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {   
                view.loadUrl(url)
                return false 
            }
        })

For more info click here

Multiplying Two Columns in SQL Server

Syntax:

SELECT <Expression>[Arithmetic_Operator]<expression>...
 FROM [Table_Name] 
 WHERE [expression];
  1. Expression : Expression made up of a single constant, variable, scalar function, or column name and can also be the pieces of a SQL query that compare values against other values or perform arithmetic calculations.
  2. Arithmetic_Operator : Plus(+), minus(-), multiply(*), and divide(/).
  3. Table_Name : Name of the table.

how to refresh my datagridview after I add new data

I found this code to work if you're trying to refresh a bound datagridview with updated data from a dataset. Obviously, this was after I sent the update to the database.

'clear out the datasource for the Grid view
Me.DataGridView1.DataSource = Nothing
'refill the table adapter from the dataset table 
Me.viewABCTableAdapter.Fill(Me.yourDataSet.viewABC)
'reset the datasource from the binding source
Me.DataGridView1.DataSource = Me.viewABCBindingSource
'should redraw with the new data
Me.DataGridView1.Refresh()

Declaring abstract method in TypeScript

If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:

/**
 * The interface defines all abstract methods and extends the concrete base class
 */
interface IAnimal extends Animal {
    speak() : void;
}

/**
 * The abstract base class only defines concrete methods & properties.
 */
class Animal {

    private _impl : IAnimal;

    public name : string;

    /**
     * Here comes the clever part: by letting the constructor take an 
     * implementation of IAnimal as argument Animal cannot be instantiated
     * without a valid implementation of the abstract methods.
     */
    constructor(impl : IAnimal, name : string) {
        this.name = name;
        this._impl = impl;

        // The `impl` object can be used to delegate functionality to the
        // implementation class.
        console.log(this.name + " is born!");
        this._impl.speak();
    }
}

class Dog extends Animal implements IAnimal {
    constructor(name : string) {
        // The child class simply passes itself to Animal
        super(this, name);
    }

    public speak() {
        console.log("bark");
    }
}

var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"

Since the Animal class requires an implementation of IAnimal it's impossible to construct an object of type Animal without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal, not Animal. E.g.:

//This works
function letTheIAnimalSpeak(animal: IAnimal) {
    console.log(animal.name + " says:");
    animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
    console.log(animal.name + " says:");
    animal.speak();
}

The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.

How to initialize a struct in accordance with C programming language standards

a = (MYTYPE){ true, 15, 0.123 };

would do fine in C99

mysql: SOURCE error 2?

Related issue I had getting error 2 running source command: filename must not be in quotes even if it contains spaces in name or path to file.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Android Studio cannot find the svn command because it's not on PATH, and it doesn't know where svn is installed.

One way to fix is to edit the PATH environment variable: add the directory that contains svn.exe. You will need to restart Android Studio to make it re-read the PATH variable.

Another way is to set the absolute path of svn.exe in the Use command client box in the settings screen that you included in your post.

UPDATE

According to this other post, TortoiseSVN doesn't include the command line tools by default. But you can re-run the installer and enable it. That will add svn.exe to PATH, and Android Studio will correctly pick it up.

How do I check to see if a value is an integer in MySQL?

To check if a value is Int in Mysql, we can use the following query. This query will give the rows with Int values

SELECT col1 FROM table WHERE concat('',col * 1) = col;

Trying to fire the onload event on script tag

I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload instruction was immediately evaluated, and then the $ usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).

So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.

var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
    console.log("script loaded :)");
    onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

For my needs, it works fine now. Hope this can help others :)

HTML Image not displaying, while the src url works

It wont work since you use URL link with "file://". Instead you should match your directory to your HTML file, for example:

Lets say my file placed in:

C:/myuser/project/file.html

And my wanted image is in:

C:/myuser/project2/image.png

All I have to do is matching the directory this way:

<img src="../project2/image.png" />

How do I speed up the gwt compiler?

In the newer versions of GWT (starting either 2.3 or 2.4, i believe), you can also add

<collapse-all-properties />

to your gwt.xml for development purposes. That will tell the GWT compiler to create a single permutation which covers all locales and browsers. Therefore, you can still test in all browsers and languages, but are still only compiling a single permutation

Specifying a custom DateTime format when serializing with Json.Net

public static JsonSerializerSettings JsonSerializer { get; set; } = new JsonSerializerSettings()
        {
            DateFormatString= "yyyy-MM-dd HH:mm:ss",
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new LowercaseContractResolver()
        };

Hello,

I'm using this property when I need set JsonSerializerSettings

How to declare a inline object with inline variables without a parent class

yes, there is:

object[] x = new object[2];

x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };

you were practically there, just the declaration of the anonymous types was a little off.

How do I import a pre-existing Java project into Eclipse and get up and running?

This assumes Eclipse and an appropriate JDK are installed on your system

  1. Open Eclipse and create a new Workspace by specifying an empty directory.
  2. Make sure you're in the Java perspective by selecting Window -> Open Perspective ..., select Other... and then Java
  3. Right click anywhere in the Package Explorer pane and select New -> Java Project
  4. In the dialog that opens give the project a name and then click the option that says "Crate project from existing sources."
  5. In the text box below the option you selected in Step 4 point to the root directory where you checked out the project. This should be the directory that contains "com"
  6. Click Finish. For this particular project you don't need to do any additional setup for your classpath since it only depends on classes that are part of the Java SE API.

How to set gradle home while importing existing project in Android studio

This is my solution on AndroidStudio/Idea for Mac

$ env | grep GRADLE
GRADLE_HOME=/usr/local/Cellar/gradle/2.6
GRADLE_USER_HOME=/Users/leon/.gradle

Linq to Sql: Multiple left outer joins

This may be cleaner (you dont need all the into statements):

var query = 
    from order in dc.Orders
    from vendor 
    in dc.Vendors
        .Where(v => v.Id == order.VendorId)
        .DefaultIfEmpty()
    from status 
    in dc.Status
        .Where(s => s.Id == order.StatusId)
        .DefaultIfEmpty()
    select new { Order = order, Vendor = vendor, Status = status } 
    //Vendor and Status properties will be null if the left join is null

Here is another left join example

var results = 
    from expense in expenseDataContext.ExpenseDtos
    where expense.Id == expenseId //some expense id that was passed in
    from category 
    // left join on categories table if exists
    in expenseDataContext.CategoryDtos
                         .Where(c => c.Id == expense.CategoryId)
                         .DefaultIfEmpty() 
    // left join on expense type table if exists
    from expenseType 
    in expenseDataContext.ExpenseTypeDtos
                         .Where(e => e.Id == expense.ExpenseTypeId)
                         .DefaultIfEmpty()
    // left join on currency table if exists
    from currency 
    in expenseDataContext.CurrencyDtos
                         .Where(c => c.CurrencyID == expense.FKCurrencyID)
                         .DefaultIfEmpty() 
    select new 
    { 
        Expense = expense,
        // category will be null if join doesn't exist
        Category = category,
        // expensetype will be null if join doesn't exist
        ExpenseType = expenseType,
        // currency will be null if join doesn't exist
        Currency = currency  
    }

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

"/openStudentPage" is the page that i want to open first, i did :

 @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
     return "redirect:/openStudentPage";
    }

@RequestMapping(value = "/openStudentPage", method = RequestMethod.GET)
public String listStudents(Model model) {
    model.addAttribute("student", new Student());
    model.addAttribute("listStudents", this.StudentService.listStudents());
    return "index";
}

How can I recover the return value of a function passed to multiprocessing.Process?

Use shared variable to communicate. For example like this:

import multiprocessing


def worker(procnum, return_dict):
    """worker function"""
    print(str(procnum) + " represent!")
    return_dict[procnum] = procnum


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i, return_dict))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print(return_dict.values())

BASH Syntax error near unexpected token 'done'

Sometimes this error happens because of unexpected CR characters in file, usually because the file was generated on a Windows system which uses CR line endings. You can fix this by running os2unix or tr, for example:

tr -d '\015' < yourscript.sh > newscript.sh

This removes any CR characters from the file.

Set value of hidden input with jquery

You don't need to set name , just giving an id is enough.

<input type="hidden" id="testId" />

and than with jquery you can use 'val()' method like below:

 $('#testId').val("work");

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

How to get root view controller?

Unless you have a good reason, in your root controller do this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(onTheEvent:)
                                             name:@"ABCMyEvent"
                                           object:nil];

And when you want to notify it:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ABCMyEvent"
                                                object:self];                

How can I check if a value is of type Integer?

this is the shortest way I know with negative integers enabled:

Object myObject = "-1";

if(Pattern.matches("\\-?\\d+", (CharSequence) myObject);)==true)
{
    System.out.println("It's an integer!");
}

And this is the way with negative integers disabled:

Object myObject = "1";

if(Pattern.matches("\\d+", (CharSequence) myObject);)==true)
{
    System.out.println("It's an integer!");
}

Simple way to read single record from MySQL

One more answer for object oriented style. Found this solution for me:

$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;

gives back just one id. Verify that your design ensures you got the right one.

Which Architecture patterns are used on Android?

Android also uses the ViewHolder design pattern.

It's used to improve performance of a ListView while scrolling it.

The ViewHolder design pattern enables you to access each list item view without the need for the look up, saving valuable processor cycles. Specifically, it avoids frequent calls of findViewById() during ListView scrolling, and that will make it smooth.

get one item from an array of name,value JSON

I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].name will give you 'k1', arr[1].value will give you 'hi'.

Maybe you want to do something like:

var obj = {};

obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";

alert ("obj.k2:" + obj.k2);

Removing an item from a select box

Remove an option:

_x000D_
_x000D_
$("#selectBox option[value='option1']").remove();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

Add an option:

_x000D_
_x000D_
$("#selectBox").append('<option value="option5">option5</option>');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

Redirect stderr to stdout in C shell

I object the above answer and provide my own. csh DOES have this capability and here is how it's done:

xxx |& some_exec # will pipe merged output to your some_exec 

or

xxx |& cat > filename

or if you just want it to merge streams (to stdout) and not redirect to a file or some_exec:

xxx |& tee /dev/null

Android Material Design Button Styles

you can give aviation to the view by adding z axis to it and can have default shadow to it. this feature was provided in L preview and will be available after it release. For now you can simply add a image the gives this look for button background

rmagick gem install "Can't find Magick-config"

imagemagick@6 works for me!

brew unlink imagemagick
brew install imagemagick@6 && brew link imagemagick@6 --force

See this thread

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

From "node_modules" in Git:

To recap.

  • Only checkin node_modules for applications you deploy, not reusable packages you maintain.
  • Any compiled dependencies should have their source checked in, not the compile targets, and should $ npm rebuild on deploy.

My favorite part:

All you people who added node_modules to your gitignore, remove that shit, today, it’s an artifact of an era we’re all too happy to leave behind. The era of global modules is dead.

(The original link was this one, but it is now dead. Thanks @Flavio for pointing it out.)*

How to efficiently count the number of keys/properties of an object in JavaScript?

To iterate on Avi Flax answer Object.keys(obj).length is correct for an object that doesnt have functions tied to it

example:

obj = {"lol": "what", owo: "pfft"};
Object.keys(obj).length; // should be 2

versus

arr = [];
obj = {"lol": "what", owo: "pfft"};
obj.omg = function(){
    _.each(obj, function(a){
        arr.push(a);
    });
};
Object.keys(obj).length; // should be 3 because it looks like this 
/* obj === {"lol": "what", owo: "pfft", omg: function(){_.each(obj, function(a){arr.push(a);});}} */

steps to avoid this:

  1. do not put functions in an object that you want to count the number of keys in

  2. use a seperate object or make a new object specifically for functions (if you want to count how many functions there are in the file using Object.keys(obj).length)

also yes i used the _ or underscore module from nodejs in my example

documentation can be found here http://underscorejs.org/ as well as its source on github and various other info

And finally a lodash implementation https://lodash.com/docs#size

_.size(obj)

jQuery delete confirmation box

Simply works as:

$("a. close").live("click",function(event){
     return confirm("Do you want to delete?");
});

iOS - UIImageView - how to handle UIImage image orientation

here is a workable sample cod, considering the image orientation:

#define rad(angle) ((angle) / 180.0 * M_PI)
- (CGAffineTransform)orientationTransformedRectOfImage:(UIImage *)img
{
    CGAffineTransform rectTransform;
    switch (img.imageOrientation)
    {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };

    return CGAffineTransformScale(rectTransform, img.scale, img.scale);
}


- (UIImage *)croppedImage:(UIImage*)orignialImage InRect:(CGRect)visibleRect{
    //transform visible rect to image orientation
    CGAffineTransform rectTransform = [self orientationTransformedRectOfImage:orignialImage];
    visibleRect = CGRectApplyAffineTransform(visibleRect, rectTransform);

    //crop image
    CGImageRef imageRef = CGImageCreateWithImageInRect([orignialImage CGImage], visibleRect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:orignialImage.scale orientation:orignialImage.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

How to comment multiple lines in Visual Studio Code?

1.Select the text, Press Cntl + K, C to comment (Ctr+E+C ) 2.Move the cursor to the first line after the delimiter // and before the Code text. 3.Press Alt + Shift and use arrow keys to make selection. ... 4.Once the selection is done, press space bar to enter a single space.

Retrieve Button value with jQuery

try this for your button:

<input type="button" class="my_button" name="buttonName" value="buttonValue" />

How do I convert a TimeSpan to a formatted string?

The easiest way to format a TimeSpan is to add it to a DateTime and format that:

string formatted = (DateTime.Today + dateDifference).ToString("HH 'hrs' mm 'mins' ss 'secs'");

This works as long as the time difference is not more than 24 hours.

The Today property returns a DateTime value where the time component is zero, so the time component of the result is the TimeSpan value.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

I solved the problem by adding the line skip-grant-tables to the my.ini:

# The MySQL server
[mysqld]
skip-grant-tables
port= 3306
...

Under XAMPP Control Panel > Section "MySQL" > Config > my.ini

Launch Minecraft from command line - username and password as prefix

This answer is going to briefly explain how the native files are handled on the latest launcher.

As of 4/29/2017 the Minecraft launcher for Windows extracts all native files and places them info %APPDATA%\Local\Temp{random folder}. That folder is temporary and is deleted once the javaw.exe process finishes (when Minecraft is closed). The location of that temporary folder must be provided in the launch arguments as the value of

-Djava.library.path=

Also, the latest launcher (2.0.847) does not show you the launch arguments so if you need to check them yourself you can do so under the Task Manager (simply enable the Command Line tab and expand it) or by using the WMIC utility as explained here.

Hope this helps some people who are still interested in doing this in 2017.

How to change a text with jQuery

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");

example: http://jsfiddle.net/niklasvh/xPRzr/

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

How do I jump out of a foreach loop in C#?

how about:

return(sList.Contains("ok"));

That should do the trick if all you want to do is check for an "ok" and return the answer ...

what is the use of xsi:schemaLocation?

The Java XML parser that spring uses will read the schemaLocation values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.

If you omit the schemaLocation, then the XML parser won't know where to get the schema in order to validate the config.

How do I test if a variable is a number in Bash?

Stack popped a message asked me if I really want to answer after 30+ answers? But of course!!! Use bash new features and here it is: (after the comment I made a change)

function isInt() { ([[ $1 -eq $(( $1 + 0 )) ]] 2>/dev/null && [[ $1 != '' ]] && echo 1) || echo '' }

function isInt() {
   ([[ $1 =~ ^[-+0-9]+$  ]] && [[ $1 -eq $(( $1 + 0 )) ]] 2>/dev/null && [[ $1 != '' ]] && echo 1) || echo ''
}

Supports:

===============out-of-the-box==================
 1. negative integers (true & arithmetic),
 2. positive integers (true & arithmetic),
 3. with quotation (true & arithmetic),
 4. without quotation (true & arithmetic),
 5. all of the above with mixed signs(!!!) (true & arithmetic),
 6. empty string (false & arithmetic),
 7. no value (false & arithmetic),
 8. alphanumeric (false & no arithmetic),
 9. mixed only signs (false & no arithmetic),
================problematic====================
 10. positive/negative floats with 1 decimal (true & NO arithmetic),
 11. positive/negative floats with 2 or more decimals (FALSE & NO arithmetic).

True/false is what you get from the function only when used combined with process substitution like in [[ $( isInt <arg> ) ]] as there is no logical type in bash neither return value of function.

I use capital when the result of the test expression is WRONG whereas, it should be the reverse!

By 'arithmetic' I mean bash can do math like in this expression: $x=$(( $y + 34)).

I use 'arithmetic/no arithmetic' when in mathematical expressions the argument acts as it is expected and 'NO arithmetic' when it misbehaves compared with what it is expected.

As you see, only no 10 and 11 are the problematic ones!

Perfect!

PS: Note that the MOST popular answer fails in case 9!

What is the best way to parse html in C#?

I think @Erlend's use of HTMLDocument is the best way to go. However, I have also had good luck using this simple library:

SgmlReader

JQuery show/hide when hover

I hope my script help you.

<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>

My script

<script>
$(".mostrar-producto").mouseover(function(){
     $(".producto").fadeIn();
 });

 $(".mostrar-producto").mouseleave(function(){
      $(".producto").fadeOut();
  });
</script>

warning about too many open figures

Here's a bit more detail to expand on Hooked's answer. When I first read that answer, I missed the instruction to call clf() instead of creating a new figure. clf() on its own doesn't help if you then go and create another figure.

Here's a trivial example that causes the warning:

from matplotlib import pyplot as plt, patches
import os


def main():
    path = 'figures'
    for i in range(21):
        _fig, ax = plt.subplots()
        x = range(3*i)
        y = [n*n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.clf()
    print('Done.')

main()

To avoid the warning, I have to pull the call to subplots() outside the loop. In order to keep seeing the rectangles, I need to switch clf() to cla(). That clears the axis without removing the axis itself.

from matplotlib import pyplot as plt, patches
import os


def main():
    path = 'figures'
    _fig, ax = plt.subplots()
    for i in range(21):
        x = range(3*i)
        y = [n*n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.cla()
    print('Done.')

main()

If you're generating plots in batches, you might have to use both cla() and close(). I ran into a problem where a batch could have more than 20 plots without complaining, but it would complain after 20 batches. I fixed that by using cla() after each plot, and close() after each batch.

from matplotlib import pyplot as plt, patches
import os


def main():
    for i in range(21):
        print('Batch {}'.format(i))
        make_plots('figures')
    print('Done.')


def make_plots(path):
    fig, ax = plt.subplots()
    for i in range(21):
        x = range(3 * i)
        y = [n * n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.cla()
    plt.close(fig)


main()

I measured the performance to see if it was worth reusing the figure within a batch, and this little sample program slowed from 41s to 49s (20% slower) when I just called close() after every plot.

How do I use the Simple HTTP client in Android?

public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

How to include Javascript file in Asp.Net page

ScriptManager control can also be used to reference javascript files. One catch is that the ScriptManager control needs to be place inside the form tag. I myself prefer ScriptManager control and generally place it just above the closing form tag.

<asp:ScriptManager ID="sm" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/yourscript.min.js" />
    </Scripts>
</asp:ScriptManager>

Can I get all methods of a class?

public static Method[] getAccessibleMethods(Class clazz) {
    List<Method> result = new ArrayList<Method>();
    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
                result.add(method);
            }
        }
        clazz = clazz.getSuperclass();
    }
    return result.toArray(new Method[result.size()]);
}

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

How to show multiline text in a table cell

style="white-space:pre-wrap; word-wrap:break-word"

This would solve the issue of new line. pre tag would add additional CSS than required.

How does #include <bits/stdc++.h> work in C++?

#include <bits/stdc++.h> is an implementation file for a precompiled header.

From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]

But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.

It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.

The disadvantages of it are that it:

  • increases the compilation time.
  • uses an internal non-standard header file of the GNU C++ library, and so will not compile in MSVC, XCode, and many other compilers

Send Post Request with params using Retrofit

You should create an interface for that like it is working well

public interface Service {
    @FormUrlEncoded
    @POST("v1/EmergencyRequirement.php/?op=addPatient")
    Call<Result> addPerson(@Field("BloodGroup") String bloodgroup,
           @Field("Address") String Address,
           @Field("City") String city, @Field("ContactNumber") String  contactnumber, 
           @Field("PatientName") String name, 
           @Field("Time") String Time, @Field("DonatedBy") String donar);
}

or you can visit to http://teachmeandroidhub.blogspot.com/2018/08/post-data-using-retrofit-in-android.html

and youcan vist to https://github.com/rajkumu12/GetandPostUsingRatrofit

How to sort a dataFrame in python pandas by two or more columns?

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

How would you count occurrences of a string (actually a char) within a string?

In C#, a nice String SubString counter is this unexpectedly tricky fellow:

public static int CCount(String haystack, String needle)
{
    return haystack.Split(new[] { needle }, StringSplitOptions.None).Length - 1;
}

Received an invalid column length from the bcp client for colid 6

I just stumbled upon this and using @b_stil's snippet, I was able to figure the culprit column. And on futher investigation, I figured i needed to trim the column just like @Liji Chandran suggested but I was using IExcelDataReader and I couldn't figure out an easy way to validate and trim each of my 160 columns.

Then I stumbled upon this class, (ValidatingDataReader) class from CSVReader.

Interesting thing about this class is that it gives you the source and destination columns data length, the culprit row and even the column value that's causing the error.

All I did was just trim all (nvarchar, varchar, char and nchar) columns.

I just changed my GetValue method to this:

 object IDataRecord.GetValue(int i)
    {
        object columnValue = reader.GetValue(i);

        if (i > -1 && i < lookup.Length)
        {
            DataRow columnDef = lookup[i];
            if
            (
                (
                    (string)columnDef["DataTypeName"] == "varchar" ||
                    (string)columnDef["DataTypeName"] == "nvarchar" ||
                    (string)columnDef["DataTypeName"] == "char" ||
                    (string)columnDef["DataTypeName"] == "nchar"
                ) &&
                (
                    columnValue != null &&
                    columnValue != DBNull.Value
                )
            )
            {
                string stringValue = columnValue.ToString().Trim();

                columnValue = stringValue;


                if (stringValue.Length > (int)columnDef["ColumnSize"])
                {
                    string message =
                        "Column value \"" + stringValue.Replace("\"", "\\\"") + "\"" +
                        " with length " + stringValue.Length.ToString("###,##0") +
                        " from source column " + (this as IDataRecord).GetName(i) +
                        " in record " + currentRecord.ToString("###,##0") +
                        " does not fit in destination column " + columnDef["ColumnName"] +
                        " with length " + ((int)columnDef["ColumnSize"]).ToString("###,##0") +
                        " in table " + tableName +
                        " in database " + databaseName +
                        " on server " + serverName + ".";

                    if (ColumnException == null)
                    {
                        throw new Exception(message);
                    }
                    else
                    {
                        ColumnExceptionEventArgs args = new ColumnExceptionEventArgs();

                        args.DataTypeName = (string)columnDef["DataTypeName"];
                        args.DataType = Type.GetType((string)columnDef["DataType"]);
                        args.Value = columnValue;
                        args.SourceIndex = i;
                        args.SourceColumn = reader.GetName(i);
                        args.DestIndex = (int)columnDef["ColumnOrdinal"];
                        args.DestColumn = (string)columnDef["ColumnName"];
                        args.ColumnSize = (int)columnDef["ColumnSize"];
                        args.RecordIndex = currentRecord;
                        args.TableName = tableName;
                        args.DatabaseName = databaseName;
                        args.ServerName = serverName;
                        args.Message = message;

                        ColumnException(args);

                        columnValue = args.Value;
                    }
                }



            }
        }

        return columnValue;
    }

Hope this helps someone

How can I programmatically check whether a keyboard is present in iOS app?

…or take the easy way:

When you enter a textField, it becomes first responder and the keyboard appears. You can check the status of the keyboard with [myTextField isFirstResponder]. If it returns YES, then the the keyboard is active.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Declaring an unsigned int in Java

You can use the Math.abs(number) function. It returns a positive number.

Measuring function execution time in R

microbenchmark is a lightweight (~50kB) package and more-or-less a standard way in R for benchmarking multiple expressions and functions:

microbenchmark(myfunction(with,arguments))

For example:

> microbenchmark::microbenchmark(log10(5), log(5)/log(10), times = 10000)
Unit: nanoseconds
           expr min lq    mean median uq   max neval cld
       log10(5)   0  0 25.5738      0  1 10265 10000   a
 log(5)/log(10)   0  0 28.1838      0  1 10265 10000

Here both the expressions were evaluated 10000 times, with mean execution time being around 25-30 ns.

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

Python socket receive - incoming packets always have a different size

The network is always unpredictable. TCP makes a lot of this random behavior go away for you. One wonderful thing TCP does: it guarantees that the bytes will arrive in the same order. But! It does not guarantee that they will arrive chopped up in the same way. You simply cannot assume that every send() from one end of the connection will result in exactly one recv() on the far end with exactly the same number of bytes.

When you say socket.recv(x), you're saying 'don't return until you've read x bytes from the socket'. This is called "blocking I/O": you will block (wait) until your request has been filled. If every message in your protocol was exactly 1024 bytes, calling socket.recv(1024) would work great. But it sounds like that's not true. If your messages are a fixed number of bytes, just pass that number in to socket.recv() and you're done.

But what if your messages can be of different lengths? The first thing you need to do: stop calling socket.recv() with an explicit number. Changing this:

data = self.request.recv(1024)

to this:

data = self.request.recv()

means recv() will always return whenever it gets new data.

But now you have a new problem: how do you know when the sender has sent you a complete message? The answer is: you don't. You're going to have to make the length of the message an explicit part of your protocol. Here's the best way: prefix every message with a length, either as a fixed-size integer (converted to network byte order using socket.ntohs() or socket.ntohl() please!) or as a string followed by some delimiter (like '123:'). This second approach often less efficient, but it's easier in Python.

Once you've added that to your protocol, you need to change your code to handle recv() returning arbitrary amounts of data at any time. Here's an example of how to do this. I tried writing it as pseudo-code, or with comments to tell you what to do, but it wasn't very clear. So I've written it explicitly using the length prefix as a string of digits terminated by a colon. Here you go:

length = None
buffer = ""
while True:
  data += self.request.recv()
  if not data:
    break
  buffer += data
  while True:
    if length is None:
      if ':' not in buffer:
        break
      # remove the length bytes from the front of buffer
      # leave any remaining bytes in the buffer!
      length_str, ignored, buffer = buffer.partition(':')
      length = int(length_str)

    if len(buffer) < length:
      break
    # split off the full message from the remaining bytes
    # leave any remaining bytes in the buffer!
    message = buffer[:length]
    buffer = buffer[length:]
    length = None
    # PROCESS MESSAGE HERE

How do I debug error ECONNRESET in Node.js?

I just figured this out, at least in my use case.

I was getting ECONNRESET. It turned out that the way my client was set up, it was hitting the server with an API call a ton of times really quickly -- and it only needed to hit the endpoint once.

When I fixed that, the error was gone.

Python Timezone conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

time_in_new_timezone = time_in_old_timezone.astimezone(new_timezone)

Given aware_dt (a datetime object in some timezone), to convert it to other timezones and to print the times in a given time format:

#!/usr/bin/env python3
import pytz  # $ pip install pytz

time_format = "%Y-%m-%d %H:%M:%S%z"
tzids = ['Asia/Shanghai', 'Europe/London', 'America/New_York']
for tz in map(pytz.timezone, tzids):
    time_in_tz = aware_dt.astimezone(tz)
    print(f"{time_in_tz:{time_format}}")

If f"" syntax is unavailable, you could replace it with "".format(**vars())

where you could set aware_dt from the current time in the local timezone:

from datetime import datetime
import tzlocal  # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
aware_dt = datetime.now(local_timezone) # the current time

Or from the input time string in the local timezone:

naive_dt = datetime.strptime(time_string, time_format)
aware_dt = local_timezone.localize(naive_dt, is_dst=None)

where time_string could look like: '2016-11-19 02:21:42'. It corresponds to time_format = '%Y-%m-%d %H:%M:%S'.

is_dst=None forces an exception if the input time string corresponds to a non-existing or ambiguous local time such as during a DST transition. You could also pass is_dst=False, is_dst=True. See links with more details at Python: How do you convert datetime/timestamp from one timezone to another timezone?

Getter and Setter declaration in .NET

The first one is the "short" form - you use it, when you do not want to do something fancy with your getters and setters. It is not possible to execute a method or something like that in this form.

The second and third form are almost identical, albeit the second one is compressed to one line. This form is discouraged by stylecop because it looks somewhat weird and does not conform to C' Stylguides.

I would use the third form if I expectd to use my getters / setters for something special, e.g. use a lazy construct or so.

Change value of input and submit form in JavaScript

Here is simple code. You must set an id for your input. Here call it 'myInput':

var myform = document.getElementById('myform');
myform.onsubmit = function(){
    document.getElementById('myInput').value = '1';
    myform.submit();
};

What is the MySQL JDBC driver connection string?

Here's the documentation:

https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html

A basic connection string looks like:

jdbc:mysql://localhost:3306/dbname

The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Uninstallation :

sudo /Library/PostgreSQL/9.6/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

Removing the data file :

sudo rm -rf /Library/PostgreSQL

Removing the configs :

sudo rm /etc/postgres-reg.ini

And thats it.

Two Divs next to each other, that then stack with responsive change

You can use CSS3 media query for this. Write like this:

CSS

.wrapper { 
  border : 2px solid #000; 
  overflow:hidden;
}

.wrapper div {
   min-height: 200px;
   padding: 10px;
}
#one {
  background-color: gray;
  float:left; 
  margin-right:20px;
  width:140px;
  border-right:2px solid #000;
}
#two { 
  background-color: white;
  overflow:hidden;
  margin:10px;
  border:2px dashed #ccc;
  min-height:170px;
}

@media screen and (max-width: 400px) {
   #one { 
    float: none;
    margin-right:0;
    width:auto;
    border:0;
    border-bottom:2px solid #000;    
  }
}

HTML

<div class="wrapper">
    <div id="one">one</div>
    <div id="two">two</div>
</div>

Check this for more http://jsfiddle.net/cUCvY/1/

How do I migrate an SVN repository with history to a new Git repository?

GitHub has an importer. Once you've created the repository, you can import from an existing repository, via its URL. It will ask for your credentials if applicable and go from there.

As it's running it will find authors, and you can simply map them to users on GitHub.

I have used it for a few repositories now, and it's pretty accurate and much faster too! It took 10 minutes for a repository with ~4000 commits, and after it took my friend four days!

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

If the reason for allowing if (aBooleanVariable) return; someMoreCode; is to allow flags, then the fact that if (true) return; someMoreCode; does not generate a compile time error seems like inconsistency in the policy of generating CodeNotReachable exception, since the compiler 'knows' that true is not a flag (not a variable).

Two other ways which might be interesting, but don't apply to switching off part of a method's code as well as if (true) return:

Now, instead of saying if (true) return; you might want to say assert false and add -ea OR -ea package OR -ea className to the jvm arguments. The good point is that this allows for some granularity and requires adding an extra parameter to the jvm invocation so there is no need of setting a DEBUG flag in the code, but by added argument at runtime, which is useful when the target is not the developer machine and recompiling & transferring bytecode takes time.

There is also the System.exit(0) way, but this might be an overkill, if you put it in Java in a JSP then it will terminate the server.

Apart from that Java is by-design a 'nanny' language, I would rather use something native like C/C++ for more control.

When does Git refresh the list of remote branches?

The OP did not ask for cleanup for all remotes, rather for all branches of default remote.

So git fetch --prune is what should be used.

Setting git config remote.origin.prune true makes --prune automatic. In that case just git fetch will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.

Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.

What does "./" (dot slash) refer to in terms of an HTML file path location?

.  = This location
.. = Up a directory

So, ./foo.html is just foo.html. And it is optional, but may have relevance if a script generated the path (relevance to the script that is, not how the reference works).

You can't specify target table for update in FROM clause

Make a temporary table (tempP) from a subquery

UPDATE pers P 
SET P.gehalt = P.gehalt * 1.05 
WHERE P.persID IN (
    SELECT tempP.tempId
    FROM (
        SELECT persID as tempId
        FROM pers P
        WHERE
            P.chefID IS NOT NULL OR gehalt < 
                (SELECT (
                    SELECT MAX(gehalt * 1.05) 
                    FROM pers MA 
                    WHERE MA.chefID = MA.chefID) 
                    AS _pers
                )
    ) AS tempP
)

I've introduced a separate name (alias) and give a new name to 'persID' column for temporary table

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Perhaps NSValue, just make sure your pointers are still valid after the delay (ie. no objects allocated on stack).

How to calculate age in T-SQL with years, months, and days

There is an easy way, based on the hours between the two days BUT with the end date truncated.

SELECT CAST(DATEDIFF(hour,Birthdate,CAST(GETDATE() as Date))/8766.0 as INT) AS Age FROM <YourTable>

This one has proven to be extremely accurate and reliable. If it weren't for the inner CAST on the GETDATE() it might flip the birthday a few hours before midnight but, with the CAST, it is dead on with the age changing over at exactly midnight.

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I also experienced the same error, "NPM package not installed correctly", while creating a Node.js project in Visual Studio 2015.

I resolved my issue by performing two steps:

  1. Delete all files present in this location:

    C:\Users\<Your User Name>\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache
    

    Restart Visual Studio.

  2. Open Visual Studio and go to menu Tools ? NuGet Package Manager ? Package Manager Settings ?

    On the left side: You will see a drop down list: select Node.js, Tools ? Npm ? ClearCache ? *OK

Then again try to create the project. It resolved my issue.

400 BAD request HTTP error code meaning?

First check the URL it might be wrong, if it is correct then check the request body which you are sending, the possible cause is request that you are sending is missing right syntax.

To elaborate , check for special characters in the request string. If it is (special char) being used this is the root cause of this error.

try copying the request and analyze each and every tags data.

Parse JSON in C#

[Update]
I've just realized why you weren't receiving results back... you have a missing line in your Deserialize method. You were forgetting to assign the results to your obj :

public static T Deserialize<T>(string json)
{
    using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        return (T)serializer.ReadObject(ms);
    } 
}

Also, just for reference, here is the Serialize method :

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
        serializer.WriteObject(ms, obj);
        return Encoding.Default.GetString(ms.ToArray());
    }
}

Edit

If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..

Deserialize:

JsonConvert.DeserializeObject<T>(string json);

Serialize:

JsonConvert.SerializeObject(object o);

This are already part of Json.NET so you can just call them on the JsonConvert class.

Link: Serializing and Deserializing JSON with Json.NET



Now, the reason you're getting a StackOverflow is because of your Properties.

Take for example this one :

[DataMember]
public string unescapedUrl
{
    get { return unescapedUrl; } // <= this line is causing a Stack Overflow
    set { this.unescapedUrl = value; }
}

Notice that in the getter, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.


Properties (in 2.0) should be defined like such :

string _unescapedUrl; // <= private field

[DataMember]
public string unescapedUrl
{
    get { return _unescapedUrl; } 
    set { _unescapedUrl = value; }
}

You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.


Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that :

public string unescapedUrl { get; set;}

Recursively looping through an object to build a property list

The solution from Artyom Neustroev does not work on complex objects, so here is a working solution based on his idea:

function propertiesToArray(obj) {
    const isObject = val =>
        typeof val === 'object' && !Array.isArray(val);

    const addDelimiter = (a, b) =>
        a ? `${a}.${b}` : b;

    const paths = (obj = {}, head = '') => {
        return Object.entries(obj)
            .reduce((product, [key, value]) => 
                {
                    let fullPath = addDelimiter(head, key)
                    return isObject(value) ?
                        product.concat(paths(value, fullPath))
                    : product.concat(fullPath)
                }, []);
    }

    return paths(obj);
}

How to convert Nonetype to int or string?

That TypeError only appears when you try to pass int() None (which is the only NoneType value, as far as I know). I would say that your real goal should not be to convert NoneType to int or str, but to figure out where/why you're getting None instead of a number as expected, and either fix it or handle the None properly.

Run Android studio emulator on AMD processor

Open Android AVD Manager: Tools -> Android -> AVD Manager and create an emulator:

  • Create Virtual Device
  • Choose any hardware
  • Now in system image you need to click on the "Other Images" tab
  • Select an image to install. IMPORTANT: Notice that for AMD in the "ABI" column it has to say: ARM EABI v7a or ARM 64 v8a
  • Install it and restart Android Studio

This works for me.

map function for objects (instead of arrays)

I needed a version that allowed modifying the keys as well (based on @Amberlamps and @yonatanmn answers);

var facts = [ // can be an object or array - see jsfiddle below
    {uuid:"asdfasdf",color:"red"},
    {uuid:"sdfgsdfg",color:"green"},
    {uuid:"dfghdfgh",color:"blue"}
];

var factObject = mapObject({}, facts, function(key, item) {
    return [item.uuid, {test:item.color, oldKey:key}];
});

function mapObject(empty, obj, mapFunc){
    return Object.keys(obj).reduce(function(newObj, key) {
        var kvPair = mapFunc(key, obj[key]);
        newObj[kvPair[0]] = kvPair[1];
        return newObj;
    }, empty);
}

factObject=

{
"asdfasdf": {"color":"red","oldKey":"0"},
"sdfgsdfg": {"color":"green","oldKey":"1"},
"dfghdfgh": {"color":"blue","oldKey":"2"}
}

Edit: slight change to pass in the starting object {}. Allows it to be [] (if the keys are integers)

Adding a leading zero to some values in column in MySQL

I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):

UPDATE table SET phone_num = concat('0', phone_num) 

I just concated 0 in front of the phone_num.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

mAddTaskButton is null because you never initialize it with:

mAddTaskButton = (Button) findViewById(R.id.addTaskButton);

before you call mAddTaskButton.setOnClickListener().

Disable/Enable button in Excel/VBA

too good !!! it's working and resolved my one day old problem easily

Dim b1 As Button

Set b1 = ActiveSheet.Buttons("Button 1")


b1.Enabled = False

Check time difference in Javascript

You can Get Two Time Different with this function. 

_x000D_
_x000D_
 /**_x000D_
     * Get Two Time Different_x000D_
     * @param join_x000D_
     * @param lastSeen_x000D_
     * @param now_x000D_
     * @returns {string}_x000D_
     */_x000D_
    function getTimeDiff( join, lastSeen, now = false)_x000D_
    {_x000D_
        let t1 = new Date(join).getTime(), t2 = new Date(lastSeen).getTime(), milliseconds =0, time ='';_x000D_
        if (now) t2 = Date.now();_x000D_
        if( isNaN(t1) || isNaN(t2) ) return '';_x000D_
        if (t1 < t2) milliseconds = t2 - t1; else milliseconds = t1 - t2;_x000D_
        var days = Math.floor(milliseconds / 1000 / 60 / (60 * 24));_x000D_
        var date_diff = new Date( milliseconds );_x000D_
        if (days > 0) time += days + 'd ';_x000D_
        if (date_diff.getHours() > 0) time += date_diff.getHours() + 'h ';_x000D_
        if (date_diff.getMinutes() > 0) time += date_diff.getMinutes() + 'm ';_x000D_
        if (date_diff.getSeconds() > 0) time += date_diff.getSeconds() + 's ';_x000D_
        return time;_x000D_
    }_x000D_
    _x000D_
    _x000D_
    console.log(getTimeDiff(1578852606608, 1579530945513));_x000D_
    
_x000D_
_x000D_
_x000D_

jQuery UI Slider (setting programmatically)

In my case with jquery slider with 2 handles only following way worked.

$('#Slider').slider('option',{values: [0.15, 0.6]});

What is the difference between square brackets and parentheses in a regex?

The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

str = str.replace(/^(7|8|9)/ig,''); 

you would replace 7 or 8 or 9 by the empty string.

If you match on this

str = str.replace(/^[7|8|9]/ig,''); 

you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

I just found this out the hard way.

How do I combine two data-frames based on two columns?

See the documentation on ?merge, which states:

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

This clearly implies that merge will merge data frames based on more than one column. From the final example given in the documentation:

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

This example was meant to demonstrate the use of incomparables, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x and y using by.x and by.y.

The view 'Index' or its master was not found.

Where this error only occurs when deployed to a web server then the issue could be because the views are not being deployed correctly.

An example of how this can happen is if the build action for the views is set to None rather than Content.

A way to check that the views are deployed correctly is to navigate to the physical path for the site on the web server and confirm that the views are present.

SQLite: How do I save the result of a query as a CSV file?

Alternatively you can do it in one line (tested in win10)

sqlite3 -help
sqlite3 -header -csv db.sqlite 'select * from tbl1;' > test.csv

Bonus: Using powershell with cmdlet and pipe (|).

get-content query.sql | sqlite3 -header -csv db.sqlite > test.csv

where query.sql is a file containing your SQL query

Create new XML file and write data to it?

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();

$doc->add('Album', true)
        ->add('Track', 'Track Title');

$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');

$doc->query('//Track')
        ->attr('id', 123);

https://github.com/servo-php/fluidxml

How do I run a Python script from C#?

If you're willing to use IronPython, you can execute scripts directly in C#:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Get IronPython here.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

I think the right answer is a combination of Steve Morgan's and Serguei's answers. That's how Internet Explorer does it. The pinvoke call to FindMimeFromData works for only 26 hard-coded mime types. Also, it will give ambigous mime types (such as text/plain or application/octet-stream) even though there may exist a more specific, more appropriate mime type. If it fails to give a good mime type, you can go to the registry for a more specific mime type. The server registry could have more up-to-date mime types.

Refer to: http://msdn.microsoft.com/en-us/library/ms775147(VS.85).aspx

Get Bitmap attached to ImageView

Other way to get a bitmap of an image is doing this:

Bitmap imagenAndroid = BitmapFactory.decodeResource(getResources(),R.drawable.jellybean_statue);
imageView.setImageBitmap(imagenAndroid);

Is it possible to use Java 8 for Android development?

Yes, you can use Java 8 Language features in Android Studio but the version must be 3.0 or higher. Read this article for how to use java 8 features in the android studio.

https://bijay-budhathoki.blogspot.com/2020/01/use-java-8-language-features-in-android-studio.html

How to view DLL functions?

For .NET DLLs you can use ildasm

How do I make a div full screen?

<div id="placeholder" style="position:absolute; top:0; right:0; bottom:0; left:0;"></div>

How exactly to use Notification.Builder

          // This is a working Notification
       private static final int NotificID=01;
   b= (Button) findViewById(R.id.btn);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Notification notification=new       Notification.Builder(MainActivity.this)
                    .setContentTitle("Notification Title")
                    .setContentText("Notification Description")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
            NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            notification.flags |=Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(NotificID,notification);


        }
    });
}

Extracting extension from filename in Python

New in version 3.4.

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'

I'm surprised no one has mentioned pathlib yet, pathlib IS awesome!

If you need all the suffixes (eg if you have a .tar.gz), .suffixes will return a list of them!

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

As far as I know a linter is included into the this package. And it requires you componend should begin from Capital character. Please check it.

However as for me it's sad.

Change bundle identifier in Xcode when submitting my first app in IOS

If you are developing a cordova app, make sure to change the version and bundle identifier in the config.xml as well

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name

import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')

sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

How to turn off gcc compiler optimization to enable buffer overflow

On newer distros (as of 2016), it seems that PIE is enabled by default so you will need to disable it explicitly when compiling.

Here's a little summary of commands which can be helpful when playing locally with buffer overflow exercises in general:

Disable canary:

gcc vuln.c -o vuln_disable_canary -fno-stack-protector

Disable DEP:

gcc vuln.c -o vuln_disable_dep -z execstack

Disable PIE:

gcc vuln.c -o vuln_disable_pie -no-pie

Disable all of protection mechanisms listed above (warning: for local testing only):

gcc vuln.c -o vuln_disable_all -fno-stack-protector -z execstack -no-pie

For 32-bit machines, you'll need to add the -m32 parameter as well.

How to set the JSTL variable value in javascript?

<script ...
  function(){
   var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";

  }
</script>

This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.

How to programmatically set drawableLeft on Android button?

myEdtiText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

Get only records created today in laravel

with carbon:

return $model->where('created_at', '>=', \Carbon::today()->toDateString());

without carbon:

return $model->where('created_at', '>=', date('Y-m-d').' 00:00:00');

Hash function for a string

Use boost::hash

#include <boost\functional\hash.hpp>

...

std::string a = "ABCDE";
size_t b = boost::hash_value(a);

Spring Data JPA - "No Property Found for Type" Exception

this error happens if you try access un-exists property

my guess is that sorting is done by spring by property name and not by real column name. and the error indicates that, in "UserBoard" there is no property named "boardId".

bests,

Oak

Merge two HTML table cells

Set the colspan attribute to 2.

...but please don't use tables for layout.

Pretty printing XML with javascript

Use above method for pretty print and then add this in any div by using jquery text() method. for example id of div is xmldiv then use :

$("#xmldiv").text(formatXml(youXmlString));

How to add data via $.ajax ( serialize() + extra data ) like this

What kind of data?

data: $('#myForm').serialize() + "&moredata=" + morevalue

The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264

and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141

eg:

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES

How to display a date as iso 8601 format with PHP

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

Git push error: Unable to unlink old (Permission denied)

After checking the permission of the folder, it is okay with 744. I had the problem with a plugin that is installed on my WordPress site. The plugin has hooked that are in the corn job I suspected.

With a simple sudo it can fix the issue

sudo git pull origin master

You have it working.

Why do I keep getting Delete 'cr' [prettier/prettier]?

Fixed - My .eslintrc.js looks like this:

module.exports = {
  root: true,
  extends: '@react-native-community',
  rules: {'prettier/prettier': ['error', {endOfLine: 'auto'}]},
};

How to get current date in jquery?

this object set zero, when element has only one symbol:

function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

This object set actual full time, hour and date:

function getActualFullDate() {
    var d = new Date();
    var day = addZero(d.getDate());
    var month = addZero(d.getMonth()+1);
    var year = addZero(d.getFullYear());
    var h = addZero(d.getHours());
    var m = addZero(d.getMinutes());
    var s = addZero(d.getSeconds());
    return day + ". " + month + ". " + year + " (" + h + ":" + m + ")";
}

function getActualHour() {
    var d = new Date();
    var h = addZero(d.getHours());
    var m = addZero(d.getMinutes());
    var s = addZero(d.getSeconds());
    return h + ":" + m + ":" + s;
}

function getActualDate() {
    var d = new Date();
    var day = addZero(d.getDate());
    var month = addZero(d.getMonth()+1);
    var year = addZero(d.getFullYear());
    return day + ". " + month + ". " + year;
}

HTML:

<span id='full'>a</span>
<br>
<span id='hour'>b</span>
<br>    
<span id='date'>c</span>

JQUERY VIEW:

$(document).ready(function(){
    $("#full").html(getActualFullDate());
    $("#hour").html(getActualHour());
    $("#date").html(getActualDate());
});

EXAMPLE

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

I may be out fishing here, but doesn't Tomcat by default open to port 8080? Try http://localhost:8080 instead.

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

How to add a button to UINavigationBar?

Adding custom button to navigation bar ( with image for buttonItem and specifying action method (void)openView{} and).

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 32, 32);
[button setImage:[UIImage imageNamed:@"settings_b.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(openView) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barButton=[[UIBarButtonItem alloc] init];
[barButton setCustomView:button];
self.navigationItem.rightBarButtonItem=barButton;

[button release];
[barButton release];

Does C# have an equivalent to JavaScript's encodeURIComponent()?

You can use the Server object in the System.Web namespace

Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.

Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.

How can javascript upload a blob?

2019 Update

This updates the answers with the latest Fetch API and doesn't need jQuery.

Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

Basic Fetch

It could be as simple as:

  fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

Fetch with Error Handling

After adding error handling, it could look like:

fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            })
            .then(response => console.log(response.text()))
            .catch(err => {
                alert(err);
            });

PHP Code

This is the server-side code in upload.php.

<?php    
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);
    fclose($fp);
?>

Computed / calculated / virtual / derived columns in PostgreSQL

YES you can!! The solution should be easy, safe, and performant...

I'm new to postgresql, but it seems you can create computed columns by using an expression index, paired with a view (the view is optional, but makes makes life a bit easier).

Suppose my computation is md5(some_string_field), then I create the index as:

CREATE INDEX some_string_field_md5_index ON some_table(MD5(some_string_field));

Now, any queries that act on MD5(some_string_field) will use the index rather than computing it from scratch. For example:

SELECT MAX(some_field) FROM some_table GROUP BY MD5(some_string_field);

You can check this with explain.

However at this point you are relying on users of the table knowing exactly how to construct the column. To make life easier, you can create a VIEW onto an augmented version of the original table, adding in the computed value as a new column:

CREATE VIEW some_table_augmented AS 
   SELECT *, MD5(some_string_field) as some_string_field_md5 from some_table;

Now any queries using some_table_augmented will be able to use some_string_field_md5 without worrying about how it works..they just get good performance. The view doesn't copy any data from the original table, so it is good memory-wise as well as performance-wise. Note however that you can't update/insert into a view, only into the source table, but if you really want, I believe you can redirect inserts and updates to the source table using rules (I could be wrong on that last point as I've never tried it myself).

Edit: it seems if the query involves competing indices, the planner engine may sometimes not use the expression-index at all. The choice seems to be data dependant.

What's the fastest way to loop through an array in JavaScript?

A basic while loop is often the fastest. jsperf.com is a great sandbox to test these types of concepts.

https://jsperf.com/fastest-array-loops-in-javascript/24

MySQL: Convert INT to DATETIME

SELECT  FROM_UNIXTIME(mycolumn)
FROM    mytable

Node.js - use of module.exports as a constructor

The example code is:

in main

square(width,function (data)
{
   console.log(data.squareVal);
});

using the following may works

exports.square = function(width,callback)
{
     var aa = new Object();
     callback(aa.squareVal = width * width);    
}

How to check if a variable is equal to one string or another string?

Two separate checks. Also, use == rather than is to check for equality rather than identity.

 if var=='stringone' or var=='stringtwo':
     dosomething()

dismissModalViewControllerAnimated deprecated

Now in iOS 6 and above, you can use:

[[Picker presentingViewController] dismissViewControllerAnimated:YES completion:nil];

Instead of:

[[Picker parentViewControl] dismissModalViewControllerAnimated:YES];

...And you can use:

[self presentViewController:picker animated:YES completion:nil];

Instead of

[self presentModalViewController:picker animated:YES];    

Difference between web server, web container and application server

Web Container + HTTP request handling = WebServer

Web Server + EJB + (Messaging + Transactions+ etc) = ApplicaitonServer

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Adding git branch on the Bash command prompt

At first, open your Bash Profile in your home directory. The easiest way to open & edit your bash_profile using your default editor.

For example, I open it using the VS Code using this command: code .bash_profile.

Then just paste the following codes to your Bash.

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

The function

parse_git_branch()

will fetch the branch name & then through PS1 you can show it in your terminal.

Here,

\u = Username

@ = Static Text

\h = Computer Name

\w = Current Directory

$ = Static Text

You can change or remove these variables for more customization.


If you use Git for the first time in terminal or instantly after configuration, maybe sometimes you can not see the branch name.

If you get this problem, don't worry. In that case, just make a sample repository and commit it after some changes. When the commit command will execute once, the terminal will find git branch from then.


Screenshot: Git Branch in Terminal

exclude @Component from @ComponentScan

The configuration seem alright, except that you should use excludeFilters instead of excludes:

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}

How to combine two vectors into a data frame

Alt simplification of https://stackoverflow.com/users/1969435/gx1sptdtda above:

cond <-c(1,2,3)
rating <-c(100,200,300)
df <- data.frame(cond, rating)
df
  cond rating
1    1    100
2    2    200
3    3    300

access key and value of object using *ngFor

If you're already using Lodash, you can do this simple approach which includes both key and value:

<ul>
  <li *ngFor='let key of _.keys(demo)'>{{key}}: {{demo[key]}}</li>
</ul>

In the typescript file, include:

import * as _ from 'lodash';

and in the exported component, include:

_: any = _;