Programs & Examples On #Getlatest

Why doesn't TFS get latest get the latest?

"Get latest version" by default will only download the files that have changed on the server since the last time you ran "Get latest version". TFS keeps track of the files you download so it doesn't spend time downloading the same version of the files again. If you are modifying the files outside of Visual Studio, this can cause the consistency problems it sounds like you are seeing.

How to get the latest tag name in current branch in Git?

Not much mention of unannotated tags vs annotated ones here. 'describe' works on annotated tags and ignores unannotated ones.

This is ugly but does the job requested and it will not find any tags on other branches (and not on the one specified in the command: master in the example below)

The filtering should prob be optimized (consolidated), but again, this seems to the the job.

git log  --decorate --tags master |grep '^commit'|grep 'tag:.*)$'|awk '{print $NF}'|sed 's/)$//'|head -n 1

Critiques welcome as I am going now to put this to use :)

Can anyone recommend a simple Java web-app framework?

Apache Wicket, Liftweb) require so much set-up, configuration

I disagree, I use Wicket for all my projects and never looked back! it doesn't take much to set up, not even an hour to set up a full environment to work with Wicket..

Checkout old commit and make it a new commit

This is exactly what I wanted to do. I was not sure of the previous command git cherry-pick C, it sounds nice but it seems you do this to get changes from another branch but not on same branch, has anyone tried it?

So I did something else which also worked : I got the files I wanted back from the old commit file by file

git checkout <commit-hash> <filename>

ex : git checkout 08a6497b76ad098a5f7eda3e4ec89e8032a4da51 file.css

-> this takes the files as they were from the old commit

Then I did my changes. And I committed again.

git status (to check which files were modified)
git diff (to check the changes you made)
git add .
git commit -m "my message"

I checked my history with git log, and I still have my history along with my new changes made from the old files. And I could push too.

Note that to go back to the state you want you need to put the hash of the commit before the unwanted changes. Also make sure you don't have uncommitted changes before you do that.

How do I use dataReceived event of the SerialPort Port Object in C#?

I was having the very same problem with a modem that had previously worked and then one day just stopped raising the DataReceived event.

The solution in my case, very randomly, was to enable RTS e.g.

sp.RtsEnable = true;

No idea why that worked on this particular bit of kit (not a comms man at all really), nor why it had worked and then stopped but it may help somebody else one day so just posting it just in case...

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Chrome

This can be achieved by three different approaches (see my blog article here for more details):

  • Search in Elements panel like below
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not really necessary in most of the cases, could be an overkill)

Here is how you search XPath in Elements panel:

  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.

enter image description here

Firefox (since version 75)

Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.

Firefox (prior version 75)

  1. Either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
    or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut.
  2. In the command line at the bottom use the following:

    • $(): Returns the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

    • $$(): Returns an array of DOM nodes that match. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.

    • $x(): Evaluates an XPath expression and returns an array of matching nodes.


Firefox (prior version 49)

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate

enter image description here

Name node is in safe mode. Not able to leave

try this, it will work

sudo -u hdfs hdfs dfsadmin -safemode leave

subquery in codeigniter active record

The functions _compile_select() and _reset_select() are deprecated.
Instead use get_compiled_select():

#Create where clause
$this->db->select('id_cer');
$this->db->from('revokace');
$where_clause = $this->db->get_compiled_select();

#Create main query
$this->db->select('*');
$this->db->from('certs');
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);

How to handle screen orientation change when progress dialog and background thread active?

These days there is a much more distinct way to handle these types of issues. The typical approach is:

1. Ensure your data is properly seperated from the UI:

Anything that is a background process should be in a retained Fragment (set this with Fragment.setRetainInstance(). This becomes your 'persistent data storage' where anything data based that you would like retained is kept. After the orientation change event, this Fragment will still be accessible in its original state through a FragmentManager.findFragmentByTag() call (when you create it you should give it a tag not an ID as it is not attached to a View).

See the Handling Runtime Changes developed guide for information about doing this correctly and why it is the best option.

2. Ensure you are interfacing correctly and safely between the background processs and your UI:

You must reverse your linking process. At the moment your background process attaches itself to a View - instead your View should be attaching itself to the background process. It makes more sense right? The View's action is dependent on the background process, whereas the background process is not dependent on the View.This means changing the link to a standard Listener interface. Say your process (whatever class it is - whether it is an AsyncTask, Runnable or whatever) defines a OnProcessFinishedListener, when the process is done it should call that listener if it exists.

This answer is a nice concise description of how to do custom listeners.

3. Link your UI into the data process whenever the UI is created (including orientation changes):

Now you must worry about interfacing the background task with whatever your current View structure is. If you are handling your orientation changes properly (not the configChanges hack people always recommend), then your Dialog will be recreated by the system. This is important, it means that on the orientation change, all your Dialog's lifecycle methods are recalled. So in any of these methods (onCreateDialog is usually a good place), you could do a call like the following:

DataFragment f = getActivity().getFragmentManager().findFragmentByTag("BACKGROUND_TAG");
if (f != null) {
    f.mBackgroundProcess.setOnProcessFinishedListener(new OnProcessFinishedListener() {
        public void onProcessFinished() {
            dismiss();
        }
    });
 }

See the Fragment lifecycle for deciding where setting the listener best fits in your individual implementation.

This is a general approach to providing a robust and complete solution to the generic problem asked in this question. There is probably a few minor pieces missing in this answer depending on your individual scenario, but this is generally the most correct approach for properly handling orientation change events.

Cygwin Make bash command not found

Follow these steps:

  1. Go to the installer again
  2. Do the initial setup.
  3. Under library - go to devel.
  4. under devel scroll and find make.
  5. install all of library with name make.
  6. click next, will take some time to install.
  7. this will solve the problem.

Subset a dataframe by multiple factor levels

Try this:

> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
    Code Value
1      A     1
2      B     2
1.1    A     1
1.2    A     1

MySQL parameterized queries

Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.

Incorrect (with security issues)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))

Correct (with escaping)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite).

How to embed fonts in CSS?

Go through http://www.w3.org/TR/css3-fonts/

Try this:

  @font-face {
        font-family: 'EntezareZohoor2';
        src: url('EntezareZohoor2.eot');
        src: local('EntezareZohoor2'), local('EntezareZohoor2'), url('EntezareZohoor2.ttf') format('svg');
       font-weight: normal;
       font-style: normal;
    }

How to lock specific cells but allow filtering and sorting

I had a simular problem. I wanted the user to be able to filter "Table3" in a protected worksheet. But the user is not able to edit the table. I accomplished above, using the vba code below:

Range("Table3").Select
Selection.Locked = True
Selection.FormulaHidden = False 
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
    , allowfiltering:=True

In the following code I filtered the code using VBA:

Range("Table3[[#Headers],[Aantal4]]").Select
ActiveSheet.ListObjects("Table3").Range.AutoFilter Field:=8, Criteria1:= _
    Array("1", "12", "2", "24", "4", "6"), Operator:=xlFilterValues

How can I check if a file exists in Perl?

#!/usr/bin/perl -w

$fileToLocate = '/whatever/path/for/file/you/are/searching/MyFile.txt';
if (-e $fileToLocate) {
    print "File is present";
}

Disable Input fields in reactive form

A more general approach would be.

// Variable/Flag declare
public formDisabled = false;

// Form init
this.form = new FormGroup({
  name: new FormControl({value: '', disabled: this.formDisabled}, 
    Validators.required),
 });

// Enable/disable form control
public toggleFormState() {
    this.formDisabled = !this.formDisabled;
    const state = this.formDisabled ? 'disable' : 'enable';

    Object.keys(this.form.controls).forEach((controlName) => {
        this.form.controls[controlName][state](); // disables/enables each form control based on 'this.formDisabled'
    });
}

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

Why write <script type="text/javascript"> when the mime type is set by the server?

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

He also says:

W3C did not adopt the language attribute, favoring instead a type attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes "text/javascript" or "application/ecmascript" or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write <script>. It is smallest, and it works on the most browsers.

For entertainment purposes only, I tried out the following five scripts

  <script type="application/ecmascript">alert("1");</script>
  <script type="text/javascript">alert("2");</script>
  <script type="baloney">alert("3");</script>
  <script type="">alert("4");</script>
  <script >alert("5");</script>

On Chrome, all but script 3 (type="baloney") worked. IE8 did not run script 1 (type="application/ecmascript") or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type attribute, but that it you use it you better use a legal (browser dependent) value.

How to clear a notification in Android

I believe the most RECENT and UPDATED for AndroidX and backward compatibility. The best way of doing (Kotlin and Java) this should be done as:

NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)

Or to cancel all notifications is:

NotificationManagerCompat.from(context).cancelAll()

Made for AndroidX or Support Libraries.

Access is denied when attaching a database

Every time I have run into this issue was when attempting to attach a database that is in a different directory from the default database directory that is setup in SQL server.

I would highly recommend that instead of jacking with permissions on various directories and accounts that you simply move your data file into the directory that sql server expects to find it.

What is a smart pointer and when should I use one?

The existing answers are good but don't cover what to do when a smart pointer is not the (complete) answer to the problem you are trying to solve.

Among other things (explained well in other answers) using a smart pointer is a possible solution to How do we use a abstract class as a function return type? which has been marked as a duplicate of this question. However, the first question to ask if tempted to specify an abstract (or in fact, any) base class as a return type in C++ is "what do you really mean?". There is a good discussion (with further references) of idiomatic object oriented programming in C++ (and how this is different to other languages) in the documentation of the boost pointer container library. In summary, in C++ you have to think about ownership. Which smart pointers help you with, but are not the only solution, or always a complete solution (they don't give you polymorphic copy) and are not always a solution you want to expose in your interface (and a function return sounds an awful lot like an interface). It might be sufficient to return a reference, for example. But in all of these cases (smart pointer, pointer container or simply returning a reference) you have changed the return from a value to some form of reference. If you really needed copy you may need to add more boilerplate "idiom" or move beyond idiomatic (or otherwise) OOP in C++ to more generic polymorphism using libraries like Adobe Poly or Boost.TypeErasure.

An error has occured. Please see log file - eclipse juno

Here's what I did to solve this:

  • I removed workspace/.metadata
  • run eclipse as an administrator.

SQL GROUP BY CASE statement with aggregate function

While Shannon's answer is technically correct, it looks like overkill.

The simple solution is that you need to put your summation outside of the case statement. This should do the trick:

sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product

Basically, your old code tells SQL to execute the sum(X*Y) for each line individually (leaving each line with its own answer that can't be grouped).

The code line I have written takes the sum product, which is what you want.

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

Edit and replay XHR chrome/firefox etc?

For Firefox the problem solved itself. It has the "Edit and Resend" feature implemented.

For Chrome Tamper extension seems to do the trick.

What is the difference between <section> and <div>?

<div> Vs <Section>

Round 1

<div>: The HTML element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as <article> or <nav>) is appropriate.

<section>: The HTML Section element (<section>) represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading.


Round 2

<div>: Browser Support enter image description here

<section>: Browser Support

The numbers in the table specifies the first browser version that fully supports the element. enter image description here

In that vein, a div is relevant only from a pure CSS or DOM perspective, whereas a section is relevant also for semantics and, in a near future, for indexing by search engines.

Building executable jar with maven?

The answer of Pascal Thivent helped me out, too. But if you manage your plugins within the <pluginManagement>element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>


    <build>
        <pluginManagement>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>main.App</mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                    <executions>
                        <execution>
                            <id>make-assembly</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

            </plugins>

        </pluginManagement>

        <plugins> <!-- did NOT work without this  -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
            </plugin>
        </plugins>

    </build>


    <dependencies>
       <!--  dependencies commented out to shorten example -->
    </dependencies>

</project>

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

Word count from a txt file program

you can do this:

file= open(r'D:\\zzzz\\names2.txt')
file_split=set(file.read().split())
print(len(file_split))

Rearrange columns using cut

You may also combine cut and paste:

paste <(cut -f2 file.txt) <(cut -f1 file.txt)

via comments: It's possible to avoid bashisms and remove one instance of cut by doing:

paste file.txt file.txt | cut -f2,3

GLYPHICONS - bootstrap icon font hex value

The hex values are on the mainpage of http://glyphicons.com/ in the tooltips of the specific icon.

mean() warning: argument is not numeric or logical: returning NA

From R 3.0.0 onwards mean(<data.frame>) is defunct (and passing a data.frame to mean will give the error you state)

A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".

In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following

lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)

Java Command line arguments

Your main method has a String[] argument. That contain the arguments that have been passed to your applications (it's often called args, but that's not a requirement).

Autowiring two beans implementing same interface - how to set default bean to autowire?

The use of @Qualifier will solve the issue.
Explained as below example : 
public interface PersonType {} // MasterInterface

@Component(value="1.2") 
public class Person implements  PersonType { //Bean implementing the interface
@Qualifier("1.2")
    public void setPerson(PersonType person) {
        this.person = person;
    }
}

@Component(value="1.5")
public class NewPerson implements  PersonType { 
@Qualifier("1.5")
    public void setNewPerson(PersonType newPerson) {
        this.newPerson = newPerson;
    }
}

Now get the application context object in any component class :

Object obj= BeanFactoryAnnotationUtils.qualifiedBeanOfType((ctx).getAutowireCapableBeanFactory(), PersonType.class, type);//type is the qualifier id

you can the object of class of which qualifier id is passed.

How to Deserialize XML document

Here's a working version. I changed the XmlElementAttribute labels to XmlElement because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the reader.ReadToEnd(); (that function reads the whole stream and returns a string, so the Deserialize() function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :).

Here are the classes:

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }

    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }

    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

The Deserialize function:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays):

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

Maven Java EE Configuration Marker with Java Server Faces 1.2

You should check your project facets in the project configuration. This is where you may uncheck the JSF dependency.

enter image description here

Best way to get identity of inserted row?

ALWAYS use scope_identity(), there's NEVER a need for anything else.

How to add background-image using ngStyle (angular2)?

Also you can try this:

[style.background-image]="'url(' + photo + ')'"

How do I format a string using a dictionary in python-3.x?

Most answers formatted only the values of the dict.

If you want to also format the key into the string you can use dict.items():

geopoint = {'latitude':41.123,'longitude':71.091}
print("{} {}".format(*geopoint.items()))

Output:

('latitude', 41.123) ('longitude', 71.091)

If you want to format in an arbitry way, that is, not showing the key-values like tuples:

from functools import reduce
print("{} is {} and {} is {}".format(*reduce((lambda x, y: x + y), [list(item) for item in geopoint.items()])))

Output:

latitude is 41.123 and longitude is 71.091

Text on image mouseover?

This is using the :hover pseudoelement in CSS3.

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper .text {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

#wrapper:hover .text {
visibility:visible;
}

?Demo HERE.


This instead is a way of achieving the same result by using jquery:

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper p {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

jquery code:

$('.hover').mouseover(function() {
  $('.text').css("visibility","visible");
});

$('.hover').mouseout(function() {
  $('.text').css("visibility","hidden");
});

You can put the jquery code where you want, in the body of the HTML page, then you need to include the jquery library in the head like this:

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

You can see the demo HERE.

When you want to use it on your website, just change the <img src /> value and you can add multiple images and captions, just copy the format i used: insert image with class="hover" and p with class="text"

Convert byte slice to io.Reader

To get a type that implements io.Reader from a []byte slice, you can use bytes.NewReader in the bytes package:

r := bytes.NewReader(byteData)

This will return a value of type bytes.Reader which implements the io.Reader (and io.ReadSeeker) interface.

Don't worry about them not being the same "type". io.Reader is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.

Cannot connect to local SQL Server with Management Studio

Open Sql server 2014 Configuration Manager.

Click Sql server services and start the sql server service if it is stopped

Then click Check SQL server Network Configuration for TCP/IP Enabled

then restart the sql server management studio (SSMS) and connect your local database engine

JavaScript: filter() for Objects

How about:

function filterObj(keys, obj) {
  const newObj = {};
  for (let key in obj) {
    if (keys.includes(key)) {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}

Or...

function filterObj(keys, obj) {
  const newObj = {};
  Object.keys(obj).forEach(key => {
    if (keys.includes(key)) {
      newObj[key] = obj[key];
    }
  });
  return newObj;
}

Rails migration for change column

Another way to change data type using migration

step1: You need to remove the faulted data type field name using migration

ex:

rails g migration RemoveFieldNameFromTableName field_name:data_type

Here don't forget to specify data type for your field

Step 2: Now you can add field with correct data type

ex:

rails g migration AddFieldNameToTableName field_name:data_type

That's it, now your table will added with correct data type field, Happy ruby coding!!

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

Got stupid error. So post here, if anyone find it useful

  1. [-\._] - means hyphen, dot and underscore
  2. [\.-_] - means all signs in range from dot to underscore

Take multiple lists into dataframe

@oopsi used pd.concat() but didn't include the column names. You could do the following, which, unlike the first solution in the accepted answer, gives you control over the column order (avoids dicts, which are unordered):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)

s1=pd.Series(lst1,name='lst1Title')
s2=pd.Series(lst2,name='lst2Title')
s3=pd.Series(lst3 ,name='lst3Title')
percentile_list = pd.concat([s1,s2,s3], axis=1)

percentile_list
Out[2]: 
    lst1Title  lst2Title  lst3Title
0           0          0          0
1           1          1          1
2           2          2          2
3           3          3          3
4           4          4          4
5           5          5          5
6           6          6          6
7           7          7          7
8           8          8          8
...

When does Git refresh the list of remote branches?

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

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

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

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

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

How to change onClick handler dynamically?

jQuery:

$('#foo').click(function() { alert('foo'); });

Or if you don't want it to follow the link href:

$('#foo').click(function() { alert('foo'); return false; });

Calling variable defined inside one function from another function

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])
    return word

def anotherFunction():
    for letter in word:             
        print("_",end=" ")

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

This script logs all the file names and ids in the drive:

// Log the name and id of every file in the user's Drive
function listFiles() {
  var files = DriveApp.getFiles();
  while ( files.hasNext() ) {
    var file = files.next();
    Logger.log( file.getName() + ' ' + file.getId() );
  }
}  

Also, the "Files: list" page has a form at the end that lists the metadata of all the files in the drive, that can be used in case you need but a few ids.

How to select all records from one table that do not exist in another table?

Here's what worked best for me.

SELECT *
FROM @T1
EXCEPT
SELECT a.*
FROM @T1 a
JOIN @T2 b ON a.ID = b.ID

This was more than twice as fast as any other method I tried.

How to scale a BufferedImage

scale(..) works a bit differently. You can use bufferedImage.getScaledInstance(..)

Java: How To Call Non Static Method From Main Method?

Please find answer:

public class Customer {

    public static void main(String[] args) {
        Customer customer=new Customer();
        customer.business();
    }

    public void business(){
        System.out.println("Hi Harry");
    }
}

Single vs double quotes in JSON

As said, JSON is not Python syntax. You need to use double quotes in JSON. Its creator is (in-)famous for using strict subsets of allowable syntax to ease programmer cognitive overload.


Below can fail if one of the JSON strings itself contains a single quote as pointed out by @Jiaaro. DO NOT USE. Left here as an example of what does not work.

It is really useful to know that there are no single quotes in a JSON string. Say, you copied and pasted it from a browser console/whatever. Then, you can just type

a = json.loads('very_long_json_string_pasted_here')

This might otherwise break if it used single quotes, too.

Is there a Google Voice API?

I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...

https://bitbucket.org/jitbit/sharpgooglevoice/wiki/Home

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Format numbers in django templates

Well I couldn't find a Django way, but I did find a python way from inside my model:

def format_price(self):
    import locale
    locale.setlocale(locale.LC_ALL, '')
    return locale.format('%d', self.price, True)

Close iOS Keyboard by touching anywhere using Swift

If you have other views that should receive the touch as well you have to set cancelsTouchesInView = false

Like this:

let elsewhereTap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    elsewhereTap.cancelsTouchesInView = false
    self.view.addGestureRecognizer(elsewhereTap)

How to implement zoom effect for image view in android?

Here is one of the most efficient way, it works smoothly:

https://github.com/MikeOrtiz/TouchImageView

Place TouchImageView.java in your project. It can then be used the same as ImageView.

Example:

TouchImageView img = (TouchImageView) findViewById(R.id.img);

If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view.

Example:

    <com.example.touch.TouchImageView
            android:id="@+id/img”
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

How to specify a min but no max decimal using the range data annotation attribute?

It seems there's no choice but to put in the max value manually. I was hoping there was some type of overload where you didn't need to specify one.

[Range(typeof(decimal), "0", "79228162514264337593543950335")]
public decimal Price { get; set; }

Redefine tab as 4 spaces

My basic ~/.vimrc with comment:

set number " show line number                                                                                           
set tabstop=2 " set display width of tab; 1 tab = x space with                                                           
set expandtab " transform tab to x space (x is tabstop)                                                               
set autoindent " auto indent; new line with number of space at the beginning same as previous                                                                      
set shiftwidth=2 " number of space append to lines when type >> 

How to make HTML open a hyperlink in another window or tab?

Since web is evolving quickly, some things changes with time. For security issues, you might want to use the rel="noopener" attribute in conjuncture with your target="_blank".

Like stated in Google Dev Documentation, the other page can access your window object with the window.opener property. Your external link should looks like this now:

<a href="http://www.starfall.com/" target="_blank" rel="noopener">Starfall</a>

Change route params without reloading in Angular 2

Using location.go(url) is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree().

Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute}) but without reloading the component, it can be rewritten as:

const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()

 this.location.go(url);

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

PHP Get name of current directory

$myVar = str_replace('/', '', $_SERVER[REQUEST_URI]);

libs/images/index.php
Result: images

Change Primary Key

You will need to drop and re-create the primary key like this:

alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.

An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):

alter table my_table drop primary key;

When to use <span> instead <p>?

<span> is an inline tag, a <p> is a block tag, used for paragraphs. Browsers will render a blank line below a paragraph, whereas <span>s will render on the same line.

PHP Using RegEx to get substring of a string

$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);

This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

php.net/preg-match

Adding blur effect to background in swift

This worked for me on Swift 5

let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)

Pointer-to-pointer dynamic two-dimensional array

In both cases your inner dimension may be dynamically specified (i.e. taken from a variable), but the difference is in the outer dimension.

This question is basically equivalent to the following:

Is int* x = new int[4]; "better" than int x[4]?

The answer is: "no, unless you need to choose that array dimension dynamically."

jQuery change method on input type="file"

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });

update:

from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

How do I vertically center an H1 in a div?

I've had success putting text within span tags and then setting vertical-align: middle on that span. Don't know how cross-browser compliant this is though, I've only tested it in webkit browsers.

What's the proper way to compare a String to an enum value?

You should declare toString() and valueOf() method in enum.

 import java.io.Serializable;

public enum Gesture implements Serializable {
    ROCK,PAPER,SCISSORS;

    public String toString(){
        switch(this){
        case ROCK :
            return "Rock";
        case PAPER :
            return "Paper";
        case SCISSORS :
            return "Scissors";
        }
        return null;
    }

    public static Gesture valueOf(Class<Gesture> enumType, String value){
        if(value.equalsIgnoreCase(ROCK.toString()))
            return Gesture.ROCK;
        else if(value.equalsIgnoreCase(PAPER.toString()))
            return Gesture.PAPER;
        else if(value.equalsIgnoreCase(SCISSORS.toString()))
            return Gesture.SCISSORS;
        else
            return null;
    }
}

Using SVG as background image

With my solution you're able to get something similar:

svg background image css

Here is bulletproff solution:

Your html: <input class='calendarIcon'/>

Your SVG: i used fa-calendar-alt

fa-calendar-alt

(any IDE may open svg image as shown below)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>

To use it at css background-image you gotta encode the svg to address valid string. I used this tool

As far as you got all stuff you need, you're coming to css

.calendarIcon{
      //your url will be something like this:
      background-image: url("data:image/svg+xml,***<here place encoded svg>***");
      background-repeat: no-repeat;
    }

Note: these styling wont have any effect on encoded svg image

.{
      fill: #f00; //neither this
      background-color: #f00; //nor this
}

because all changes over the image must be applied directly to its svg code

<svg xmlns="" path="" fill="#f00"/></svg>

To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:

.calendarIcon{
      background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
      background-repeat: no-repeat;
      padding-right: calc(1.5em + 0.75rem);
      background-position: center right calc(0.375em + 0.1875rem);
      background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
    }

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

How to connect to a MS Access file (mdb) using C#?

Another simplest way to connect is through an OdbcConnection using App.config file like this

  <appSettings>  
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True"/>
  </appSettings>

MyDB.mdb is my database file and it is present in current primary application folder with main exe file.

if your mdf file has password then use like this

  <appSettings>
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True;Jet OLEDB:Database Password=Admin$@123"/>
  </appSettings>

BarCode Image Generator in Java

I use barbeque , it's great, and supports a very wide range of different barcode formats.
See if you like its API .

Sample API:

public static Barcode createCode128(java.lang.String data)
                             throws BarcodeException

Creates a Code 128 barcode that dynamically switches between character sets to give the smallest possible encoding. This will encode all numeric characters, upper and lower case alpha characters and control characters from the standard ASCII character set. The size of the barcode created will be the smallest possible for the given data, and use of this "optimal" encoding will generally give smaller barcodes than any of the other 3 "vanilla" encodings.

Android WebView Cookie Problem

I've spent the greater half of 3 hours working on a very similar issue. In my case I had a number of calls, that I made to a web service using a DefaulHttpClient and then I wanted to set the session and all other corresponding cookies in my WebView.

I don't know if this will solve your problem, since I don't know what your getCookie() method does, but in my case I actually had to call.

cookieManager.removeSessionCookie();

First to remove the session cookie and then re-add it. I was finding that when I tried to set the JSESSIONID cookie without first removing it, the value I wanted to set it to wasn't being save. Not sure if this will help you particular issue, but thought I'd share what I had found.

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

JAVA_HOME is set to an invalid directory:

JAVA_HOME should point to the home jdk directory, and not to jdk/bin directory.

You need to set the JAVA_HOME like this:

JAVA_HOME="C:\Program Files\Java\jdk1.8.0_131"

Double % formatting question for printf in Java

Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

System.out.printf("%s \r\n",String.valueOf(d));

or

System.out.printf("%s \r\n",Double.toString(d));

This is what println do by default:

System.out.println(d) 

(and terminates the line)

HTML Entity Decode

Injecting untrusted HTML into the page is dangerous as explained in How to decode HTML entities using jQuery?.

One alternative is to use a JavaScript-only implementation of PHP's html_entity_decode (from http://phpjs.org/functions/html_entity_decode:424). The example would then be something like:

var varTitle = html_entity_decode("Chris&apos; corner");

SimpleXml to string

You can use the SimpleXMLElement::asXML() method to accomplish this:

$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);

// The entire XML tree as a string:
// "<element><child>Hello World</child></element>"
$xml->asXML();

// Just the child node as a string:
// "<child>Hello World</child>"
$xml->child->asXML();

check the null terminating character in char*

You have used '/0' instead of '\0'. This is incorrect: the '\0' is a null character, while '/0' is a multicharacter literal.

Moreover, in C it is OK to skip a zero in your condition:

while (*(forward++)) {
    ...
}

is a valid way to check character, integer, pointer, etc. for being zero.

Same font except its weight seems different on different browsers

Try -webkit-font-smoothing: subpixel-antialiased;

How to specify the port an ASP.NET Core application is hosted on?

In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:

  • Using command line arguments, by starting your .NET application with --urls=[url]:
dotnet run --urls=http://localhost:5001/
  • Using appsettings.json, by adding a Urls node:
{
  "Urls": "http://localhost:5001"
}
  • Using environment variables, with ASPNETCORE_URLS=http://localhost:5001/.
  • Using UseUrls(), if you prefer doing it programmatically:
public static class Program
{
    public static void Main(string[] args) =>
        CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup<Startup>();
                builder.UseUrls("http://localhost:5001/");
            });
}

Or, if you're still using the web host builder instead of the generic host builder:

public class Program
{
    public static void Main(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://localhost:5001/")
            .Build()
            .Run();
}

How to shut down the computer from C#

There is no .net native method for shutting off the computer. You need to P/Invoke the ExitWindows or ExitWindowsEx API call.

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Next to being in the wrong directory I just tripped about another variant:

I had a File.open(my_file).each {|line| puts line} exploding but there was something by that name in the directory I was working in (ls in the command line showed the name). I checked with a File.exists?(my_file) which strangely returned false. Explanation: my_file was a symlink which target didn't exist anymore! Since File.exists? will follow a symlink it will say false though the link is still there.

How to display scroll bar onto a html table

Something like this?

http://jsfiddle.net/TweNm/

The idea is to wrap the <table> in a non-statically positioned <div> which has an overflow:auto CSS property. Then position the elements in the <thead> absolutely.

_x000D_
_x000D_
#table-wrapper {_x000D_
  position:relative;_x000D_
}_x000D_
#table-scroll {_x000D_
  height:150px;_x000D_
  overflow:auto;  _x000D_
  margin-top:20px;_x000D_
}_x000D_
#table-wrapper table {_x000D_
  width:100%;_x000D_
_x000D_
}_x000D_
#table-wrapper table * {_x000D_
  background:yellow;_x000D_
  color:black;_x000D_
}_x000D_
#table-wrapper table thead th .text {_x000D_
  position:absolute;   _x000D_
  top:-20px;_x000D_
  z-index:2;_x000D_
  height:20px;_x000D_
  width:35%;_x000D_
  border:1px solid red;_x000D_
}
_x000D_
<div id="table-wrapper">_x000D_
  <div id="table-scroll">_x000D_
    <table>_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th><span class="text">A</span></th>_x000D_
                <th><span class="text">B</span></th>_x000D_
                <th><span class="text">C</span></th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
          <tr> <td>1, 0</td> <td>2, 0</td> <td>3, 0</td> </tr>_x000D_
          <tr> <td>1, 1</td> <td>2, 1</td> <td>3, 1</td> </tr>_x000D_
          <tr> <td>1, 2</td> <td>2, 2</td> <td>3, 2</td> </tr>_x000D_
          <tr> <td>1, 3</td> <td>2, 3</td> <td>3, 3</td> </tr>_x000D_
          <tr> <td>1, 4</td> <td>2, 4</td> <td>3, 4</td> </tr>_x000D_
          <tr> <td>1, 5</td> <td>2, 5</td> <td>3, 5</td> </tr>_x000D_
          <tr> <td>1, 6</td> <td>2, 6</td> <td>3, 6</td> </tr>_x000D_
          <tr> <td>1, 7</td> <td>2, 7</td> <td>3, 7</td> </tr>_x000D_
          <tr> <td>1, 8</td> <td>2, 8</td> <td>3, 8</td> </tr>_x000D_
          <tr> <td>1, 9</td> <td>2, 9</td> <td>3, 9</td> </tr>_x000D_
          <tr> <td>1, 10</td> <td>2, 10</td> <td>3, 10</td> </tr>_x000D_
          <!-- etc... -->_x000D_
          <tr> <td>1, 99</td> <td>2, 99</td> <td>3, 99</td> </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android difference between Two Dates

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Usage:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Output:

dateDifference: 2

Kotlin Version:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
    return try {
        DurationUnit.DAYS.convert(
            format.parse(newDate).time - format.parse(oldDate).time,
            DurationUnit.MILLISECONDS
        )
    } catch (e: Exception) {
        e.printStackTrace()
        0
    }
}

Javascript array value is undefined ... how do I test for that

There are more (many) ways to Rome:

//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null

cheers!

boolean in an if statement

This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax whatever == TRUE would ever confuse anyone who knew what they were doing.

WPF Binding to parent DataContext

Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).

If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel

public class ThisViewModel : ViewModelBase
{
    TypeOfAncestorViewModel Parent { get; set; }
}

and bind against that directly instead.

<TextBox Text="{Binding Parent}" />

How to change an element's title attribute using jQuery

Another option, if you prefer, would be to get the DOM element from the jQuery object and use standard DOM accessors on it:

$("#myElement")[0].title = "new title value";

The "jQuery way", as mentioned by others, is to use the attr() method. See the API documentation for attr() here.

Send a SMS via intent

Add try-catch otherwise phones without sim will crash.

void sentMessage(String msg) {
    try {
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.setType("vnd.android-dir/mms-sms");
        smsIntent.putExtra("sms_body", msg);
        startActivity(smsIntent);
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this, "No SIM Found", Toast.LENGTH_LONG).show();
    }
}

How can I mix LaTeX in with Markdown?

kramdown does exactly what you describe:

https://kramdown.gettalong.org/syntax.html#math-blocks

And it's way more reliable and well-defined than Markdown.

Simple parse JSON from URL on Android and display in listview

JSONObject(html).getString("name");

How to get the html String: Make an HTTP request with android

Controller not a function, got undefined, while defining controllers globally

With Angular 1.3+ you can no longer use global controller declaration on the global scope (Without explicit registration). You would need to register the controller using module.controller syntax.

Example:-

angular.module('app', [])
    .controller('ContactController', ['$scope', function ContactController($scope) {
        $scope.contacts = ["[email protected]", "[email protected]"];

        $scope.add = function() {
            $scope.contacts.push($scope.newcontact);
            $scope.newcontact = "";

        };
    }]);

or

function ContactController($scope) {
    $scope.contacts = ["[email protected]", "[email protected]"];

    $scope.add = function() {
        $scope.contacts.push($scope.newcontact);
        $scope.newcontact = "";
    };
}
ContactController.$inject = ['$scope'];
angular.module('app', []).controller('ContactController', ContactController);

It is a breaking change but it can be turned off to use globals by using allowGlobals.

Example:-

angular.module('app')
    .config(['$controllerProvider', function($controllerProvider) {
        $controllerProvider.allowGlobals();
    }]);

Here is the comment from Angular source:-

  • check if a controller with given name is registered via $controllerProvider
  • check if evaluating the string on the current scope returns a constructor
  • if $controllerProvider#allowGlobals, check window[constructor] on the global window object (not recommended)
 .....

expression = controllers.hasOwnProperty(constructor)
            ? controllers[constructor]
            : getter(locals.$scope, constructor, true) ||
                (globals ? getter($window, constructor, true) : undefined);

Some additional checks:-

  • Do Make sure to put the appname in ng-app directive on your angular root element (eg:- html) as well. Example:- ng-app="myApp"

  • If everything is fine and you are still getting the issue do remember to make sure you have the right file included in the scripts.

  • You have not defined the same module twice in different places which results in any entities defined previously on the same module to be cleared out, Example angular.module('app',[]).controller(.. and again in another place angular.module('app',[]).service(.. (with both the scripts included of course) can cause the previously registered controller on the module app to be cleared out with the second recreation of module.

how can the textbox width be reduced?

rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.

http://htmldog.com/reference/htmltags/textarea/

Failed to execute 'createObjectURL' on 'URL':

UPDATE

Consider avoiding createObjectURL() method, while browsers are disabling support for it. Just attach MediaStream object directly to the srcObject property of HTMLMediaElement e.g. <video> element.

const mediaStream = new MediaStream();
const video = document.getElementById('video-player');
video.srcObject = mediaStream;

However, if you need to work with MediaSource, Blob or File, you have to create a URL with URL.createObjectURL() and assign it to HTMLMediaElement.src.

Read more details here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject


Older Answer

I experienced same error, when I passed to createObjectURL raw data:

window.URL.createObjectURL(data)

It has to be Blob, File or MediaSource object, not data itself. This worked for me:

var binaryData = [];
binaryData.push(data);
window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))

Check also the MDN for more info: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

How do I apply the for-each loop to every character in a String?

String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}

 

How do I install imagemagick with homebrew?

You could try:

brew update && brew install imagemagick

How to read a text file into a list or an array with Python

You will have to split your string into a list of values using split()

So,

lines = text_file.read().split(',')

EDIT: I didn't realise there would be so much traction to this. Here's a more idiomatic approach.

import csv
with open('filename.csv', 'r') as fd:
    reader = csv.reader(fd)
    for row in reader:
        # do something

Convert to date format dd/mm/yyyy

Try this:

$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");

Stuck at ".android/repositories.cfg could not be loaded."

Create the file! try:

mkdir -p .android && touch ~/.android/repositories.cfg

unsigned int vs. size_t

In short, size_t is never negative, and it maximizes performance because it's typedef'd to be the unsigned integer type that's big enough -- but not too big -- to represent the size of the largest possible object on the target platform.

Sizes should never be negative, and indeed size_t is an unsigned type. Also, because size_t is unsigned, you can store numbers that are roughly twice as big as in the corresponding signed type, because we can use the sign bit to represent magnitude, like all the other bits in the unsigned integer. When we gain one more bit, we are multiplying the range of numbers we can represents by a factor of about two.

So, you ask, why not just use an unsigned int? It may not be able to hold big enough numbers. In an implementation where unsigned int is 32 bits, the biggest number it can represent is 4294967295. Some processors, such as the IP16L32, can copy objects larger than 4294967295 bytes.

So, you ask, why not use an unsigned long int? It exacts a performance toll on some platforms. Standard C requires that a long occupy at least 32 bits. An IP16L32 platform implements each 32-bit long as a pair of 16-bit words. Almost all 32-bit operators on these platforms require two instructions, if not more, because they work with the 32 bits in two 16-bit chunks. For example, moving a 32-bit long usually requires two machine instructions -- one to move each 16-bit chunk.

Using size_t avoids this performance toll. According to this fantastic article, "Type size_t is a typedef that's an alias for some unsigned integer type, typically unsigned int or unsigned long, but possibly even unsigned long long. Each Standard C implementation is supposed to choose the unsigned integer that's big enough--but no bigger than needed--to represent the size of the largest possible object on the target platform."

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

For Mac sudo chmod 755 /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php Worked for me

Is there a cross-domain iframe height auto-resizer that works?

Here is an alternative implementation.

enter image description here

Basically if you able to edit page at other domain you can place another iframe page that belongs to your server which saving height to cookies. With an interval read cookies when it is updated, update the height of the iframe. That is all.

Edit: 2019 December

The solution above basically uses another iframe inside of an iframe 3rd iframe is belongs to the top page domain, which you call this page with a query string that saves size value to a cookie, outer page checks this query with some interval. But it is not a good solution so you should follow this one:

In Top page :

window.addEventListener("message", (m)=>{iframeResizingFunction(m)});

Here you can check m.origin to see where is it comes from.

In frame page:

window.parent.postMessage({ width: 640, height:480 }, "*")

Although, please don't forget this is not so secure way. To make it secure update * value (targetOrigin) with your desired value. Please follow documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

OpenCV - Apply mask to a color image

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here

How to get the last N records in mongodb?

 db.collection.find().sort({$natural: -1 }).limit(5)

How to import existing *.sql files in PostgreSQL 8.4?

Be careful with "/" and "\". Even on Windows the command should be in the form:

\i c:/1.sql

Matplotlib transparent line plots

It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.

How to get source code of a Windows executable?

For Any *.Exe file written in any language .You can view the source code with hiew (otherwise Hackers view). You can download it at www.hiew.ru. It will be the demo version but still can view the code.

After this follow these steps:

  1. Press alt+f2 to navigate to the file.

  2. Press enter to see its assembly / c++ code.

how to get current datetime in SQL?

I want my datetime, and I want it now()!

For MySQL, anyway.

Why am I getting string does not name a type Error?

string does not name a type. The class in the string header is called std::string.

Please do not put using namespace std in a header file, it pollutes the global namespace for all users of that header. See also "Why is 'using namespace std;' considered a bad practice in C++?"

Your class should look like this:

#include <string>

class Game
{
    private:
        std::string white;
        std::string black;
        std::string title;
    public:
        Game(std::istream&, std::ostream&);
        void display(colour, short);
};

Get JSF managed bean by name in any Servlet related class

I use this:

public static <T> T getBean(Class<T> clazz) {
    try {
        String beanName = getBeanName(clazz);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return facesContext.getApplication().evaluateExpressionGet(facesContext, "#{" + beanName + "}", clazz);
    //return facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, nomeBean);
    } catch (Exception ex) {
        return null;
    }
}

public static <T> String getBeanName(Class<T> clazz) {
    ManagedBean managedBean = clazz.getAnnotation(ManagedBean.class);
    String beanName = managedBean.name();

    if (StringHelper.isNullOrEmpty(beanName)) {
        beanName = clazz.getSimpleName();
        beanName = Character.toLowerCase(beanName.charAt(0)) + beanName.substring(1);
    }

    return beanName;
}

And then call:

MyManageBean bean = getBean(MyManageBean.class);

This way you can refactor your code and track usages without problems.

Single vs Double quotes (' vs ")

Using double quotes for HTML

i.e.

<div class="colorFont"></div>

Using single quotes for JavaScript

i.e.

$('#container').addClass('colorFont');
$('<div class="colorFont2></div>');

Create file path from variables

You want the path.join() function from os.path.

>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
    os.makedirs (final_path)

Negation in Python

Combining the input from everyone else (use not, no parens, use os.mkdir) you'd get...

special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
    os.mkdir(special_path_for_john)

Java Refuses to Start - Could not reserve enough space for object heap

I recently faced this issue. I have 3 java applications that start with 1024m or 1280m heap size. Java is looking at the available space in swap, and if there is not enough memory available, the jvm exits.

To resolve the issue, I had to end several programs that had a large amount of virtual memory allocated.

I was running on x86-64 linux with a 64-bit jvm.

How to get all Errors from ASP.Net MVC modelState?

_x000D_
_x000D_
<div class="text-danger" style="direction:rtl" asp-validation-summary="All"></div>
_x000D_
_x000D_
_x000D_

simply use asp-validation-summary Tag Helper

if statements matching multiple values

How about:

if (new[] {1, 2}.Contains(value))

It's a hack though :)

Or if you don't mind creating your own extension method, you can create the following:

public static bool In<T>(this T obj, params T[] args)
{
    return args.Contains(obj);
}

And you can use it like this:

if (1.In(1, 2))

:)

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

If you're using Laravel, do

composer update

This should be work.

How can I do width = 100% - 100px in CSS?

Could you do:

margin-right: 50px;
margin-left: 50px;

Edit: My solution is wrong. The solution posted by Aric TenEyck suggesting using a div with width 100% and then nesting another div using the margins seems more correct.

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

You need to link the with the -lm linker option

You need to compile as

gcc test.c  -o test -lm

gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l linker option followed by the library name m thus -lm.

oracle - what statements need to be committed?

DML have to be committed or rollbacked. DDL cannot.

http://www.orafaq.com/faq/what_are_the_difference_between_ddl_dml_and_dcl_commands

You can switch auto-commit on and that's again only for DML. DDL are never part of transactions and therefore there is nothing like an explicit commit/rollback.

truncate is DDL and therefore commited implicitly.

Edit
I've to say sorry. Like @DCookie and @APC stated in the comments there exist sth like implicit commits for DDL. See here for a question about that on Ask Tom. This is in contrast to what I've learned and I am still a bit curious about.

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

Hashing a dictionary?

I do it like this:

hash(str(my_dict))

How do I do a not equal in Django queryset filtering?

While you can filter Models with =, __gt, __gte, __lt, __lte, you cannot use ne or !=. However, you can achieve better filtering using the Q object.

You can avoid chaining QuerySet.filter() and QuerySet.exclude(), and use this:

from django.db.models import Q
object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted')

Efficient way to rotate a list in python

What about just using pop(0)?

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

Running multiple commands in one line in shell

Try this..

cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple

Find the similarity metric between two strings

There is a built in.

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

Using it:

>>> similar("Apple","Appel")
0.8
>>> similar("Apple","Mango")
0.0

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

You have to change delimiter before using triggers, stored procedures and so on.

delimiter //
create procedure ProG() 
begin 
SELECT * FROM hs_hr_employee_leave_quota;
end;//
delimiter ;

How do I get AWS_ACCESS_KEY_ID for Amazon?

Amazon changes the admin console from time to time, hence the previous answers above are irrelevant in 2020.

The way to get the secret access key (Oct.2020) is:

  1. go to IAM console: https://console.aws.amazon.com/iam
  2. click on "Users". (see image) enter image description here
  3. go to the user you need his access key. enter image description here

As i see the answers above, I can assume my answer will become irrelevant in a year max :-)

HTH

Getting Checkbox Value in ASP.NET MVC 4

This has been a major pain and feels like it should be simpler. Here's my setup and solution.

I'm using the following HTML helper:

@Html.CheckBoxFor(model => model.ActiveFlag)

Then, in the controller, I am checking the form collection and processing accordingly:

bool activeFlag = collection["ActiveFlag"] == "false" ? false : true;
[modelObject].ActiveFlag = activeFlag;

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

Difference between DOMContentLoaded and load events

See the difference yourself:

DEMO

From Microsoft IE

The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images. DOMContentLoaded is a great event to use to hookup UI functionality to complex web pages.

From Mozilla Developer Network

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

Get the data received in a Flask request

Here's an example of parsing posted JSON data and echoing it back.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/foo', methods=['POST']) 
def foo():
    data = request.json
    return jsonify(data)

To post JSON with curl:

curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo

Or to use Postman:

using postman to post JSON

Example of Named Pipes

You can actually write to a named pipe using its name, btw.

Open a command shell as Administrator to get around the default "Access is denied" error:

echo Hello > \\.\pipe\PipeName

Auto-center map with multiple markers in Google Maps API v3

I've tryied all answers of this topic, but just this below worked fine on my project.

Angular 7 and AGM Core 1.0.0-beta.7

<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
  <agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
    *ngFor="let localizacao of localizacoesTec">
  </agm-marker>
</agm-map>

The properties [agmFitBounds]="true" at agm-marker and [fitBounds]="true" at agm-map does the job

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Correct way to find max in an Array in Swift

You can use with reduce:

let randomNumbers = [4, 7, 1, 9, 6, 5, 6, 9]
let maxNumber = randomNumbers.reduce(randomNumbers[0]) { $0 > $1 ? $0 : $1 } //result is 9

How can I disable notices and warnings in PHP within the .htaccess file?

I used ini_set('display_errors','off'); and it worked great.

How to redraw DataTable with new data

I was having same issue, and the solution was working but with some alerts and warnings so here is full solution, the key was to check for existing DataTable object or not, if yes just clear the table and add jsonData, if not just create new.

            var table;
            if ($.fn.dataTable.isDataTable('#example')) {
                table = $('#example').DataTable();
                table.clear();
                table.rows.add(jsonData).draw();
            }
            else {
                table = $('#example').DataTable({
                    "data": jsonData,
                    "deferRender": true,
                    "pageLength": 25,
                    "retrieve": true,

Versions

  • JQuery: 3.3.1
  • DataTable: 1.10.20

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

generate random double numbers in c++

This solution requires C++11 (or TR1).

#include <random>

int main()
{
   double lower_bound = 0;
   double upper_bound = 10000;
   std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
   std::default_random_engine re;
   double a_random_double = unif(re);

   return 0;
}

For more details see John D. Cook's "Random number generation using C++ TR1".

See also Stroustrup's "Random number generation".

Only get hash value using md5sum (without filename)

Another way is to do :

md5sum filename |cut -f 1 -d " "

Cut will split line to each space and return only first field.

.bashrc at ssh login

.bashrc is not sourced when you log in using SSH. You need to source it in your .bash_profile like this:

if [ -f ~/.bashrc ]; then
  . ~/.bashrc
fi

How to execute multiple SQL statements from java

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

EXAMPLE:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

Print a file, skipping the first X lines, in Bash

If you want to see the first 10 lines you can use sed as below:

sed -n '1,10 p' myFile.txt

Or if you want to see lines from 20 to 30 you can use:

sed -n '20,30 p' myFile.txt

Extend a java class from one file in another java file

Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them. The closes thing to an include statement java has is 'import'. Since classes are broken up into namespaces like foo.bar.Baz, if you're in the qux package and you want to use the Baz class without having to use its full name of foo.bar.Baz, then you need to use an import statement at the beginning of your java file like so: import foo.bar.Baz

Removing all empty elements from a hash / YAML?

I made a deep_compact method for this that recursively filters out nil records (and optionally, blank records as well):

class Hash
  # Recursively filters out nil (or blank - e.g. "" if exclude_blank: true is passed as an option) records from a Hash
  def deep_compact(options = {})
    inject({}) do |new_hash, (k,v)|
      result = options[:exclude_blank] ? v.blank? : v.nil?
      if !result
        new_value = v.is_a?(Hash) ? v.deep_compact(options).presence : v
        new_hash[k] = new_value if new_value
      end
      new_hash
    end
  end
end

MySQL WHERE: how to write "!=" or "not equals"?

The != operator most certainly does exist! It is an alias for the standard <> operator.

Perhaps your fields are not actually empty strings, but instead NULL?

To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

get unique machine id

The following site uses System.Management to accomplish the same is a very sleek way in a console application

diff current working copy of a file with another branch's committed copy

To see local changes compare to your current branch

git diff .

To see local changed compare to any other existing branch

git diff <branch-name> .

To see changes of a particular file

git diff <branch-name> -- <file-path>

Make sure you run git fetch at the beginning.

How to get JSON Key and Value?

First, I see you're using an explicit $.parseJSON(). If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.

To iterate through the first item in the array you've got there, use code like this:

var firstItem = response.d[0];

for(key in firstItem) {
  console.log(key + ':' + firstItem[key]);
}

If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d and then use this code inside that outer loop.

Android global variable

I checked for similar answer, but those given here don't fit my needs. I find something that, from my point of view, is what you're looking for. The only possible black point is a security matter (or maybe not) since I don't know about security.

I suggest using Interface (no need to use Class with constructor and so...), since you only have to create something like :

public interface ActivityClass {

    public static final String MYSTRING_1 = "STRING";

    public static final int MYINT_1 = 1;

}

Then you can access everywhere within your classes by using the following:

int myInt = ActivityClass.MYINT_1;
String myString = ActivityClass.MYSTRING_1;

How to scroll to top of page with JavaScript/jQuery?

If you're in quircks mode (thanks @Niet the Dark Absol):

document.body.scrollTop = document.documentElement.scrollTop = 0;

If you're in strict mode:

document.documentElement.scrollTop = 0;

No need for jQuery here.

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

lodash multi-column sortBy descending

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy:

var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);

What is the precise meaning of "ours" and "theirs" in git?

  • Ours: This is the branch you are currently on.
  • Theirs: This is the other branch that is used in your action.

So if you are on branch release/2.5 and you merge branch feature/new-buttons into it, then the content as found in release/2.5 is what ours refers to and the content as found on feature/new-buttons is what theirs refers to. During a merge action this is pretty straight forward.

The only problem most people fall for is the rebase case. If you do a re-base instead of a normal merge, the roles are swapped. How's that? Well, that's caused solely by the way rebasing works. Think of rebase to work like that:

  1. All commits you have done since your last pull are moved to a branch of their own, let's name it BranchX.
  2. You checkout the head of your current branch, discarding any local changes you had but that way retrieving all changes others have pushed for that branch.
  3. Now every commit on BranchX is cherry-picked in order old to new to your current branch.
  4. BranchX is deleted again and thus won't ever show up in any history.

Of course, that's not really what is going on but it's a nice mind model for me. And if you look at 2 and 3, you will understand why the roles are swapped now. As of 2, your current branch is now the branch from the server without any of your changes, so this is ours (the branch you are on). The changes you made are now on a different branch that is not your current one (BranchX) and thus these changes (despite being the changes you made) are theirs (the other branch used in your action).

That means if you merge and you want your changes to always win, you'd tell git to always choose "ours" but if you rebase and you want all your changes to always win, you tell git to always choose "theirs".

Remap values in pandas column with a dict

Adding to this question if you ever have more than one columns to remap in a data dataframe:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels 
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

Hope it can be useful to someone.

Cheers

File to byte[] in Java

Using the same approach as the community wiki answer, but cleaner and compiling out of the box (preferred approach if you don't want to import Apache Commons libs, e.g. on Android):

public static byte[] getFileBytes(File file) throws IOException {
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1)
            ous.write(buffer, 0, read);
    } finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
    }
    return ous.toByteArray();
}

Making PHP var_dump() values display one line per value

Yes, try wrapping it with <pre>, e.g.:

echo '<pre>' , var_dump($variable) , '</pre>';

How can I get the current network interface throughput statistics on Linux/UNIX?

Besides iftop and iptraf, also check:

  • bwm-ng (Bandwidth Monitor Next Generation)

and/or

  • cbm (Color Bandwidth Meter)

ref: http://www.powercram.com/2010/01/bandwidth-monitoring-tools-for-ubuntu.html

VLook-Up Match first 3 characters of one column with another column

Try using a wildcard like this

=VLOOKUP(LEFT(A1,3)&"*",B$2:B$22,1,FALSE)

so if A1 is "barry" that formula will return the first value in B2:B22 that starts with "bar"

Remove the last line from a file in Bash

I had trouble with all the answers here because I was working with a HUGE file (~300Gb) and none of the solutions scaled. Here's my solution:

dd if=/dev/null of=<filename> bs=1 seek=$(echo $(stat --format=%s <filename> ) - $( tail -n1 <filename> | wc -c) | bc )

In words: Find out the length of the file you want to end up with (length of file minus length of length of its last line, using bc) and, set that position to be the end of the file (by dding one byte of /dev/null onto it).

This is fast because tail starts reading from the end, and dd will overwrite the file in place rather than copy (and parse) every line of the file, which is what the other solutions do.

NOTE: This removes the line from the file in place! Make a backup or test on a dummy file before trying it out on your own file!

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

How can I select rows by range?

Assuming id is the primary key of table :

SELECT * FROM table WHERE id BETWEEN 10 AND 50

For first 20 results

SELECT * FROM table order by id limit 20;

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

More correct variant:

{
struct timespec delta = {5 /*secs*/, 135 /*nanosecs*/};
while (nanosleep(&delta, &delta));
}

Using Custom Domains With IIS Express

Following Jaro's advice, I was able to get this working under Windows XP and IIS Express (installed via Web Matrix) with a small modification and was not limited to only localhost. It's just a matter of setting the bindings correctly.

  1. Use WebMatrix to create a new site from folder in your web application root.
  2. Close WebMatrix.
  3. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config (Windows XP. Vista and 7 paths will be similar) and edit the site definition in the <sites> config block to be along the lines of the following:

    <site name="DevExample" id="997005936">
        <application path="/" applicationPool="Clr2IntegratedAppPool">
            <virtualDirectory
                path="/"
                physicalPath="C:\path\to\application\root" />
        </application>
        <bindings>
            <binding
                protocol="http"
                bindingInformation="*:80:dev.example.com" />
        </bindings>
        <applicationDefaults applicationPool="Clr2IntegratedAppPool" />
    </site>

If running MVC, then keep the applicationPool set to one of the "Integrated" options.

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

How to run function of parent window when child window closes?

Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer

Error pushing to GitHub - insufficient permission for adding an object to repository database

 user@M063:/var/www/html/app/.git/objects$ sudo chmod 777 -R .git/objects
 user@M063:/var/www/html/app/.git/objects$ sudo chown -R user:user .git/objects/

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

The answer is:

<a href="page.html" onclick="return false">page link</a>

select2 changing items dynamically

For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check https://github.com/select2/select2/issues/2830

Table with fixed header and fixed column on pure css

To fix both Headers and Columns, you can use the following plugin:


Updated in July 2019

Recently is emerged also a pure CSS solution that is based on CSS property position: sticky; (here for more details about it) applied onto each TH item (instead of their parent container)

Change User Agent in UIWebView

To just add a custom content to the current UserAgent value, do the following:

1 - Get the user agent value from a NEW WEBVIEW

2 - Append the custom content to it

3 - Save the new value in a dictionary with the key UserAgent

4 - Save the dictionary in standardUserDefaults.

See the exemple below:

NSString *userAgentP1 = [[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *userAgentP2 = @"My_custom_value";
NSString *userAgent = [NSString stringWithFormat:@"%@ %@", userAgentP1, userAgentP2];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:userAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

How can I convert an RGB image into grayscale in Python?

image=myCamera.getImage().crop(xx,xx,xx,xx).scale(xx,xx).greyscale()

You can use greyscale() directly for the transformation.

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Peak memory usage of a linux/unix process

Because /usr/bin/time is not present in many modern distributions (Bash built-in time instead), you can use Busybox time implementation with -v argument:

busybox time -v uname -r

It's output is similar to GNU time output. Busybox is pre-installed in most Linux distros (Debian, Ubuntu, etc.). If you using Arch Linux, you can install it with:

sudo pacman -S busybox

How do you run CMD.exe under the Local System Account?

  1. Download psexec.exe from Sysinternals.
  2. Place it in your C:\ drive.
  3. Logon as a standard or admin user and use the following command: cd \. This places you in the root directory of your drive, where psexec is located.
  4. Use the following command: psexec -i -s cmd.exe where -i is for interactive and -s is for system account.
  5. When the command completes, a cmd shell will be launched. Type whoami; it will say 'system"
  6. Open taskmanager. Kill explorer.exe.
  7. From an elevated command shell type start explorer.exe.
  8. When explorer is launched notice the name "system" in start menu bar. Now you can delete some files in system32 directory which as admin you can't delete or as admin you would have to try hard to change permissions to delete those files.

Users who try to rename or deleate System files in any protected directory of windows should know that all windows files are protected by DACLS while renaming a file you have to change the owner and replace TrustedInstaller which owns the file and make any user like a user who belongs to administrator group as owner of file then try to rename it after changing the permission, it will work and while you are running windows explorer with kernel privilages you are somewhat limited in terms of Network access for security reasons and it is still a research topic for me to get access back

FlutterError: Unable to load asset

  1. you should start image path with assets word:

image: AssetImage('assets/images/pizza0.png')

  1. you must add each sub folder in a new line in pubspec.yaml

How to show text in combobox when no item selected?

Here's how I do it. It might not be the best method, and offers least control; however, it's simple and quick and I thought it might be a good idea to share it so that more options are available for others.

<ComboBox SelectedIndex="0">
    <ComboBoxItem Visibility="Collapsed">Please select one...</ComboBoxItem>
    <ComboBoxItem>1</ComboBoxItem>
    <ComboBoxItem>2</ComboBoxItem>
    <ComboBoxItem>3</ComboBoxItem>
    <ComboBoxItem>4</ComboBoxItem>
</ComboBox>

The idea behind this is that the initial selection is index 0, which is collapsed, so it's not available under selection for the user once they select something else. The downside is that you have to remember that if you're checking for a selected index, remember that index 0 means there was no selection made.

Axios handling errors

I tried using the try{}catch{} method but it did not work for me. However, when I switched to using .then(...).catch(...), the AxiosError is caught correctly that I can play around with. When I try the former when putting a breakpoint, it does not allow me to see the AxiosError and instead, says to me that the caught error is undefined, which is also what eventually gets displayed in the UI.

Not sure why this happens I find it very trivial. Either way due to this, I suggest using the conventional .then(...).catch(...) method mentioned above to avoid throwing undefined errors to the user.

HttpWebRequest using Basic authentication

Try this:

System.Net.CredentialCache credentialCache = new System.Net.CredentialCache(); 
credentialCache.Add(
    new System.Uri("http://www.yoururl.com/"),
    "Basic", 
    new System.Net.NetworkCredential("username", "password")
);

...
...

httpWebRequest.Credentials = credentialCache; 

Using CRON jobs to visit url?

* * * * * wget -O - http://yoursite.com/tasks.php >/dev/null 2>&1

That should work for you. Just have a wget script that loads the page.

Using -O - means that the output of the web request will be sent to STDOUT (standard output)

by adding >/dev/null we instruct standard output to be redirect to a black hole. by adding 2>&1 we instruct STDERR (errors) to also be sent to STDOUT, and thus all output will be sent to a blackhole. (so it will load the website, but never write a file anywhere)

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Get first day of week in SQL Server

This works wonderfully for me:

CREATE FUNCTION [dbo].[StartOfWeek]
(
  @INPUTDATE DATETIME
)
RETURNS DATETIME

AS
BEGIN
  -- THIS does not work in function.
  -- SET DATEFIRST 1 -- set monday to be the first day of week.

  DECLARE @DOW INT -- to store day of week
  SET @INPUTDATE = CONVERT(VARCHAR(10), @INPUTDATE, 111)
  SET @DOW = DATEPART(DW, @INPUTDATE)

  -- Magic convertion of monday to 1, tuesday to 2, etc.
  -- irrespect what SQL server thinks about start of the week.
  -- But here we have sunday marked as 0, but we fix this later.
  SET @DOW = (@DOW + @@DATEFIRST - 1) %7
  IF @DOW = 0 SET @DOW = 7 -- fix for sunday

  RETURN DATEADD(DD, 1 - @DOW,@INPUTDATE)

END

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, I was fetching data from database, changing some column values and updating it in database but for updating I was using the same save query which was violating primary key constraints i.e duplicate values for primary key, so I had written a separate query for updating the columns and it solved my problem..!