Programs & Examples On #Adodbapi

Disable same origin policy in Chrome

There is a Chrome extension called CORS Toggle.

Click here to access it and add it to Chrome.

After adding it, toggle it to the on position to allow cross-domain requests.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

The selected solution is fine if you want jQuery to process all svg elements in your DOM and your DOM is of reasonable size. But if your DOM is large and you decide to load parts of your DOM dynamically, it really makes no sense to have to rescan the entire DOM just to update svg elements. Instead, use a jQuery plugin to do this:

/**
 * A jQuery plugin that loads an svg file and replaces the jQuery object with its contents.
 *
 * The path to the svg file is specified in the src attribute (which normally does not exist for an svg element).
 *
 * The width, height and class attributes in the loaded svg will be replaced by those that exist in the jQuery object's
 * underlying html. Note: All other attributes in the original element are lost including the style attribute. Place
 * any styles in a style class instead.
 */
(function ($) {
    $.fn.svgLoader = function () {
        var src = $(this).attr("src");
        var width = this.attr("width");
        var height = this.attr("height");
        var cls = this.attr("class");
        var ctx = $(this);

        // Get the svg file and replace the <svg> element.
        $.ajax({
            url: src,
            cache: false
        }).done(function (html) {
            let svg = $(html);
            svg.attr("width", width);
            svg.attr("height", height);
            svg.attr("class", cls);
            var newHtml = $('<a></a>').append(svg.clone()).html();
            ctx.replaceWith(newHtml);
        });

        return this;
    };

}(jQuery));

In your html, specify an svg element as follows:

<svg src="images/someSvgFile.svg" height="45" width="45" class="mySVGClass"/>

And apply the plugin:

$(".mySVGClass").svgLoader();

How to delete a file after checking whether it exists

if (System.IO.File.Exists(@"C:\test.txt"))
    System.IO.File.Delete(@"C:\test.txt"));

but

System.IO.File.Delete(@"C:\test.txt");

will do the same as long as the folder exists.

Disable hover effects on mobile browsers

Here is my solution: http://jsfiddle.net/agamemnus/g56aw709/-- code below.

All one needs to do is to convert their ":hover" to ".hover"... that's it! The big difference between this and the rest is that this will also work on non-singular element selectors such as .my_class > *:hover {.

handle_css_hover_effects ()

function handle_css_hover_effects (init) {
 var init = init || {}
 var handle_touch_events = init.handle_touch_events || true
 var handle_mouse_events = init.handle_mouse_events || true
 var hover_class         = init.hover_class         || "hover"
 var delay_preferences   = init.delay_preferences   || {touch: {add: 500, remove: 500}}
 function default_handler (curobj, input_type, op) {
  var hovered_element_selector = "*" + ((op == "add") ? ":" : ("." + hover_class))
  var hovered_elements = Array.prototype.slice.call(document.body.querySelectorAll(hovered_element_selector))
  var modified_list = []
  while (true) {
   if ((curobj == null) || (curobj == document.documentElement)) break
   if (hovered_elements.indexOf(curobj) != -1) modified_list.push (curobj)
   curobj = curobj.parentNode
  }
  function do_hover_change () {modified_list.forEach (function (curobj) {curobj.classList[op](hover_class)})}
  if ((!delay_preferences[input_type]) || (!delay_preferences[input_type][op])) {
   do_hover_change ()
  } else {
   setTimeout (do_hover_change, delay_preferences[input_type][op])
  }
 }

 if (handle_mouse_events) {
  document.body.addEventListener ('mouseover' , function (evt) {var curobj = evt.target; default_handler (curobj, "mouse", "add")})
  document.body.addEventListener ('mouseout'  , function (evt) {var curobj = evt.target; default_handler (curobj, "mouse", "remove")})
  document.body.addEventListener ('click'     , function (evt) {var curobj = evt.target; default_handler (curobj, "mouse", "remove")})
 }

 if (handle_touch_events) {
  document.body.addEventListener ('touchstart', function (evt) {var curobj = evt.target; default_handler (curobj, "touch", "add")})
  document.body.addEventListener ('touchend'  , function (evt) {var curobj = evt.target; default_handler (curobj, "touch", "remove")})
  document.body.addEventListener ('touchmove',  function (evt) {
   var curobj = evt.target
   var hovered_elements = Array.prototype.slice.call(document.body.querySelectorAll("*:hover"))
   var lastobj = null
   evt = evt.changedTouches[0]
   var elements_at_point = get_elements_at_point (evt.pageX, evt.pageY)
   // Get the last element that isn't at the current point but is still hovered over, and remove only its hover attribute.
   while (true) {
    if ((curobj == null) || (curobj == document.documentElement)) break
    if ((hovered_elements.indexOf(curobj) != -1) && (elements_at_point.indexOf(curobj) == -1)) lastobj = curobj
    curobj = curobj.parentNode
   }
   if (lastobj == null) return
   if ((!delay_preferences.touch) || (!delay_preferences.touch.remove)) {
    lastobj.classList.remove(hover_class)
   } else {
    setTimeout (function () {lastobj.classList.remove(hover_class)}, delay_preferences.touch.remove)
   }

   function get_elements_at_point (x, y) {
    var el_list = [], pe_list = []
    while (true) {
     var curobj = document.elementFromPoint(x, y)
     if ((curobj == null) || (curobj == document.documentElement)) break
     el_list.push (curobj); pe_list.push (curobj.style.pointerEvents)
     curobj.style.pointerEvents = "none"
    }
    el_list.forEach (function (current_element, i) {current_element.style.pointerEvents = pe_list[i]})
    return el_list
   }
  })
 }
}

How to get filename without extension from file path in Ruby

require 'pathname'

Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>

I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.

How to import classes defined in __init__.py

  1. 'lib/'s parent directory must be in sys.path.

  2. Your 'lib/__init__.py' might look like this:

    from . import settings # or just 'import settings' on old Python versions
    class Helper(object):
          pass
    

Then the following example should work:

from lib.settings import Values
from lib import Helper

Answer to the edited version of the question:

__init__.py defines how your package looks from outside. If you need to use Helper in settings.py then define Helper in a different file e.g., 'lib/helper.py'.

.
|   `-- import_submodule.py
    `-- lib
    |-- __init__.py
    |-- foo
    |   |-- __init__.py
    |   `-- someobject.py
    |-- helper.py
    `-- settings.py

2 directories, 6 files

The command:

$ python import_submodule.py

Output:

settings
helper
Helper in lib.settings
someobject
Helper in lib.foo.someobject

# ./import_submodule.py
import fnmatch, os
from lib.settings import Values
from lib import Helper

print
for root, dirs, files in os.walk('.'):
    for f in fnmatch.filter(files, '*.py'):
        print "# %s/%s" % (os.path.basename(root), f)
        print open(os.path.join(root, f)).read()
        print


# lib/helper.py
print 'helper'
class Helper(object):
    def __init__(self, module_name):
        print "Helper in", module_name


# lib/settings.py
print "settings"
import helper

class Values(object):
    pass

helper.Helper(__name__)


# lib/__init__.py
#from __future__ import absolute_import
import settings, foo.someobject, helper

Helper = helper.Helper


# foo/someobject.py
print "someobject"
from .. import helper

helper.Helper(__name__)


# foo/__init__.py
import someobject

Can "git pull --all" update all my local branches?

I came across the same issue of this question...

Wondering myself about it, I did a small alias function inside my .bashrc file:

gitPullAll() {
    for branch in `git branch | sed -E 's/^\*/ /' | awk '{print $1}'`; do
        git checkout $branch
        git pull -p
        printf "\n"
    done
    echo "Done"
}

Worked for me (:

How to remove the URL from the printing page?

I would agree with most of the answers saying that its a browser settings but still you can achieve what you want via COM. Keep in mind that most browsers will still have issue with that and even IE will raise the COM security bar to users. So unless its not something you are offering within organisation, don't do it.

Create an ArrayList with multiple object types?

You could create a List<Object>, but you really don't want to do this. Mixed lists that abstract to Object are not very useful and are a potential source of bugs. In fact the fact that your code requires such a construct gives your code a bad code smell and suggests that its design may be off. Consider redesigning your program so you aren't forced to collect oranges with orangutans.

Instead -- do what G V recommends and I was about to recommend, create a custom class that holds both int and String and create an ArrayList of it. 1+ to his answer!

How to quickly drop a user with existing privileges

The accepted answer resulted in errors for me when attempting REASSIGN OWNED BY or DROP OWNED BY. The following worked for me:

REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
DROP USER username;

The user may have privileges in other schemas, in which case you will have to run the appropriate REVOKE line with "public" replaced by the correct schema. To show all of the schemas and privilege types for a user, I edited the \dp command to make this query:

SELECT 
  n.nspname as "Schema",
  CASE c.relkind 
    WHEN 'r' THEN 'table' 
    WHEN 'v' THEN 'view' 
    WHEN 'm' THEN 'materialized view' 
    WHEN 'S' THEN 'sequence' 
    WHEN 'f' THEN 'foreign table' 
  END as "Type"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.array_to_string(c.relacl, E'\n') LIKE '%username%';

I'm not sure which privilege types correspond to revoking on TABLES, SEQUENCES, or FUNCTIONS, but I think all of them fall under one of the three.

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Fixed header, footer with scrollable content

Now we've got CSS grid. Welcome to 2019.

_x000D_
_x000D_
/* Required */_x000D_
body {_x000D_
   margin: 0;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
   height: 100vh;_x000D_
   display: grid;_x000D_
   grid-template-rows: 30px 1fr 30px;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   overflow-y: scroll;_x000D_
}_x000D_
_x000D_
/* Optional */_x000D_
#wrapper > * {_x000D_
   padding: 5px;_x000D_
}_x000D_
_x000D_
#header {_x000D_
   background-color: #ff0000ff;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   background-color: #00ff00ff;_x000D_
}_x000D_
_x000D_
#footer {_x000D_
   background-color: #0000ffff;_x000D_
}
_x000D_
<body>_x000D_
   <div id="wrapper">_x000D_
      <div id="header">Header Content</div>_x000D_
      <div id="content">_x000D_
         Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
      </div>_x000D_
      <div id="footer">Footer Content</div>_x000D_
   </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Export and import table dump (.sql) using pgAdmin

If you have Git bash installed, you can do something like this:

/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

Extracted from this article:

  1. Go to your run command and enter:

    netstat -o -n -a | findstr 0.0:80

The last number here is the process ID using it. This is most often IIS or other web relates service and is easy to resolve, but every so often (very often it would seem looking around on google) it appears to be PID 4 – which according to the Windows Task Manager is the NT Kernel and System. Not very helpful given killing this will result in a blue screen of death.

The thing hogging port 80 has nothing to do with IIS or web anything, it's SQL Server Reporting Services. Turn off anything that resembles a SQL Server Services and start Apache again, no need for a reboot.

So problems with PID 4 listening to port 80? Check your SQL services and turn them off.

UPDATE - Comment from @sangam:

Worked at a shot. In my case, it turned out to be SQL server reporting services. I stopped the service for all the installed instances, and it worked (without machine reboot).

Select info from table where row has max date

Using an in can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:

SELECT *
  FROM (SELECT msisdn
              ,callid
              ,Change_color
              ,play_file_name
              ,date_played
          FROM insert_log
         WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
        ORDER BY callid ASC) t1
       JOIN (SELECT MAX(date_played) AS date_played
               FROM insert_log GROUP BY callid) t2
         ON t1.date_played = t2.date_played

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

Font-awesome provides a great solution out of the box:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />_x000D_
_x000D_
<ul class='fa-ul'>_x000D_
  <li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
  <li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Cannot uninstall angular-cli

I had angular-cli version 1.0.0-beta.28.3, and the only thing that worked for me was deleting the angular-cli directly from the global node_modules folder:

cd /usr/local/bin/lib/node_modules
rm -rf angular-cli

After that ng version output was, as expected:

command not found: ng

And I could install the latest angular-cli version:

npm install -g @angular/cli@latest

Hope it helps...

Fastest way to download a GitHub project

Downloading with Git using Windows CMD from a GitHub project

You can get download the link from GitHub <b>HTTPS clone URL</b>

Download with Window Command Prompt cmd for above picture HTTPS clone URL

  1. Copy the HTTPS clone URL shown in picture 1

  2. Open CMD

  3. git clone //paste the URL show in picture 2

What is the worst programming language you ever worked with?

LabVIEW (is that even considered a language?)

It was horrible. If you want to broaden the term, HTML sucks too, as does XML.

sqlalchemy: how to join several tables by one query?

A good style would be to setup some relations and a primary key for permissions (actually, usually it is good style to setup integer primary keys for everything, but whatever):

class User(Base):
    __tablename__ = 'users'
    email = Column(String, primary_key=True)
    name = Column(String)

class Document(Base):
    __tablename__ = "documents"
    name = Column(String, primary_key=True)
    author_email = Column(String, ForeignKey("users.email"))
    author = relation(User, backref='documents')

class DocumentsPermissions(Base):
    __tablename__ = "documents_permissions"
    id = Column(Integer, primary_key=True)
    readAllowed = Column(Boolean)
    writeAllowed = Column(Boolean)
    document_name = Column(String, ForeignKey("documents.name"))
    document = relation(Document, backref = 'permissions')

Then do a simple query with joins:

query = session.query(User, Document, DocumentsPermissions).join(Document).join(DocumentsPermissions)

How to make a div with no content have a width?

I had the same issue. I wanted icons to appear by pressing the button but without any movement and sliding the enviroment, just like bulb: on and off, appeared and dissapeared, so I needed to make an empty div with fixed sizes.

width: 13px;
min-width: 13px;

did the trick for me

How to play .wav files with java

Another way of doing it with AudioInputStream:

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.swing.JDialog;
import javax.swing.JFileChooser;

public class CoreJavaSound extends Object implements LineListener {
    File soundFile;

    JDialog playingDialog;

    Clip clip;

    public static void main(String[] args) throws Exception {
        CoreJavaSound s = new CoreJavaSound();
    }

    public CoreJavaSound() throws Exception {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        soundFile = chooser.getSelectedFile();

        System.out.println("Playing " + soundFile.getName());

        Line.Info linfo = new Line.Info(Clip.class);
        Line line = AudioSystem.getLine(linfo);
        clip = (Clip) line;
        clip.addLineListener(this);
        AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
        clip.open(ais);
        clip.start();
    }

    public void update(LineEvent le) {
        LineEvent.Type type = le.getType();
        if (type == LineEvent.Type.OPEN) {
            System.out.println("OPEN");
        } else if (type == LineEvent.Type.CLOSE) {
            System.out.println("CLOSE");
            System.exit(0);
        } else if (type == LineEvent.Type.START) {
            System.out.println("START");
            playingDialog.setVisible(true);
        } else if (type == LineEvent.Type.STOP) {
            System.out.println("STOP");
            playingDialog.setVisible(false);
            clip.close();
        }
    }
}

C compile error: Id returned 1 exit status

I may guess, the old instance of your program is still running. Windows does not allow to change the files which are currently "in use" and your linker cannot write the new .exe on the top of the running one. Try stopping/killing your program.

CSS3 Fade Effect

The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..

E.g.

a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}

How to iterate through range of Dates in Java?

The following snippet (uses java.time.format of Java 8) maybe used to iterate over a date range :

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    // Any chosen date format maybe taken  
    LocalDate startDate = LocalDate.parse(startDateString,formatter);
    LocalDate endDate = LocalDate.parse(endDateString,formatter);
    if(endDate.isBefore(startDate))
    {
        //error
    }
    LocalDate itr = null;
    for (itr = startDate; itr.isBefore(endDate)||itr.isEqual(itr); itr = itr.plusDays(1))
    {
        //Processing  goes here
    }

The plusMonths()/plusYears() maybe chosen for time unit increment. Increment by a single day is being done in above illustration.

Create normal zip file programmatically

You should look into Zip Packages

They are a more structured version of normal ZIP archives, requiring some meta stuff in the root. So other ZIP tools can open a package, but the Sysytem.IO.Packaging API can not open all ZIP files.

Convert a string to a double - is this possible?

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

$s = '1234.13';
$double = bcadd($s,'0',2);

PHP: bcadd

How to list all Git tags?

You can list all existing tags git tag or you could filter the list with git tag -l 'v1.1.*', where * acts as a wildcard. It will return a list of tags marked with v1.1.

You will notice that when you call git tag you do not get to see the contents of your annotations. To preview them you must add -n to your command: git tag -n2.

$ git tag -l -n2

v1.0 Release version 1.0

v1.1 Release version 1.1

The command lists all existing tags with maximum 3 lines of their tag message. By default -n only shows the first line. For more info be sure to check this tag related article as well.

How to count the number of occurrences of an element in a List

Put the elements of the arraylist in the hashMap to count the frequency.

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

How to reverse a 'rails generate'

We use generate as rails generate app. So regenerating any generate statement can be reversed using destroy statement. Just replace generate with destroy i.e. rails generate app can be written as rails destroy app' rails generate ____asrails destroy ____`

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

SQL command to display history of queries

You can look at the query cache: http://www.databasejournal.com/features/mysql/article.php/3110171/MySQLs-Query-Cache.htm but it might not give you access to the actual queries and will be very hit-and-miss if it did work (subtle pun intended)

But MySQL Query Browser very likely maintains its own list of queries that it runs, outside of the MySQL engine. You would have to do the same in your app.

Edit: see dan m's comment leading to this: How to show the last queries executed on MySQL? looks sound.

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

How can I truncate a string to the first 20 words in PHP?

based on ????'s answer:

function truncate_words($string,$words=20) {
 return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
}

or

function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') {
 $new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
 if($new != $string){
  return $new.$ellipsis;
 }else{
  return $string;
 }

}

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

In my case, someone had come along and incorrectly edited the redis.conf file to this:

bind 127.0.0.1 ::1
bind 192.168.1.7

when, it really needed to be this (one line):

bind 127.0.0.1 ::1 192.168.1.7

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

How can I resolve the error: "The command [...] exited with code 1"?

Check your paths: If you are using a separate build server for TFS (most likely), make sure that all your paths in the .csproj file match the TFS server paths. I got the above error when checking in the *.csproj file when it had references to my development machine paths and not the TFS server paths.

Remove multi-line commands: Also, try and remove multi-line commands into single-line commands in xml as a precaution. I had the following xml in the *.proj that caused issues in TFS:

<Exec Condition="bl.." 
Command=" Blah...
..." </Exec>

Changing the above xml to this worked:

  <Exec Condition="bl.." Command=" Blah..." </Exec>

Calling one Activity from another in Android

check the following code to open new activit.

Intent f = new Intent(MainActivity.this, SecondActivity.class);

startActivity(f);

Get the week start date and week end date from week number

I just encounter a similar case with this one, but the solution here seems not helping me. So I try to figure it out by myself. I work out the week start date only, week end date should be of similar logic.

Select 
      Sum(NumberOfBrides) As [Wedding Count], 
      DATEPART( wk, WeddingDate) as [Week Number],
      DATEPART( year, WeddingDate) as [Year],
      DATEADD(DAY, 1 - DATEPART(WEEKDAY, dateadd(wk, DATEPART( wk, WeddingDate)-1,  DATEADD(yy,DATEPART( year, WeddingDate)-1900,0))), dateadd(wk, DATEPART( wk, WeddingDate)-1, DATEADD(yy,DATEPART( year, WeddingDate)-1900,0))) as [Week Start]

FROM  MemberWeddingDates
Group By DATEPART( year, WeddingDate), DATEPART( wk, WeddingDate)
Order By Sum(NumberOfBrides) Desc

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

No need to uninstall it or going crazy with symbolic links, just use an alias. I faced the same problem when upgrading to python 3.7.1.
Just install the new python version using brew install python then in your .bash_profile create an alias pointing to the new python version; like this: alias python="/usr/local/bin/python3" then save and run source ~/.bash_profile.
Done.

File upload progress bar with jQuery

I have used the following in my project. you can try too.

ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {

    if (ajax.status) {

        if (ajax.status == 200 && (ajax.readyState == 4)){
            //To do tasks if any, when upload is completed
        }
    }
}
ajax.upload.addEventListener("progress", function (event) {

    var percent = (event.loaded / event.total) * 100;
    //**percent** variable can be used for modifying the length of your progress bar.
    console.log(percent);

});

ajax.open("POST", 'your file upload link', true);
ajax.send(formData);
//ajax.send is for uploading form data.

cannot load such file -- bundler/setup (LoadError)

i had the same issue and tried all the answers without any luck.

steps i did to reproduce:

  1. rvm instal 2.1.10
  2. rvm gemset create my_gemset
  3. rvm use 2.1.10@my_gemset
  4. bundle install

however bundle install installed Rails, but i still got cannot load such file -- bundler/setup (LoadError)

finally running gem install rails -v 4.2 fixed it

SameSite warning Chrome 77

I had to disable this in chrome://flags

enter image description here

Half circle with CSS (border, outline only)

Below is a minimal code to achieve the effect.

This also works responsively since the border-radius is in percentage.

_x000D_
_x000D_
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
_x000D_
_x000D_

Parse JSON response using jQuery

The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].

You have to iterate through that values to get actuall value. Like the following

jQuery provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (linktext, link) {
        console.log(linktext);
        console.log(link);
    });
});

Now just create an Hyperlink using that info.

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

You can do it by simply aliasing the MAMP php on Apple terminal:

alias phpmamp='/Applications/MAMP/bin/php/php7.0.0/bin/php'

Example: > phpmamp - v

Now you can run something like: > phpmamp scriptname.php

Note: This will be applied only for the current terminal session.

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Jquery Date picker Default Date

interesting, datepicker default date is current date as I found,

but you can set date by

$("#yourinput").datepicker( "setDate" , "7/11/2011" );

don't forget to check you system date :)

"inappropriate ioctl for device"

Ran into this error today while trying to use code to delete a folder/files that are living on a Windoze 7 box that's mounted as a share on a Centos server. Got the inappropriate icotl for device error and tried everything that came to mind. Read just about every post on the net related to this.

Obviously the problem was isolated to the mounted Windoze share on the Linux server. Looked at the file permissions on the Windoze box and noted the files had their permissions set to read only.

Changed those, went back to the Linux server and all worked as expected. This may not be the solution for most but hopefully it saves someone some time.

Where do I get servlet-api.jar from?

Make sure that you're using the same Servlet API specification that your Web container supports. Refer to this chart if you're using Tomcat: http://tomcat.apache.org/whichversion.html

The Web container that you use will definitely have the API jars you require.

Tomcat 6 for example has it in apache-tomcat-6.0.26/lib/servlet-api.jar

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

Upgrade your SqlServer management studio from 2008 to 2012

Or Download the service packs of SqlServer Management Studio and update probably resolve you solution

You can download the SQL Server Management studio 2012 from below link

Microsoft® SQL Server® 2012 Express http://www.microsoft.com/en-us/download/details.aspx?id=29062

How to set the Android progressbar's height?

You can use the LinearProgressIndicator provided by the Material Components Library and the app:trackThickness attribute:

<com.google.android.material.progressindicator.LinearProgressIndicator
    android:indeterminate="true"
    app:trackThickness="xxdp"
    ../>

With 12dp:

enter image description here

With 4dp:

enter image description here

Note: it requires at least the version 1.3.0-alpha04.

GitLab remote: HTTP Basic: Access denied and fatal Authentication

Well, I faced the same issue whenever I change my login password.

Below is the command I need to run to fix this issue:-

git config --global credential.helper wincred

After running above command it asks me again my updated username and password.

Using C# to read/write Excel files (.xls/.xlsx)

I'm a big fan of using EPPlus to perform these types of actions. EPPlus is a library you can reference in your project and easily create/modify spreadsheets on a server. I use it for any project that requires an export function.

Here's a nice blog entry that shows how to use the library, though the library itself should come with some samples that explain how to use it.

Third party libraries are a lot easier to use than Microsoft COM objects, in my opinion. I would suggest giving it a try.

WooCommerce: Finding the products in database

The following tables are store WooCommerce products database :

  • wp_posts -

    The core of the WordPress data is the posts. It is stored a post_type like product or variable_product.

  • wp_postmeta-

    Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id of product in wp_postmeta table.

Product categories, subcategories stored in this table :

  • wp_terms
  • wp_termmeta
  • wp_term_taxonomy
  • wp_term_relationships
  • wp_woocommerce_termmeta

following Query Return a list of product categories

SELECT wp_terms.* 
    FROM wp_terms 
    LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
    WHERE wp_term_taxonomy.taxonomy = 'product_cat';

for more reference -

WARNING: sanitizing unsafe style value url

There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272

I didn't read in detail when this warning is printed when nothing was sanitized.

WPF Image Dynamically changing Image source during runtime

Hey, this one is kind of ugly but it's one line only:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));

how to add <script>alert('test');</script> inside a text box?

Ok to answer this . I simply converted my < and the > to &lt; and &gt;. What was happening previously is i used to set the text <script>alert('1')</script> but before setting the text in the input text browserconverts &lt; and &gt; as < and the >. So hence converting them again to &lt; and &gt;since browser will understand that as only tags and converts them , than executing the script inside <input type="text" />

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

I have solved my php7 issues on centos 7 by updating /etc/php.ini with these settings:

 post_max_size = 500M
 upload_max_filesize = 500M

Hash Map in Python

class HashMap:
    def __init__(self):
        self.size = 64
        self.map = [None] * self.size

    def _get_hash(self, key):
        hash = 0

        for char in str(key):
            hash += ord(char)
        return hash % self.size

    def add(self, key, value):
        key_hash = self._get_hash(key)
        key_value = [key, value]

        if self.map[key_hash] is None:
            self.map[key_hash] = list([key_value])
            return True
        else:
            for pair in self.map[key_hash]:
                if pair[0] == key:
                    pair[1] = value
                    return True
                else:
                    self.map[key_hash].append(list([key_value]))
                    return True

    def get(self, key):
        key_hash = self._get_hash(key)
        if self.map[key_hash] is not None:
            for pair in self.map[key_hash]: 
                if pair[0] == key:
                    return pair[1]
        return None

    def delete(self, key):
        key_hash = self._get_hash(key)

        if self.map[key_hash] is None :
            return False
        for i in range(0, len(self.map[key_hash])):
            if self.map[key_hash][i][0] == key:
                self.map[key_hash].pop(i)
                return True

    def print(self):

        print('---Phonebook---')
        for item in self.map:
            if item is not None:
                print(str(item))

h = HashMap()

HTML code for an apostrophe

A List Apart has a nice reference on characters and typography in HTML. According to that article, the correct HTML entity for the apostrophe is &#8217;. Example use: ’ .

How to sort an array of objects with jquery or javascript

the sort method contains an optional argument to pass a custom compare function.

Assuming you wanted an array of arrays:

var arr = [[3, "Mike", 20],[5, "Alex", 15]];

function compareName(a, b)
{

  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}
arr.sort(compareName);

Otherwise if you wanted an array of objects, you could do:

function compareName(a, b)
{

  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
}

npm start error with create-react-app

add environment variables in windows

  1. C:\WINDOWS\System32
  2. C:\Program Files\nodejs
  3. C:\Program Files\nodejs\node_modules\npm\bin
  4. C:\WINDOWS\System32\WindowsPowerShell\v1.0
  5. C:\Users{your system name without curly braces}\AppData\Roaming\npm

these 5 are must in path.

and use the latest version of node.js

Correlation heatmap

  1. Use the 'jet' colormap for a transition between blue and red.
  2. Use pcolor() with the vmin, vmax parameters.

It is detailed in this answer: https://stackoverflow.com/a/3376734/21974

jQueryUI modal dialog does not show close button (x)

I suppose there is some conflict with other JS library in your code. Try to force showing the close button:

...
open:function () {
  $(".ui-dialog-titlebar-close").show();
} 
...

This worked for me.

Java's L number (long) specification

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix).

How do I write a correct micro-benchmark in Java?

To add to the other excellent advice, I'd also be mindful of the following:

For some CPUs (e.g. Intel Core i5 range with TurboBoost), the temperature (and number of cores currently being used, as well as thier utilisation percent) affects the clock speed. Since CPUs are dynamically clocked, this can affect your results. For example, if you have a single-threaded application, the maximum clock speed (with TurboBoost) is higher than for an application using all cores. This can therefore interfere with comparisons of single and multi-threaded performance on some systems. Bear in mind that the temperature and volatages also affect how long Turbo frequency is maintained.

Perhaps a more fundamentally important aspect that you have direct control over: make sure you're measuring the right thing! For example, if you're using System.nanoTime() to benchmark a particular bit of code, put the calls to the assignment in places that make sense to avoid measuring things which you aren't interested in. For example, don't do:

long startTime = System.nanoTime();
//code here...
System.out.println("Code took "+(System.nanoTime()-startTime)+"nano seconds");

Problem is you're not immediately getting the end time when the code has finished. Instead, try the following:

final long endTime, startTime = System.nanoTime();
//code here...
endTime = System.nanoTime();
System.out.println("Code took "+(endTime-startTime)+"nano seconds");

How to store arrays in MySQL?

In MySQL, use the JSON type.

Contra the answers above, the SQL standard has included array types for almost twenty years; they are useful, even if MySQL has not implemented them.

In your example, however, you'll likely want to create three tables: person and fruit, then person_fruit to join them.

DROP TABLE IF EXISTS person_fruit;
DROP TABLE IF EXISTS person;
DROP TABLE IF EXISTS fruit;

CREATE TABLE person (
  person_id   INT           NOT NULL AUTO_INCREMENT,
  person_name VARCHAR(1000) NOT NULL,
  PRIMARY KEY (person_id)
);

CREATE TABLE fruit (
  fruit_id    INT           NOT NULL AUTO_INCREMENT,
  fruit_name  VARCHAR(1000) NOT NULL,
  fruit_color VARCHAR(1000) NOT NULL,
  fruit_price INT           NOT NULL,
  PRIMARY KEY (fruit_id)
);

CREATE TABLE person_fruit (
  pf_id     INT NOT NULL AUTO_INCREMENT,
  pf_person INT NOT NULL,
  pf_fruit  INT NOT NULL,
  PRIMARY KEY (pf_id),
  FOREIGN KEY (pf_person) REFERENCES person (person_id),
  FOREIGN KEY (pf_fruit) REFERENCES fruit (fruit_id)
);

INSERT INTO person (person_name)
VALUES
  ('John'),
  ('Mary'),
  ('John'); -- again

INSERT INTO fruit (fruit_name, fruit_color, fruit_price)
VALUES
  ('apple', 'red', 1),
  ('orange', 'orange', 2),
  ('pineapple', 'yellow', 3);

INSERT INTO person_fruit (pf_person, pf_fruit)
VALUES
  (1, 1),
  (1, 2),
  (2, 2),
  (2, 3),
  (3, 1),
  (3, 2),
  (3, 3);

If you wish to associate the person with an array of fruits, you can do so with a view:

DROP VIEW IF EXISTS person_fruit_summary;
CREATE VIEW person_fruit_summary AS
  SELECT
    person_id                                                                                              AS pfs_person_id,
    max(person_name)                                                                                       AS pfs_person_name,
    cast(concat('[', group_concat(json_quote(fruit_name) ORDER BY fruit_name SEPARATOR ','), ']') as json) AS pfs_fruit_name_array
  FROM
    person
    INNER JOIN person_fruit
      ON person.person_id = person_fruit.pf_person
    INNER JOIN fruit
      ON person_fruit.pf_fruit = fruit.fruit_id
  GROUP BY
    person_id;

The view shows the following data:

+---------------+-----------------+----------------------------------+
| pfs_person_id | pfs_person_name | pfs_fruit_name_array             |
+---------------+-----------------+----------------------------------+
|             1 | John            | ["apple", "orange"]              |
|             2 | Mary            | ["orange", "pineapple"]          |
|             3 | John            | ["apple", "orange", "pineapple"] |
+---------------+-----------------+----------------------------------+

In 5.7.22, you'll want to use JSON_ARRAYAGG, rather than hack the array together from a string.

"Auth Failed" error with EGit and GitHub

I was having the same issue which it seems was down to config issue. The github mac osx app had created a ssh private key called github_rsa

In your Eclipse go to Window > Preferences > Network Connections > SSH2

In the general tab you should see SSH2 home /Users/<you username>/.ssh you'll probably see id_dsa,id_rsa defined as private keys.

Click 'Add private key' and select github_rsa located /Users/<you username>/.ssh

Regular Expression: Any character that is NOT a letter or number

  • Match letters only /[A-Z]/ig
  • Match anything not letters /[^A-Z]/ig
  • Match number only /[0-9]/g or /\d+/g
  • Match anything not number /[^0-9]/g or /\D+/g
  • Match anything not number or letter /[^A-Z0-9]/ig

There are other possible patterns

Get current language in CultureInfo

Current system language is retrieved using :

  CultureInfo.InstalledUICulture

"Gets the CultureInfo that represents the culture installed with the operating system."

InstalledUICulture

To set it as default language for thread use :

   System.Globalization.CultureInfo.DefaultThreadCurrentCulture=CultureInfo.InstalledUICulture;

Set Colorbar Range in matplotlib

Using figure environment and .set_clim()

Could be easier and safer this alternative if you have multiple plots:

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )
data1 = np.clip(data,0,6)
data2 = np.clip(data,-6,0)
vmin = np.min(np.array([data,data1,data2]))
vmax = np.max(np.array([data,data1,data2]))

fig = plt.figure()
ax = fig.add_subplot(131)
mesh = ax.pcolormesh(data, cmap = cm)
mesh.set_clim(vmin,vmax)
ax1 = fig.add_subplot(132)
mesh1 = ax1.pcolormesh(data1, cmap = cm)
mesh1.set_clim(vmin,vmax)
ax2 = fig.add_subplot(133)
mesh2 = ax2.pcolormesh(data2, cmap = cm)
mesh2.set_clim(vmin,vmax)
# Visualizing colorbar part -start
fig.colorbar(mesh,ax=ax)
fig.colorbar(mesh1,ax=ax1)
fig.colorbar(mesh2,ax=ax2)
fig.tight_layout()
# Visualizing colorbar part -end

plt.show()

enter image description here

A single colorbar

The best alternative is then to use a single color bar for the entire plot. There are different ways to do that, this tutorial is very useful for understanding the best option. I prefer this solution that you can simply copy and paste instead of the previous visualizing colorbar part of the code.

fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8,
                    wspace=0.4, hspace=0.1)
cb_ax = fig.add_axes([0.83, 0.1, 0.02, 0.8])
cbar = fig.colorbar(mesh, cax=cb_ax)

enter image description here

P.S.

I would suggest using pcolormesh instead of pcolor because it is faster (more infos here ).

Looping through a DataTable

If you want to change the contents of each and every cell in a datatable then we need to Create another Datatable and bind it as follows using "Import Row". If we don't create another table it will throw an Exception saying "Collection was Modified".

Consider the following code.

//New Datatable created which will have updated cells
DataTable dtUpdated = new DataTable();

//This gives similar schema to the new datatable
dtUpdated = dtReports.Clone();
foreach (DataRow row in dtReports.Rows)
{
    for (int i = 0; i < dtReports.Columns.Count; i++)
    {
        string oldVal = row[i].ToString();
        string newVal = "{"+oldVal;
        row[i] = newVal;
    }
    dtUpdated.ImportRow(row); 
}

This will have all the cells preceding with Paranthesis({)

How to save a list to a file and read it as a list type?

If you want you can use numpy's save function to save the list as file. Say you have two lists

sampleList1=['z','x','a','b']
sampleList2=[[1,2],[4,5]]

here's the function to save the list as file, remember you need to keep the extension .npy

def saveList(myList,filename):
    # the filename should mention the extension 'npy'
    np.save(filename,myList)
    print("Saved successfully!")

and here's the function to load the file into a list

def loadList(filename):
    # the filename should mention the extension 'npy'
    tempNumpyArray=np.load(filename)
    return tempNumpyArray.tolist()

a working example

>>> saveList(sampleList1,'sampleList1.npy')
>>> Saved successfully!
>>> saveList(sampleList2,'sampleList2.npy')
>>> Saved successfully!

# loading the list now 
>>> loadedList1=loadList('sampleList1.npy')
>>> loadedList2=loadList('sampleList2.npy')

>>> loadedList1==sampleList1
>>> True

>>> print(loadedList1,sampleList1)

>>> ['z', 'x', 'a', 'b'] ['z', 'x', 'a', 'b']

Kubernetes Pod fails with CrashLoopBackOff

I faced similar issue "CrashLoopBackOff" when I debugged getting pods and logs of pod. Found out that my command arguments are wrong

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

"could not find stored procedure"

Sometimes this can also happen when you have a stored procedure being called with parameters. For example, if you type something like:

set @runProc = 'dbo.StoredProcedure'
 exec @runProc

This will work, However:

set @runProc = 'dbo.StoredProcedure ''foods'''
exec @runProc

This will throw the error "could not find stored procedure dbo.StoredProcedure 'foods'", however this can easily be overcome with parantheses like so:

set @runProc = 'exec dbo.StoredProcedure ''foods'''
exec (@runProc)

Sending cookies with postman

You can enable Interceptor in browser and in Postman separately. For send/recieve cookies you should enable Interceptor in Postman. So if you enable interceptor only in browser - it will not work. Actually you don't need enable Interceptor in browser at all - if you don't want to flood your postman history with unnecessary requests.

How to leave space in HTML

As others already answered, $nbsp; will output no-break space character. Here is w3 docs for &nbsp and others.

However there is other ways to do it and nowdays i would prefer using CSS stylesheets. There is also w3c tutorials for beginners.

With CSS you can do it like this:

<html>
    <head>
        <title>CSS test</title>
        <style type="text/css">
            p { word-spacing: 40px; }
        </style>
    </head>
    <body>
        <p>Hello World! Enough space between words, what do you think about it?</p>
    </body>
</html>

How can I add spaces between two <input> lines using CSS?

Try to minimize the use of <br> as much as you possibly can. HTML is supposed to carry content and structure, <br> is neither. A simple workaround is to wrap your input elements in <p> elements, like so:

<form name="publish" id="publish" action="publishprocess.php" method="post">

    <p><input type="text" id="title" name="title" size="60" maxlength="110" value="<?php echo $title ?>" /> - Title</p>
    <p><input type="text" id="contact" name="contact" size="24" maxlength="30" value="<?php echo $contact ?>" /> - Contact</p>

    <p>Task description (you may include task description, requirements on bidders, time requirements, etc):</p>
    <p><textarea name="detail" id="detail" rows="7" cols="60" style="font-family:Arial, Helvetica, sans-serif"><?php echo $detail ?></textarea></p>

    <p><input type="text" id="price" name="price" size="10" maxlength="20" value="<?php echo $price ?>" /> - Price</p>

    <p><input class="tagvalidate" type="text" id="tag" name="tag" size="40" maxlength="60" value="<?php echo $tag ?>" /> - Skill or Knowledge Tags</p>
    <p>Combine multiple words into single-words, space to separate up to 3 tags (example:photoshop quantum-physics computer-programming)</p>

    <p>District Restriction:<?php echo $locationtext.$cityname; ?></p>

    <p><input type="submit" id="submit" value="Submit" /></p>
</form>

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

You can use replaceAll() method :

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

etc..

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

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

Downloading a file from spring controllers

  1. Return ResponseEntity<Resource> from a handler method
  2. Specify Content-Type explicitly
  3. Set Content-Disposition if necessary:
    1. filename
    2. type
      1. inline to force preview in a browser
      2. attachment to force a download
@Controller
public class DownloadController {
    @GetMapping("/downloadPdf.pdf")
    // 1.
    public ResponseEntity<Resource> downloadPdf() {
        FileSystemResource resource = new FileSystemResource("/home/caco3/Downloads/JMC_Tutorial.pdf");
        // 2.
        MediaType mediaType = MediaTypeFactory
                .getMediaType(resource)
                .orElse(MediaType.APPLICATION_OCTET_STREAM);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        // 3
        ContentDisposition disposition = ContentDisposition
                // 3.2
                .inline() // or .attachment()
                // 3.1
                .filename(resource.getFilename())
                .build();
        headers.setContentDisposition(disposition);
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }
}

Explanation

Return ResponseEntity<Resource>

When you return a ResponseEntity<Resource>, the ResourceHttpMessageConverter kicks in and writes an appropriate response.

The resource could be:

Be aware of possibly wrong Content-Type header set (see FileSystemResource is returned with content type json). That's why this answer suggests setting the Content-Type explicitly.

Specify Content-Type explicitly:

Some options are:

The MediaTypeFactory allows to discover the MediaType appropriate for the Resource (see also /org/springframework/http/mime.types file)

Set Content-Disposition if necessary:

Sometimes it is necessary to force a download in a browser or to make the browser open a file as a preview. You can use the Content-Disposition header to satisfy this requirement:

The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).

In the Spring Framework a ContentDisposition can be used.

To preview a file in a browser:

ContentDisposition disposition = ContentDisposition
        .builder("inline") // Or .inline() if you're on Spring MVC 5.3+
        .filename(resource.getFilename())
        .build();

To force a download:

ContentDisposition disposition = ContentDisposition
        .builder("attachment") // Or .attachment() if you're on Spring MVC 5.3+
        .filename(resource.getFilename())
        .build();

Use InputStreamResource carefully:

Since an InputStream can be read only once, Spring won't write Content-Length header if you return an InputStreamResource (here is a snippet of code from ResourceHttpMessageConverter):

@Override
protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException {
    // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
    // Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
    if (InputStreamResource.class == resource.getClass()) {
        return null;
    }
    long contentLength = resource.contentLength();
    return (contentLength < 0 ? null : contentLength);
}

In other cases it works fine:

~ $ curl -I localhost:8080/downloadPdf.pdf  | grep "Content-Length"
Content-Length: 7554270

XOR operation with two strings in java

This solution is compatible with Android (I've tested and used it myself). Thanks to @user467257 whose solution I adapted this from.

import android.util.Base64;

public class StringXORer {

public String encode(String s, String key) {
    return new String(Base64.encode(xorWithKey(s.getBytes(), key.getBytes()), Base64.DEFAULT));
}

public String decode(String s, String key) {
    return new String(xorWithKey(base64Decode(s), key.getBytes()));
}

private byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
        out[i] = (byte) (a[i] ^ key[i%key.length]);
    }
    return out;
}

private byte[] base64Decode(String s) {
    return Base64.decode(s,Base64.DEFAULT);
}

private String base64Encode(byte[] bytes) {
    return new String(Base64.encode(bytes,Base64.DEFAULT));

}
}

How to round up a number in Javascript?

Normal rounding will work with a small tweak:

Math.round(price * 10)/10

and if you want to keep a currency format, you can use the Number method .toFixed()

(Math.round(price * 10)/10).toFixed(2)

Though this will make it a String =)

How do I load the contents of a text file into a javascript variable?

If you only want a constant string from the text file, you could include it as JavaScript:

_x000D_
_x000D_
// This becomes the content of your foo.txt file_x000D_
let text = `_x000D_
My test text goes here!_x000D_
`;
_x000D_
<script src="foo.txt"></script>_x000D_
<script>_x000D_
  console.log(text);_x000D_
</script>
_x000D_
_x000D_
_x000D_

The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.

This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the file:// scheme.

How to iterate a loop with index and element in Swift

For completeness you can simply iterate over your array indices and use subscript to access the element at the corresponding index:

let list = [100,200,300,400,500]
for index in list.indices {
    print("Element at:", index, " Value:", list[index])
}

Using forEach

list.indices.forEach {
    print("Element at:", $0, " Value:", list[$0])
}

Using collection enumerated() method. Note that it returns a collection of tuples with the offset and the element:

for item in list.enumerated() {
    print("Element at:", item.offset, " Value:", item.element)
}

using forEach:

list.enumerated().forEach {
    print("Element at:", $0.offset, " Value:", $0.element)
}

Those will print

Element at: 0 Value: 100

Element at: 1 Value: 200

Element at: 2 Value: 300

Element at: 3 Value: 400

Element at: 4 Value: 500

If you need the array index (not the offset) and its element you can extend Collection and create your own method to get the indexed elements:

extension Collection {
    func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
        var index = startIndex
        for element in self {
            try body((index,element))
            formIndex(after: &index)
        }
    }
}

Another possible implementation as suggested by Alex is to zip the collection indices with its elements:

extension Collection {
    func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
        for element in zip(indices, self) { try body(element) }
    }
    var indexedElements: Zip2Sequence<Indices, Self> { zip(indices, self) }
}

Testing:

let list =  ["100","200","300","400","500"]

// You can iterate the index and its elements using a closure
list.dropFirst(2).indexedElements {
    print("Index:", $0.index, "Element:", $0.element)
}

// or using a for loop
for (index, element) in list.indexedElements  {
    print("Index:", index, "Element:", element)
}

This will p[rint

Index: 2 Element: 300

Index: 3 Element: 400

Index: 4 Element: 500

Index: 0 Element: 100

Index: 1 Element: 200

Index: 2 Element: 300

Index: 3 Element: 400

Index: 4 Element: 500

Read CSV with Scanner()

I have seen many production problems caused by code not handling quotes ("), newline characters within quotes, and quotes within the quotes; e.g.: "he said ""this""" should be parsed into: he said "this"

Like it was mentioned earlier, many CSV parsing examples out there just read a line, and then break up the line by the separator character. This is rather incomplete and problematic.

For me and probably those who prefer build verses buy (or use somebody else's code and deal with their dependencies), I got down to classic text parsing programming and that worked for me:

/**
 * Parse CSV data into an array of String arrays. It handles double quoted values.
 * @param is input stream
 * @param separator
 * @param trimValues
 * @param skipEmptyLines
 * @return an array of String arrays
 * @throws IOException
 */
public static String[][] parseCsvData(InputStream is, char separator, boolean trimValues, boolean skipEmptyLines)
    throws IOException
{
    ArrayList<String[]> data = new ArrayList<String[]>();
    ArrayList<String> row = new ArrayList<String>();
    StringBuffer value = new StringBuffer();
    int ch = -1;
    int prevCh = -1;
    boolean inQuotedValue = false;
    boolean quoteAtStart = false;
    boolean rowIsEmpty = true;
    boolean isEOF = false;

    while (true)
    {
        prevCh = ch;
        ch = (isEOF) ? -1 : is.read();

        // Handle carriage return line feed
        if (prevCh == '\r' && ch == '\n')
        {
            continue;
        }
        if (inQuotedValue)
        {
            if (ch == -1)
            {
                inQuotedValue = false;
                isEOF = true;
            }
            else
            {
                value.append((char)ch);

                if (ch == '"')
                {
                    inQuotedValue = false;
                }
            }
        }
        else if (ch == separator || ch == '\r' || ch == '\n' || ch == -1)
        {
            // Add the value to the row
            String s = value.toString();

            if (quoteAtStart && s.endsWith("\""))
            {
                s = s.substring(1, s.length() - 1);
            }
            if (trimValues)
            {
                s = s.trim();
            }
            rowIsEmpty = (s.length() > 0) ? false : rowIsEmpty;
            row.add(s);
            value.setLength(0);

            if (ch == '\r' || ch == '\n' || ch == -1)
            {
                // Add the row to the result
                if (!skipEmptyLines || !rowIsEmpty)
                {
                    data.add(row.toArray(new String[0]));
                }
                row.clear();
                rowIsEmpty = true;

                if (ch == -1)
                {
                    break;
                }
            }
        }
        else if (prevCh == '"')
        {
            inQuotedValue = true;
        }
        else
        {
            if (ch == '"')
            {
                inQuotedValue = true;
                quoteAtStart = (value.length() == 0) ? true : false;
            }
            value.append((char)ch);
        }
    }
    return data.toArray(new String[0][]);
}

Unit Test:

String[][] data = parseCsvData(new ByteArrayInputStream("foo,\"\",,\"bar\",\"\"\"music\"\"\",\"carriage\r\nreturn\",\"new\nline\"\r\nnext,line".getBytes()), ',', true, true);
for (int rowIdx = 0; rowIdx < data.length; rowIdx++)
{
    System.out.println(Arrays.asList(data[rowIdx]));
}

generates the output:

[foo, , , bar, "music", carriage
return, new
line]
[next, line]

SMTP error 554

To resolve problem go to the MDaemon-->setup-->Miscellaneous options-->Server-->SMTP Server Checks commands and headers for RFC Compliance

How to calculate the number of occurrence of a given character in each row of a column of strings?

The question below has been moved here, but it seems this page doesn't directly answer to Farah El's question. How to find number 1s in 101 in R

So, I'll write an answer here, just in case.

library(magrittr)
n %>% # n is a number you'd like to inspect
  as.character() %>%
  str_count(pattern = "1")

https://stackoverflow.com/users/8931457/farah-el

JavaScript listener, "keypress" doesn't detect backspace?

Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field

window.addEventListener("keydown", function(e){
    /*
     * keyCode: 8
     * keyIdentifier: "U+0008"
    */
    if(e.keyCode === 8 && document.activeElement !== 'text') {
        e.preventDefault();
        alert('Prevent page from going back');
    }
});

How do I find out what License has been applied to my SQL Server installation?

I presume you mean via SSMS?

For a SQL Server Instance:

SELECT SERVERPROPERTY('productversion'), 
       SERVERPROPERTY ('productlevel'), 
       SERVERPROPERTY ('edition')

For a SQL Server Installation:

Select @@Version

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

jQuery toggle CSS?

The initiale code must have borderBottomLeftRadius: 0px

$('#user_button').toggle().css('borderBottomLeftRadius','+5px');

What's the syntax to import a class in a default package in Java?

It is not a compilation error at all! You can import a default package to a default package class only.

If you do so for another package, then it shall be a compilation error.

How to support different screen size in android

Adding to @ud_an

It is not a good practice to create different folders for layouts. Create your layout such that it works fine with all the screen sizes. To achieve this, play with the layout attributes. You only need to have different images for hdpi, mdpi and ldpi types. The rest will be managed by android OS.

org.json.simple cannot be resolved

try this

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

A KeyValuePair in Java

The class AbstractMap.SimpleEntry is generic and can be useful.

jsPDF multi page PDF with HTML renderer

Automatically not split data to multi pages. You may split manually.

If your ( rowCount * rowHeight ) > 420mm ( A3 Height in mm ) add new page function. ( Sorry I can't edit your code without run ) After add new page leftMargin, topMargin = 0; ( start over ) I added sample code with yours. I hope it's right.

else {
    doc.margins = 1;
    doc.setFont("Times  ");
    doc.setFontType("normal ");
    doc.setFontSize(11);
    if ( rowCount * rowHeight > 420 ) {
        doc.addPage();
        rowCount = 3; // skip 1 and 2 above
    } else {
        // now rowcount = 3 ( top of new page for 3 )
        // j is your x axis cell index ( j start from 0 on $.each function ) or you can add cellCount like rowCount and replace with
        // rowcount is your y axis cell index
        left = ( ( j ) * ( cellWidth + leftMargin );
        top = ( ( rowcount - 3 ) * ( rowHeight + topMargin );
        doc.cell( leftMargin, top, cellWidth, rowHeight, cellContent, i);
        // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
    }
}

You can convert html directly to pdf lossless. Youtube video for html => pdf example

How to use _CRT_SECURE_NO_WARNINGS

Add by

Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS

screenshot of the relevant config interface

Can an int be null in Java?

Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.

Eg: Integer i=null;

How do I make an asynchronous GET request in PHP?

For me the question about asynchronous GET request is appeared because of I met with situation when I need to do hundreds of requests, get and deal with result data on every request and every request takes significant milliseconds of executing that leads to minutes(!) of total executing with simple file_get_contents.

In this case it was very helpful comment of w_haigh at php.net on function http://php.net/manual/en/function.curl-multi-init.php

So, here is my upgraded and cleaned version of making lot of requests simultaneously. For my case it's equivalent to "asynchronous" way. May be it helps for someone!

// Build the multi-curl handle, adding both $ch
$mh = curl_multi_init();

// Build the individual requests, but do not execute them
$chs = [];
$chs['ID0001'] = curl_init('http://webservice.example.com/?method=say&word=Hello');
$chs['ID0002'] = curl_init('http://webservice.example.com/?method=say&word=World');
// $chs[] = ...
foreach ($chs as $ch) {
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,  // Return requested content as string
        CURLOPT_HEADER => false,         // Don't save returned headers to result
        CURLOPT_CONNECTTIMEOUT => 10,    // Max seconds wait for connect
        CURLOPT_TIMEOUT => 20,           // Max seconds on all of request
        CURLOPT_USERAGENT => 'Robot YetAnotherRobo 1.0',
    ]);

    // Well, with a little more of code you can use POST queries too
    // Also, useful options above can be  CURLOPT_SSL_VERIFYHOST => 0  
    // and  CURLOPT_SSL_VERIFYPEER => false ...

    // Add every $ch to the multi-curl handle
    curl_multi_add_handle($mh, $ch);
}

// Execute all of queries simultaneously, and continue when ALL OF THEM are complete
$running = null;
do {
    curl_multi_exec($mh, $running);
} while ($running);

// Close the handles
foreach ($chs as $ch) {
    curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);

// All of our requests are done, we can now access the results
// With a help of ids we can understand what response was given
// on every concrete our request
$responses = [];
foreach ($chs as $id => $ch) {
    $responses[$id] = curl_multi_getcontent($ch);
    curl_close($ch);
}
unset($chs); // Finita, no more need any curls :-)

print_r($responses); // output results

It's easy to rewrite this to handle POST or other types of HTTP(S) requests or any combinations of them. And Cookie support, redirects, http-auth, etc.

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Change application's starting activity

This is easy to fix.

  • Changes to the Launcher activity are also stored in the Debug configuration.
  • Go to Run > Debug Configurations and edit the setting.
  • There is also a similar setting in Intellij under Run > Edit Configurations select Run default Activity and it will no longer save the setting in this fashion.

Target elements with multiple classes, within one rule

.border-blue.background { ... } is for one item with multiple classes.
.border-blue, .background { ... } is for multiple items each with their own class.
.border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

See Chris' answer for a more thorough explanation.

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

jquery smooth scroll to an anchor?

works

$('a[href*=#]').each(function () {
    $(this).attr('href', $(this).attr('href').replace('#', '#_'));
    $(this).on( "click", function() {

        var hashname = $(this).attr('href').replace('#_', '');

        if($(this).attr('href') == "#_") {
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
        else {
            var target = $('a[name="' + hashname + '"], #' + hashname),
                targetOffset = target.offset().top;
            if(targetOffset >= 1) {
                $('html, body').animate({ scrollTop: targetOffset-60 }, 300);
            }
        }
    });
});

Body of Http.DELETE request in Angular2

You are actually able to fool Angular2 HTTP into sending a body with a DELETE by using the request method. This is how:

let body = {
    target: targetId,
    subset: "fruits",
    reason: "rotten"
};

let options = new RequestOptionsArgs({ 
    body: body,
    method: RequestMethod.Delete
  });

this.http.request('http://testAPI:3000/stuff', options)
    .subscribe((ok)=>{console.log(ok)});

Note, you will have to set the request method in the RequestOptionsArgs and not in http.request's alternative first parameter Request. That for some reason yields the same result as using http.delete

I hope this helps and that I am not to late. I think the angular guys are wrong here to not allow a body to be passed with delete, even though it is discouraged.

What does API level mean?

An API is ready-made source code library.

In Java for example APIs are a set of related classes and interfaces that come in packages. This picture illustrates the libraries included in the Java Standard Edition API. Packages are denoted by their color.

This pictures illustrates the libraries included in the Java Standard Edition API

How to show what a commit did?

The answers by Bomber and Jakub (Thanks!) are correct and work for me in different situations.

For a quick glance at what was in the commit, I use

git show <replace this with your commit-id>

But I like to view a graphical Diff when studying something in detail and have set up a P4diff as my git diff and then use

git diff <replace this with your commit-id>^!

How to create an Oracle sequence starting with max value from a table?

use dynamic sql

BEGIN
            DECLARE
            maxId NUMBER;
              BEGIN
              SELECT MAX(id)+1
              INTO maxId
              FROM table_name;          
              execute immediate('CREATE SEQUENCE sequane_name MINVALUE '||maxId||' START WITH '||maxId||' INCREMENT BY 1 NOCACHE NOCYCLE');
              END;
END;

How do I allow HTTPS for Apache on localhost?

This worked on Windows 10 with Apache24:

1 - Add this at the bottom of C:/Apache24/conf/httpd.conf

Listen 443
<VirtualHost *:443>
    DocumentRoot "C:/Apache24/htdocs"
    ServerName localhost
    SSLEngine on
    SSLCertificateFile "C:/Apache24/conf/ssl/server.crt"
    SSLCertificateKeyFile "C:/Apache24/conf/ssl/server.key"
</VirtualHost>

2 - Add the server.crt and server.key files in the C:/Apache24/conf/ssl folder. See other answers on this page to find those 2 files.

That's it!

How to retrieve the LoaderException property?

catch (ReflectionTypeLoadException ex)
{        
    foreach (var item in ex.LoaderExceptions)
    {
          MessageBox.Show(item.Message);                    
    }
}

I'm sorry for resurrecting an old thread, but wanted to post a different solution to pull the loader exception (Using the actual ReflectionTypeLoadException) for anybody else to come across this.

HTML img scaling

No Javascript required.

IE6 Internet Explorer 6

Percent only works for the width of an element, but height:100%; does not work without the correct code.

CSS

html, body { height:100%; } 

Then using a percentage works properly, and dynamically updates on window resize.

<img src="image.jpg" style="height:80%;">

You do not need a width attribute, the width scales proportionately as the browser window size is changed.

And this little gem, is in case the image is scaled up, it will not look (overly) blocky (it interpolates).

img { -ms-interpolation-mode: bicubic; }

Props go to this source: Ultimate IE6 Cheatsheet: How To Fix 25+ Internet Explorer 6 Bugs

How do I run Python code from Sublime Text 2?

You can access the Python console via “View/Show console” or Ctrl+`.

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

Maybe unrelated to the original reason in this question, but for those who would face same with gradle and local module dependency

dependencies {
    checkstyle project(":module")
}

this error could happen, if module doesn't contain group and version, so in the module/build.gradle just need to be specified

plugins {
    id 'java-library'
}

group = "com.example"
version = "master-SNAPSHOT"

How to get a JavaScript object's class?

In javascript, there are no classes, but I think that you want the constructor name and obj.constructor.toString() will tell you what you need.

C# Clear all items in ListView

Just use the clear method is works like a charm. ListView1.Items.Clear() i think if its not working it may be the position whereby you place this code. Also can try nullifying the datasource.

Link a .css on another folder

I think what you want to do is

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
_x000D_
_x000D_

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

this is better approach and its successful :

Actions oAction = new Actions(driver);
oAction.moveToElement(Webelement);
oAction.contextClick(Webelement).build().perform();  /* this will perform right click */
WebElement elementOpen = driver.findElement(By.linkText("Open")); /*This will select menu after right click */

elementOpen.click();

Set database timeout in Entity Framework

For Database first Aproach:

We can still set it in a constructor, by override the ContextName.Context.tt T4 Template this way:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
        Database.CommandTimeout = 180;
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}

Database.CommandTimeout = 180; is the acutaly change.

The generated output is this:

public ContextName() : base("name=ContextName")
{
    Database.CommandTimeout = 180;
}

If you change your Database Model, this template stays, but the actualy class will be updated.

How to resize an image with OpenCV2.0 and Python2.6

def rescale_by_height(image, target_height, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_height` (preserving aspect ratio)."""
    w = int(round(target_height * image.shape[1] / image.shape[0]))
    return cv2.resize(image, (w, target_height), interpolation=method)

def rescale_by_width(image, target_width, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_width` (preserving aspect ratio)."""
    h = int(round(target_width * image.shape[0] / image.shape[1]))
    return cv2.resize(image, (target_width, h), interpolation=method)

How to open .SQLite files

I would suggest using R and the package RSQLite

#install.packages("RSQLite") #perhaps needed
library("RSQLite")

# connect to the sqlite file
sqlite    <- dbDriver("SQLite")
exampledb <- dbConnect(sqlite,"database.sqlite")

dbListTables(exampledb)

Vim: insert the same characters across multiple lines

:%s/^/vendor_/

or am I missing something?

How to get the first 2 letters of a string in Python?

to print first two letter of a string

str = "string"

print(str[0:2])

How to place a file on classpath in Eclipse?

Just to add. If you right-click on an eclipse project and select Properties, select the Java Build Path link on the left. Then select the Source Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src folder is the classpath folder.

Java, How to add library files in netbeans?

For Netbeans 2020 September version. JDK 11

(Suggesting this for Gradle project only)

1. create libs folder in src/main/java folder of the project

2. copy past all library jars in there

3. open build.gradle in files tab of project window in project's root

4. correct main class (mine is mainClassName = 'uz.ManipulatorIkrom')

5. and in dependencies add next string:

apply plugin: 'java' 
apply plugin: 'jacoco' 
apply plugin: 'application'
description = 'testing netbeans'
mainClassName = 'uz.ManipulatorIkrom' //4th step
repositories {
    jcenter()
}
dependencies {
    implementation fileTree(dir: 'src/main/java/libs', include: '*.jar') //5th step   
}

6. save, clean-build and then run the app

How to restore the dump into your running mongodb

mongodump --host test.mongodb.net --port 27017 --db --username --password --authenticationDatabase admin --ssl --out

mongorestore --db --verbose

How to add Active Directory user group as login in SQL Server

Here is my observation. I created a login (readonly) for a group windows(AD) user account but, its acting defiantly in different SQL servers. In the SQl servers that users can not see the databases I added view definition checked and also gave database execute permeation to the master database for avoiding error 229. I do not have this issue if I create a login for a user.

Centering text in a table in Twitter Bootstrap

The .table td 's text-align is set to left, rather than center.

Adding this should center all your tds:

.table td {
   text-align: center;   
}

_x000D_
_x000D_
@import url('https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css');_x000D_
table,_x000D_
thead,_x000D_
tr,_x000D_
tbody,_x000D_
th,_x000D_
td {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.table td {_x000D_
  text-align: center;_x000D_
}
_x000D_
<table class="table">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>1</th>_x000D_
      <th>1</th>_x000D_
      <th>1</th>_x000D_
      <th>1</th>_x000D_
      <th>2</th>_x000D_
      <th>2</th>_x000D_
      <th>2</th>_x000D_
      <th>2</th>_x000D_
      <th>3</th>_x000D_
      <th>3</th>_x000D_
      <th>3</th>_x000D_
      <th>3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td colspan="4">Lorem</td>_x000D_
      <td colspan="4">ipsum</td>_x000D_
      <td colspan="4">dolor</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Updated JSFIDDLE

Find closing HTML tag in Sublime Text

There is a shortcut (Ctrl+Shift+A for Windows and Linux users, Command+Shift+A for Mac users) to select the whole block within the currently selected tag.

For example, if you pressed this while your text cursor was within the outer div tag in the code below, all the divs with class selected would be selected.

<div class='current_tag_block'>
  <div class='selected'></div>
  <div class='selected'></div>
  <div class='selected'></div>
  <div class='selected'></div>
</div>

How to add action listener that listens to multiple buttons

The problem is that button1 is a local variable. You could do it by just change the way you add the actionListener.

button.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e)
            {
                //button is pressed
                System.out.println("You clicked the button");
            }});

Or you make button1 a global variable.

What's a good IDE for Python on Mac OS X?

You might want to look into Eclim, an Eclipse server that allows you to use Eclipse functionality from within your favorite text editor. For python-related functionality, it uses Rope, PyFlakes, and PyLint under the hood.

Navigation Drawer (Google+ vs. YouTube)

I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.

How to get data from observable in angular2

this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

Four fewer characters, but 2 more ms

%%timeit
df.isna().T.any()
# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
df.isna().any(axis=1)
# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

I'd probably use axis=1

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

Java 8 stream reverse order

This is how I do it.

I don't like the idea of creating a new collection and reverse iterating it.

The IntStream#map idea is pretty neat, but I prefer the IntStream#iterate method, for I think the idea of a countdown to Zero better expressed with the iterate method and easier to understand in terms of walking the array from back to front.

import static java.lang.Math.max;

private static final double EXACT_MATCH = 0d;

public static IntStream reverseStream(final int[] array) {
    return countdownFrom(array.length - 1).map(index -> array[index]);
}

public static DoubleStream reverseStream(final double[] array) {
    return countdownFrom(array.length - 1).mapToDouble(index -> array[index]);
}

public static <T> Stream<T> reverseStream(final T[] array) {
    return countdownFrom(array.length - 1).mapToObj(index -> array[index]);
}

public static IntStream countdownFrom(final int top) {
    return IntStream.iterate(top, t -> t - 1).limit(max(0, (long) top + 1));
}

Here are some tests to prove it works:

import static java.lang.Integer.MAX_VALUE;
import static org.junit.Assert.*;

@Test
public void testReverseStream_emptyArrayCreatesEmptyStream() {
    Assert.assertEquals(0, reverseStream(new double[0]).count());
}

@Test
public void testReverseStream_singleElementCreatesSingleElementStream() {
    Assert.assertEquals(1, reverseStream(new double[1]).count());
    final double[] singleElementArray = new double[] { 123.4 };
    assertArrayEquals(singleElementArray, reverseStream(singleElementArray).toArray(), EXACT_MATCH);
}

@Test
public void testReverseStream_multipleElementsAreStreamedInReversedOrder() {
    final double[] arr = new double[] { 1d, 2d, 3d };
    final double[] revArr = new double[] { 3d, 2d, 1d };
    Assert.assertEquals(arr.length, reverseStream(arr).count());
    Assert.assertArrayEquals(revArr, reverseStream(arr).toArray(), EXACT_MATCH);
}

@Test
public void testCountdownFrom_returnsAllElementsFromTopToZeroInReverseOrder() {
    assertArrayEquals(new int[] { 4, 3, 2, 1, 0 }, countdownFrom(4).toArray());
}

@Test
public void testCountdownFrom_countingDownStartingWithZeroOutputsTheNumberZero() {
    assertArrayEquals(new int[] { 0 }, countdownFrom(0).toArray());
}

@Test
public void testCountdownFrom_doesNotChokeOnIntegerMaxValue() {
    assertEquals(true, countdownFrom(MAX_VALUE).anyMatch(x -> x == MAX_VALUE));
}

@Test
public void testCountdownFrom_givesZeroLengthCountForNegativeValues() {
    assertArrayEquals(new int[0], countdownFrom(-1).toArray());
    assertArrayEquals(new int[0], countdownFrom(-4).toArray());
}

Using a cursor with dynamic SQL in a stored procedure

A cursor will only accept a select statement, so if the SQL really needs to be dynamic make the declare cursor part of the statement you are executing. For the below to work your server will have to be using global cursors.

Declare @UserID varchar(100)
declare @sqlstatement nvarchar(4000)
--move declare cursor into sql to be executed
set @sqlstatement = 'Declare  users_cursor CURSOR FOR SELECT userId FROM users'

exec sp_executesql @sqlstatement


OPEN users_cursor
FETCH NEXT FROM users_cursor
INTO @UserId

WHILE @@FETCH_STATUS = 0
BEGIN
Print @UserID
EXEC asp_DoSomethingStoredProc @UserId

FETCH NEXT FROM users_cursor --have to fetch again within loop
INTO @UserId

END
CLOSE users_cursor
DEALLOCATE users_cursor

If you need to avoid using the global cursors, you could also insert the results of your dynamic SQL into a temporary table, and then use that table to populate your cursor.

Declare @UserID varchar(100)
create table #users (UserID varchar(100))

declare @sqlstatement nvarchar(4000)
set @sqlstatement = 'Insert into #users (userID) SELECT userId FROM users'
exec(@sqlstatement)

declare users_cursor cursor for Select UserId from #Users
OPEN users_cursor
FETCH NEXT FROM users_cursor
INTO @UserId

WHILE @@FETCH_STATUS = 0
BEGIN

EXEC asp_DoSomethingStoredProc @UserId

FETCH NEXT FROM users_cursor
INTO @UserId

END
CLOSE users_cursor
DEALLOCATE users_cursor

drop table #users

How to catch a specific SqlException error?

You can evaluate based on severity type. Note to use this you must be subscribed to OnInfoMessage

conn.InfoMessage += OnInfoMessage;
conn.FireInfoMessageEventOnUserErrors = true;

Then your OnInfoMessage would contain:

foreach(SqlError err in e.Errors) {
//Informational Errors
if (Between(Convert.ToInt16(err.Class), 0, 10, true)) {
    logger.Info(err.Message);
//Errors users can correct.
} else if (Between(Convert.ToInt16(err.Class), 11, 16, true)) {
    logger.Error(err.Message);
//Errors SysAdmin can correct.
} else if (Between(Convert.ToInt16(err.Class), 17, 19, true)) {
    logger.Error(err.Message);
//Fatal Errors 20+
} else {
    logger.Fatal(err.Message);
}}

This way you can evaluate on severity rather than on error number and be more effective. You can find more information on severity here.

private static bool Between( int num, int lower, int upper, bool inclusive = false )
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}

JQuery datepicker language

Include js files of datepicker and language (locales)

'resource/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
'resource/bower_components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.sv.min.js',

In the options of the datepicker, set the language as below:

$('.datepicker').datepicker({'language' : 'sv'});

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

This exception could point to the LINQ parameter that is named source:

 System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)

As the source parameter in your LINQ query (var nCounts = from sale in sal) is 'sal', I suppose the list named 'sal' might be null.

Catching nullpointerexception in Java

I think your problem is inside CheckCircular, in the while condition:

Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

I got this error when Updating code first MVC5 database. Dropping (right click, delete) all the tables from my database and removing the migrations from the Migration folder worked for me.

How do I filter ForeignKey choices in a Django ModelForm?

A more public way is by calling get_form in Admin classes. It also works for non-database fields too. For example here i have a field called '_terminal_list' on the form that can be used in special cases for choosing several terminal items from get_list(request), then filtering based on request.user:

class ChangeKeyValueForm(forms.ModelForm):  
    _terminal_list = forms.ModelMultipleChoiceField( 
queryset=Terminal.objects.all() )

    class Meta:
        model = ChangeKeyValue
        fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time',  ] 

class ChangeKeyValueAdmin(admin.ModelAdmin):
    form = ChangeKeyValueForm
    list_display = ('terminal','task_list', 'plugin','last_update_time')
    list_per_page =16

    def get_form(self, request, obj = None, **kwargs):
        form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)
        qs, filterargs = Terminal.get_list(request)
        form.base_fields['_terminal_list'].queryset = qs
        return form

Your branch is ahead of 'origin/master' by 3 commits

This message from git means that you have made three commits in your local repo, and have not published them to the master repository. The command to run for that is git push {local branch name} {remote branch name}.

The command git pull (and git pull --rebase) are for the other situation when there are commit on the remote repo that you don't have in your local repo. The --rebase option means that git will move your local commit aside, synchronise with the remote repo, and then try to apply your three commit from the new state. It may fail if there is conflict, but then you'll be prompted to resolve them. You can also abort the rebase if you don't know how to resolve the conflicts by using git rebase --abort and you'll get back to the state before running git pull --rebase.

How do you perform address validation?

There are companies that provide this service. Service bureaus that deal with mass mailing will scrub an entire mailing list to that it's in the proper format, which results in a discount on postage. The USPS sells databases of address information that can be used to develop custom solutions. They also have lists of approved vendors who provide this kind of software and service.

There are some (but not many) packages that have APIs for hooking address validation into your software.

However, you're right that its a pretty nasty problem.

http://www.usps.com/ncsc/ziplookup/vendorslicensees.htm

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

VS 2017 Git Local Commit DB.lock error on every commit

enter image description here

For me these two files I have deleted by mistake, after undo these two files and get added in my changes, I was able to commit my changes to git.

Failed to resolve: com.google.firebase:firebase-core:16.0.1

Since May 23, 2018 update, when you're using a firebase dependency, you must include the firebase-core dependency, too.

If adding it, you still having the error, try to update the gradle plugin in your gradle-wrapper.properties to 4.5 version:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip

and resync the project.

Nth max salary in Oracle

This will show the 3rd max salary from table employee. If you want to find out the 5th or 6th (whatever you want) value then just change the where condition like this where rownum<=5" or "where rownum<=6 and so on...

select min(sal) from(select distinct(sal) from emp  where rownum<=3 order by sal desc);

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

redirected uri is the location where the user will be redirected after successfully login to your app. for example to get access token for your app in facebook you need to subimt redirected uri which is nothing only the app Domain that your provide when you create your facebook app.

Use of "global" keyword in Python

Accessing a name and assigning a name are different. In your case, you are just accessing a name.

If you assign to a variable within a function, that variable is assumed to be local unless you declare it global. In the absence of that, it is assumed to be global.

>>> x = 1         # global 
>>> def foo():
        print x       # accessing it, it is global

>>> foo()
1
>>> def foo():   
        x = 2        # local x
        print x 

>>> x            # global x
1
>>> foo()        # prints local x
2

ES6 Class Multiple inheritance

use Mixins for ES6 multiple Inheritence.

let classTwo = Base => class extends Base{
    // ClassTwo Code
};

class Example extends classTwo(ClassOne) {
    constructor() {
    }
}

How to style a JSON block in Github Wiki?

Some color-syntaxing enrichment can be applied with the following blockcode syntax

```json
Here goes your json object definition
```

Note: This won't prettify the json representation. To do so, one can previously rely on an external service such as jsbeautifier.org and paste the prettified result in the wiki.

JavaScript backslash (\) in variables is causing an error

The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx

type object 'datetime.datetime' has no attribute 'datetime'

from datetime import datetime
import time
from calendar import timegm
d = datetime.utcnow()
d = d.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
utc_time = time.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = timegm(utc_time)

Help needed with Median If in Excel

Assuming your categories are in cells A1:A6 and the corresponding values are in B1:B6, you might try typing the formula =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) in another cell and then pressing CTRL+SHIFT+ENTER.

Using CTRL+SHIFT+ENTER tells Excel to treat the formula as an "array formula". In this example, that means that the IF statement returns an array of 6 values (one of each of the cells in the range $A$1:$A$6) instead of a single value. The MEDIAN function then returns the median of these values. See http://www.cpearson.com/excel/arrayformulas.aspx for a similar example using AVERAGE instead of MEDIAN.

Remote origin already exists on 'git push' to a new repository

I just faced this issue myself and I just removed it by removing the origin. the origin is removed by this command

git remove rm origin

try implementing this command.

PHP Warning Permission denied (13) on session_start()

PHP does not have permissions to write on /tmp directory. You need to use chmod command to open /tmp permissions.

postgres default timezone

The time zone is a session parameter. So, you can change the timezone for the current session.

See the doc.

set timezone TO 'GMT';

Or, more closely following the SQL standard, use the SET TIME ZONE command. Notice two words for "TIME ZONE" where the code above uses a single word "timezone".

SET TIME ZONE 'UTC';

The doc explains the difference:

SET TIME ZONE extends syntax defined in the SQL standard. The standard allows only numeric time zone offsets while PostgreSQL allows more flexible time-zone specifications. All other SET features are PostgreSQL extensions.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Coding Conventions - Naming Enums

In our codebase; we typically declare enums in the class that they belong to.

So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.

Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear, etc.

Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT). (side note; all our constants are in upper case)

As always, your coding standards probably differ from mine; so YMMV.

How to output a multiline string in Bash?

Since I recommended printf in a comment, I should probably give some examples of its usage (although for printing a usage message, I'd be more likely to use Dennis' or Chris' answers). printf is a bit more complex to use than echo. Its first argument is a format string, in which escapes (like \n) are always interpreted; it can also contain format directives starting with %, which control where and how any additional arguments are included in it. Here are two different approaches to using it for a usage message:

First, you could include the entire message in the format string:

printf "usage: up [--level <n>| -n <levels>][--help][--version]\n\nReport bugs to: \nup home page: \n"

Note that unlike echo, you must include the final newline explicitly. Also, if the message happens to contain any % characters, they would have to be written as %%. If you wanted to include the bugreport and homepage addresses, they can be added quite naturally:

printf "usage: up [--level <n>| -n <levels>][--help][--version]\n\nReport bugs to: %s\nup home page: %s\n" "$bugreport" "$homepage"

Second, you could just use the format string to make it print each additional argument on a separate line:

printf "%s\n" "usage: up [--level <n>| -n <levels>][--help][--version]" "" "Report bugs to: " "up home page: "

With this option, adding the bugreport and homepage addresses is fairly obvious:

printf "%s\n" "usage: up [--level <n>| -n <levels>][--help][--version]" "" "Report bugs to: $bugreport" "up home page: $homepage"

How to get distinct values for non-key column fields in Laravel?

Grouping by will not work if the database rules don't allow any of the select fields to be outside of an aggregate function. Instead use the laravel collections.

$users = DB::table('users')
        ->select('id','name', 'email')
        ->get();

foreach($users->unique('name') as $user){
  //....
}

Someone pointed out that this may not be great on performance for large collections. I would recommend adding a key to the collection. The method to use is called keyBy. This is the simple method.

     $users = DB::table('users')
        ->select('id','name', 'email')
        ->get()
        ->keyBy('name');

The keyBy also allows you to add a call back function for more complex things...

     $users = DB::table('users')
        ->select('id','name', 'email')
        ->get()
        ->keyBy(function($user){
              return $user->name . '-' . $user->id;
         });

If you have to iterate over large collections, adding a key to it solve the performance issue.

Tuples( or arrays ) as Dictionary keys in C#

Between tuple and nested dictionaries based approaches, it's almost always better to go for tuple based.

From maintainability point of view,

  • its much easier to implement a functionality that looks like:

    var myDict = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
    

    than

    var myDict = new Dictionary<TypeA, Dictionary<TypeB, Dictionary<TypeC, string>>>();
    

    from the callee side. In the second case each addition, lookup, removal etc require action on more than one dictionary.

  • Furthermore, if your composite key require one more (or less) field in future, you will need to change code a significant lot in the second case (nested dictionary) since you have to add further nested dictionaries and subsequent checks.

From performance perspective, the best conclusion you can reach is by measuring it yourself. But there are a few theoretical limitations which you can consider beforehand:

  • In the nested dictionary case, having an additional dictionary for every keys (outer and inner) will have some memory overhead (more than what creating a tuple would have).

  • In the nested dictionary case, every basic action like addition, updation, lookup, removal etc need to be carried out in two dictionaries. Now there is a case where nested dictionary approach can be faster, i.e., when the data being looked up is absent, since the intermediate dictionaries can bypass the full hash code computation & comparison, but then again it should be timed to be sure. In presence of data, it should be slower since lookups should be performed twice (or thrice depending on nesting).

  • Regarding tuple approach, .NET tuples are not the most performant when they're meant to be used as keys in sets since its Equals and GetHashCode implementation causes boxing for value types.

I would go with tuple based dictionary, but if I want more performance, I would use my own tuple with better implementation.


On a side note, few cosmetics can make the dictionary cool:

  1. Indexer style calls can be a lot cleaner and intuitive. For eg,

    string foo = dict[a, b, c]; //lookup
    dict[a, b, c] = ""; //update/insertion
    

    So expose necessary indexers in your dictionary class which internally handles the insertions and lookups.

  2. Also, implement a suitable IEnumerable interface and provide an Add(TypeA, TypeB, TypeC, string) method which would give you collection initializer syntax, like:

    new MultiKeyDictionary<TypeA, TypeB, TypeC, string> 
    { 
        { a, b, c, null }, 
        ...
    };
    

What is the Simplest Way to Reverse an ArrayList?

A little more readable :)

public static <T> ArrayList<T> reverse(ArrayList<T> list) {
    int length = list.size();
    ArrayList<T> result = new ArrayList<T>(length);

    for (int i = length - 1; i >= 0; i--) {
        result.add(list.get(i));
    }

    return result;
}

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

Vim clear last search highlighting

I think mixing @ShaunBouckaert and Mar 19 '09 at 16:22 answers is a good compromise :

" Reset highlighted search
nnoremap <CR> :let @/=""<CR><CR>

Press Enter and the highlighted text is no longer highlighted, while search highlighting is still enabled.

Does JavaScript have the interface type (such as Java's 'interface')?

This is old but I implemented interfaces to use on ES6 without transpiller.

https://github.com/jkutianski/ES6-Interfaces

Display text from .txt file in batch file

@echo off
set log=%time% %date%
echo %log%

That is a batch for saving the date and time as a temporary variable, and displaying it. In a hurry, I don't have time to write a script to open a txt, maybe later.

Lost connection to MySQL server during query?

Make sure you close cursor before connection. I've resolved my problem with this:

if cur and con:                        
    cur.close() 
    con.close() 

Align an element to bottom with flexbox

I just found a solution for this.

for those who are not satisfied with the given answers can try this approach with flexbox

CSS

    .myFlexContainer {
        display: flex;
        width: 100%;
    }

    .myFlexChild {
        width: 100%;
        display: flex;

        /* 
         * set this property if this is set to column by other css class 
         *  that is used by your target element 
         */
        flex-direction: row;

        /* 
         * necessary for our goal 
         */
        flex-wrap: wrap;
        height: 500px;
    }

    /* the element you want to put at the bottom */
    .myTargetElement {
        /*
         * will not work unless flex-wrap is set to wrap and 
         * flex-direction is set to row
         */
        align-self: flex-end;
    }

HTML

    <div class="myFlexContainer">
        <div class="myFlexChild">
            <p>this is just sample</p>
            <a class="myTargetElement" href="#">set this to bottom</a>
        </div>
    </div>

What is the best way to merge mp3 files?

David's answer is correct that just concatenating the files will leave ID3 tags scattered inside (although this doesn't normally affect playback, so you can do "copy /b" or on UNIX "cat a.mp3 b.mp3 > combined.mp3" in a pinch).

However, mp3wrap isn't exactly the right tool to just combine multiple MP3s into one "clean" file. Rather than using ID3, it actually inserts its own custom data format in amongst the MP3 frames (the "wrap" part), which causes issues with playback, particularly on iTunes and iPods. Although the file will play back fine if you just let them run from start to finish (because players will skip these is arbitrary non-MPEG bytes) the file duration and bitrate will be reported incorrectly, which breaks seeking. Also, mp3wrap will wipe out all your ID3 metadata, including cover art, and fail to update the VBR header with the correct file length.

mp3cat on its own will produce a good concatenated data file (so, better than mp3wrap), but it also strips ID3 tags and fails to update the VBR header with the correct length of the joined file.

Here's a good explanation of these issues and method (two actually) to combine MP3 files and produce a "clean" final result with original metadata intact -- it's command-line so works on Mac/Linux/BSD etc. It uses:

  • mp3cat to combine the MPEG data frames only into a continuous file, then
  • id3cp to copy all metadata over to the combined file, and finally
  • VBRFix to update the VBR header.

For a Windows GUI tool, take a look at Merge MP3 -- it takes care of everything. (VBRFix also comes in GUI form, but it doesn't do the joining.)

Eclipse interface icons very small on high resolution screen in Windows 8.1

Have a look at Neon (4.6) M6 - New and Noteworthy, the milestone release contains some automatic scaling for images (e.g. for toolbar).

SWT provides resolution-based auto-scaling

SWT now automatically scales images on high-DPI monitors on Windows and Linux, similar to the Mac's Retina support on OS X. In the absence of high-resolution images, SWT will auto-scale the available images to ensure that SWT-based applications like Eclipse are scaled proportionately to the resolution of the monitor.

enter image description here

This feature can be disabled on Windows and GTK by setting this VM argument to false in eclipse.ini or on the command line after -vmargs:

-Dswt.enable.autoScale=false

Auto-scaling cannot be disabled on the Mac as it is provided by the OS.

Caveats: We're aware that some scaled images look bad at scale factors less than 200%. This will be improved in M7. Furthermore, we're working on support for high-DPI images in Platform UI, so that plug-in providers can add high-DPI icons without doing any code changes.



Or maybe this helps, in Eclipse Mars API for high resolution was added

New APIs have been added to provide support for rendering high-resolution images on high-DPI monitors. Two constructors have been added to the Image class. They accept image-provider callbacks that allow clients to supply resolution-dependent versions of images:

public interface ImageDataProvider {
  public ImageData getImageData (int zoom);
}
public interface ImageFileNameProvider {
  public String getImagePath (int zoom);
}

Depending on the user's monitor configuration, SWT will request images with the corresponding zoom level. Here's an example that displays 3 original images, followed by variants whose resolution changes depending your monitor's resolution: Snippet367.java.

Note that this is just the first step to support high-resolution images in SWT and Eclipse-based applications. Work is underway to adopt the new APIs in the platform. Futhermore, more work in SWT is required to properly support drawing into high-resolution images via GC.

APIs for high-DPI monitor support
http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2FwhatsNew%2Fplatform_isv_whatsnew.html

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

First, edit NetworkManager.conf file:

vim /etc/NetworkManager/NetworkManager.conf

Comment this line:

#dns=dnsmasq

Finally

sudo service network-manager restart
sudo service docker restart

ld cannot find an existing library

Unless I'm badly mistaken libmagic or -lmagic is not the same library as ImageMagick. You state that you want ImageMagick.

ImageMagick comes with a utility to supply all appropriate options to the compiler.

Ex:

g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o "prog"

Using Mockito to test abstract classes

PowerMock's Whitebox.invokeMethod(..) can be handy in this case.

Need to list all triggers in SQL Server database with table name and table's schema

One difficulty is that the text, or description has line feeds. My clumsy kludge, to get it in something more tabular, is to add an HTML literal to the SELECT clause, copy and paste everything to notepad, save with an html extension, open in a browser, then copy and paste to a spreadsheet. example

SELECT obj.NAME AS TBL,trg.name,sm.definition,'<br>'
FROM SYS.OBJECTS obj
LEFT JOIN (SELECT trg1.object_id,trg1.parent_object_id,trg1.name FROM sys.objects trg1 WHERE trg1.type='tr' AND trg1.name like 'update%') trg
 ON obj.object_id=trg.parent_object_id
LEFT JOIN (SELECT sm1.object_id,sm1.definition FROM sys.sql_modules sm1 where sm1.definition like '%suser_sname()%') sm ON trg.object_id=sm.object_id
WHERE obj.type='u'
ORDER BY obj.name;

you may still need to fool around with tabs to get the description into one field, but at least it'll be on one line, which I find very helpful.

What is the App_Data folder used for in Visual Studio?

It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.

How to select distinct rows in a datatable and store into an array

You can use like that:

data is DataTable

data.DefaultView.ToTable(true, "Id", "Name", "Role", "DC1", "DC2", "DC3", "DC4", "DC5", "DC6", "DC7");  

but performance will be down. try to use below code:

data.AsEnumerable().Distinct(System.Data.DataRowComparer.Default).ToList();  

For Performance ; http://onerkaya.blogspot.com/2013/01/distinct-dataviewtotable-vs-linq.html

Equal sized table cells to fill the entire width of the containing table

Using table-layout: fixed as a property for table and width: calc(100%/3); for td (assuming there are 3 td's). With these two properties set, the table cells will be equal in size.

Refer to the demo.

CSS3 transitions inside jQuery .css()

Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.

Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.

JS Fiddle Live Demo

Javascript:

$("#startTransition").on("click", function()
{

    if( $(".boxOne").is(":visible")) 
    {
        $(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
        $(".boxTwo").css({ x: '100%' });
        $(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
        return;        
    }

    $(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
    $(".boxOne").css({ x: '100%' });
    $(".boxOne").show().transition({ x: '0%', opacity: 1.0 });

});

Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.

Python ImportError: No module named wx

Make sure you choose the right project intepreter in the compiler. I used the Pycharm, and I encountered the same problem. And it was solved by choose the right intepreter. Thisvideo may help you.

How to run a script file remotely using SSH

I don't know if it's possible to run it just like that.

I usually first copy it with scp and then log in to run it.

scp foo.sh user@host:~
ssh user@host
./foo.sh

WebSocket with SSL

To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.

for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.

In firefox, this can be done from 'about:preferences' and searching for 'Certificates'

Test if a vector contains a given element

The any() function makes for readable code

> w <- c(1,2,3)
> any(w==1)
[1] TRUE

> v <- c('a','b','c')
> any(v=='b')
[1] TRUE

> any(v=='f')
[1] FALSE

How to search in an array with preg_match?

$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

Output

Array
(
    [1] => say hello
    [2] => hello stackoverflow
    [3] => hello world
)

What is the proper use of an EventEmitter?

There is no: nono and no: yesyes. The truth is in the middle And no reasons to be scared because of the next version of Angular.

From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.

I know..Maybe I'm a bit an old fashioned developer. But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.

Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly. You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.

How to get the new value of an HTML input after a keypress has modified it?

Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:

function showMe(e) {
// i am spammy!
  alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />