Programs & Examples On #Simplification

Vue.js - How to properly watch for nested data

I've found it works this way too:

watch: {
    "details.position"(newValue, oldValue) {
        console.log("changes here")
    }
},
data() {
    return {
      details: {
          position: ""
      }
    }
}

How do I redirect in expressjs while passing some context?

we can use express-session to send the required data

when you initialise the app

const express = require('express');
const app = express();
const session = require('express-session');
app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false}));

so before redirection just save the context for the session

app.post('/category', function(req, res) {
    // add your context here 
req.session.context ='your context here' ;
    res.redirect('/');
});

Now you can get the context anywhere for the session. it can get just by req.session.context

app.get('/', function(req, res) {

    // So prepare the context
var context=req.session.context;
    res.render('home.jade', context);
});

Stop absolutely positioned div from overlapping text

Could you add z-index style to the two sections so that the one you want appears on top?

Div height 100% and expands to fit content

You can also use

 display: inline-block;

mine worked with this

How to properly create composite primary keys - MYSQL

CREATE  TABLE `mom`.`sec_subsection` (

  `idsec_sub` INT(11) NOT NULL ,

  `idSubSections` INT(11) NOT NULL ,

  PRIMARY KEY (`idsec_sub`, `idSubSections`) 

);

postgresql - sql - count of `true` values

probably, the best approach is to use nullif function.

in general

select
    count(nullif(myCol = false, true)),  -- count true values
    count(nullif(myCol = true, true)),   -- count false values
    count(myCol);

or in short

select
    count(nullif(myCol, true)),  -- count false values
    count(nullif(myCol, false)), -- count true values
    count(myCol);

http://www.postgresql.org/docs/9.0/static/functions-conditional.html

Comparing two dictionaries and checking how many (key, value) pairs are equal

I'm new to python but I ended up doing something similar to @mouad

unmatched_item = set(dict_1.items()) ^ set(dict_2.items())
len(unmatched_item) # should be 0

The XOR operator (^) should eliminate all elements of the dict when they are the same in both dicts.

Deleting an object in C++

saveLeaves(vec,msh);
I'm assuming takes the msh pointer and puts it inside of vec. Since msh is just a pointer to the memory, if you delete it, it will also get deleted inside of the vector.

What is simplest way to read a file into String?

Don't write your own util class to do this - I would recommend using Guava, which is full of all kinds of goodness. In this case you'd want either the Files class (if you're really just reading a file) or CharStreams for more general purpose reading. It has methods to read the data into a list of strings (readLines) or totally (toString).

It has similar useful methods for binary data too. And then there's the rest of the library...

I agree it's annoying that there's nothing similar in the standard libraries. Heck, just being able to supply a CharSet to a FileReader would make life a little simpler...

adding child nodes in treeview

May i add to Stormenet example some KISS (Keep It Simple & Stupid):

If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :

            treeView1.Nodes.Add("ParentKey","Parent Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");

Another Ex. two parent's first have two child's second one child:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
            treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");

Take if farther - sub child of child 2:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");

As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!

How do I manage conflicts with git submodules?

First, find the hash you want to your submodule to reference. then run

~/supery/subby $ git co hashpointerhere
~/supery/subby $ cd ../
~/supery $ git add subby
~/supery $ git commit -m 'updated subby reference'

that has worked for me to get my submodule to the correct hash reference and continue on with my work without getting any further conflicts.

NLS_NUMERIC_CHARACTERS setting for decimal

Best way is,

SELECT to_number(replace(:Str,',','')/100) --into num2 
FROM dual;

How to define constants in Visual C# like #define in C?

static class Constants
{
    public const int MIN_LENGTH = 5;
    public const int MIN_WIDTH  = 5; 
    public const int MIN_HEIGHT = 6;
}

// elsewhere
public CBox()
{
    length = Constants.MIN_LENGTH; 
    width  = Constants.MIN_WIDTH; 
    height = Constants.MIN_HEIGHT;  
}

Java Loop every minute

ScheduledExecutorService

The Answer by Lee is close, but only runs once. The Question seems to be asking to run indefinitely until an external state changes (until the response from a web site/service changes).

The ScheduledExecutorService interface is part of the java.util.concurrent package built into Java 5 and later as a more modern replacement for the old Timer class.

Here is a complete example. Call either scheduleAtFixedRate or scheduleWithFixedDelay.

ScheduledExecutorService executor = Executors.newScheduledThreadPool ( 1 );

Runnable r = new Runnable () {
    @Override
    public void run () {
        try {  // Always wrap your Runnable with a try-catch as any uncaught Exception causes the ScheduledExecutorService to silently terminate.
            System.out.println ( "Now: " + Instant.now () );  // Our task at hand in this example: Capturing the current moment in UTC.
            if ( Boolean.FALSE ) {  // Add your Boolean test here to see if the external task is fonud to be completed, as described in this Question.
                executor.shutdown ();  // 'shutdown' politely asks ScheduledExecutorService to terminate after previously submitted tasks are executed.
            }

        } catch ( Exception e ) {
            System.out.println ( "Oops, uncaught Exception surfaced at Runnable in ScheduledExecutorService." );
        }
    }
};

try {
    executor.scheduleAtFixedRate ( r , 0L , 5L , TimeUnit.SECONDS ); // ( runnable , initialDelay , period , TimeUnit )
    Thread.sleep ( TimeUnit.MINUTES.toMillis ( 1L ) ); // Let things run a minute to witness the background thread working.
} catch ( InterruptedException ex ) {
    Logger.getLogger ( App.class.getName () ).log ( Level.SEVERE , null , ex );
} finally {
    System.out.println ( "ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed." );
    executor.shutdown ();
}

Expect output like this:

Now: 2016-12-27T02:52:14.951Z
Now: 2016-12-27T02:52:19.955Z
Now: 2016-12-27T02:52:24.951Z
Now: 2016-12-27T02:52:29.951Z
Now: 2016-12-27T02:52:34.953Z
Now: 2016-12-27T02:52:39.952Z
Now: 2016-12-27T02:52:44.951Z
Now: 2016-12-27T02:52:49.953Z
Now: 2016-12-27T02:52:54.953Z
Now: 2016-12-27T02:52:59.951Z
Now: 2016-12-27T02:53:04.952Z
Now: 2016-12-27T02:53:09.951Z
ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed.
Now: 2016-12-27T02:53:14.951Z

How can I deploy an iPhone application from Xcode to a real iPhone device?

Free Provisioning after Xcode 7

In order to test your app on a real device rather than pay the Apple Developer fee (or jailbreak your device), you can use the new free provisioning that Xcode 7 and iOS 9 supports.

Here are the steps taken more or less from the documentation (which is pretty good, so give it a read):

1. Add your Apple ID in Xcode

Go to XCode > Preferences > Accounts tab > Add button (+) > Add Apple ID. See the docs for more help.

enter image description here

2. Click the General tab in the Project Navigator

enter image description here

3. Choose your Apple ID from the Team popup menu.

enter image description here

4. Connect your device and choose it in the scheme menu.

enter image description here

5. Click the Fix Issues button

enter image description here

If you get an error about the bundle name being invalid, change it to something unique.

6. Run your app

In Xcode, click the Build and run button.

enter image description here

7. Trust the app developer in the device settings

After running your app, you will get a security error because the app you want to run is not from the App Store.

enter image description here

On your device, go to Settings > General > Profile > your-Apple-ID-name > Trust your-Apple-ID-name > Trust.

8. Run your app on your device again.

That's it. You can now run your own (or any other apps that you have the source code for) without having to dish out the $99 dollars. Thank you, Apple, for finally allowing this.

How do I change db schema to dbo

You can batch change schemas of multiple database objects as described in this post:

How to change schema of all tables, views and stored procedures in MSSQL

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

I also had this problem. I changed port and did other things, but they didn't help me. In my case, I connected Tomcat to IDE after installing Netbeans (before). I just uninstalled Netbeans and Tomcat after that I reinstall Netbeans along with Tomcat (NOT separately). And the problem was solved.

Is there a GUI design app for the Tkinter / grid geometry?

The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.

Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.

* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).

How do I lowercase a string in Python?

How to convert string to lowercase in Python?

Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?

E.g. Kilometers --> kilometers

The canonical Pythonic way of doing this is

>>> 'Kilometers'.lower()
'kilometers'

However, if the purpose is to do case insensitive matching, you should use case-folding:

>>> 'Kilometers'.casefold()
'kilometers'

Here's why:

>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True

This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.

Unicode Python 3

Python 3 handles plain string literals as unicode:

>>> string = '????????'
>>> string
'????????'
>>> string.lower()
'????????'

Python 2, plain string literals are bytes

In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8.

And lower doesn't map any changes that bytes would be aware of, so we get the same string.

>>> string = '????????'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
????????

In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263

Use Unicode literals, not str literals

So we need a unicode string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u prefix (and note the u prefix also works in Python 3):

>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())
????????

Note that the bytes are completely different from the str bytes - the escape character is '\u' followed by the 2-byte width, or 16 bit representation of these unicode letters:

>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'

Now if we only have it in the form of a str, we need to convert it to unicode. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode constructor or str.decode method with the codec to convert the str to unicode:

>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
????????
>>> string_to_unicode = string.decode('utf-8') 
>>> print(string_to_unicode.lower())
????????
>>> unicode_from_string == string_to_unicode == unicode_literal
True

Both methods convert to the unicode type - and same as the unicode_literal.

Best Practice, use Unicode

It is recommended that you always work with text in Unicode.

Software should only work with Unicode strings internally, converting to a particular encoding on output.

Can encode back when necessary

However, to get the lowercase back in type str, encode the python string to utf-8 again:

>>> print string
????????
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
????????

So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.

How to parse JSON in Kotlin?

I personally use the Jackson module for Kotlin that you can find here: jackson-module-kotlin.

implementation "com.fasterxml.jackson.module:jackson-module-kotlin:$version"

As an example, here is the code to parse the JSON of the Path of Exile skilltree which is quite heavy (84k lines when formatted) :

Kotlin code:

package util

import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.*
import java.io.File

data class SkillTreeData( val characterData: Map<String, CharacterData>, val groups: Map<String, Group>, val root: Root,
                          val nodes: List<Node>, val extraImages: Map<String, ExtraImage>, val min_x: Double,
                          val min_y: Double, val max_x: Double, val max_y: Double,
                          val assets: Map<String, Map<String, String>>, val constants: Constants, val imageRoot: String,
                          val skillSprites: SkillSprites, val imageZoomLevels: List<Int> )


data class CharacterData( val base_str: Int, val base_dex: Int, val base_int: Int )

data class Group( val x: Double, val y: Double, val oo: Map<String, Boolean>?, val n: List<Int> )

data class Root( val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )

data class Node( val id: Int, val icon: String, val ks: Boolean, val not: Boolean, val dn: String, val m: Boolean,
                 val isJewelSocket: Boolean, val isMultipleChoice: Boolean, val isMultipleChoiceOption: Boolean,
                 val passivePointsGranted: Int, val flavourText: List<String>?, val ascendancyName: String?,
                 val isAscendancyStart: Boolean?, val reminderText: List<String>?, val spc: List<Int>, val sd: List<String>,
                 val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )

data class ExtraImage( val x: Double, val y: Double, val image: String )

data class Constants( val classes: Map<String, Int>, val characterAttributes: Map<String, Int>,
                      val PSSCentreInnerRadius: Int )

data class SubSpriteCoords( val x: Int, val y: Int, val w: Int, val h: Int )

data class Sprite( val filename: String, val coords: Map<String, SubSpriteCoords> )

data class SkillSprites( val normalActive: List<Sprite>, val notableActive: List<Sprite>,
                         val keystoneActive: List<Sprite>, val normalInactive: List<Sprite>,
                         val notableInactive: List<Sprite>, val keystoneInactive: List<Sprite>,
                         val mastery: List<Sprite> )

private fun convert( jsonFile: File ) {
    val mapper = jacksonObjectMapper()
    mapper.configure( DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true )

    val skillTreeData = mapper.readValue<SkillTreeData>( jsonFile )
    println("Conversion finished !")
}

fun main( args : Array<String> ) {
    val jsonFile: File = File( """rawSkilltree.json""" )
    convert( jsonFile )

JSON (not-formatted): http://filebin.ca/3B3reNQf3KXJ/rawSkilltree.json

Given your description, I believe it matches your needs.

Automatically running a batch file as an administrator

CMD Itself does not have a function to run files as admin, but powershell does, and that powershell function can be exectuted through CMD with a certain command. Write it in command prompt to run the file you specified as admin.

powershell -command start-process -file yourfilename -verb runas

Hope it helped!

How to change the ROOT application?

I've got a problem when configured Tomcat' server.xml and added Context element. He just doesn't want to use my config: http://www.oreillynet.com/onjava/blog/2006/12/configuration_antipatterns_tom.html

If you're in a Unix-like system:

  1. mv $CATALINA_HOME/webapps/ROOT $CATALINA_HOME/webapps/___ROOT
  2. ln -s $CATALINA_HOME/webapps/your_project $CATALINA_HOME/webapps/ROOT

Done.

Works for me.

How to ensure that there is a delay before a service is started in systemd?

Instead of editing the bringup service, add a post-start delay to the service which it depends on. Edit cassandra.service like so:

ExecStartPost=/bin/sleep 30

This way the added sleep shouldn't slow down restarts of starting services that depend on it (though does slow down its own start, maybe that's desirable?).

Measure the time it takes to execute a t-sql query

Another way is using a SQL Server built-in feature named Client Statistics which is accessible through Menu > Query > Include Client Statistics.

You can run each query in separated query window and compare the results which is given in Client Statistics tab just beside the Messages tab.

For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.

Result

You can read all 3 ways for acquiring execution time in here. You may even need to display Estimated Execution Plan ctrlL for further investigation about your query.

Can a CSS class inherit one or more other classes?

In specific circumstances you can do a "soft" inheritance:

.composite
{
display:inherit;
background:inherit;
}

.something { display:inline }
.else      { background:red }

This only works if you are adding the .composite class to a child element. It is "soft" inheritance because any values not specified in .composite are not inherited obviously. Keep in mind it would still be less characters to simply write "inline" and "red" instead of "inherit".

Here is a list of properties and whether or not they do this automatically: https://www.w3.org/TR/CSS21/propidx.html

Remove Server Response Header IIS7

Addition to the URL Rewrite answer, here is the complete XML for web.config

<system.webServer>
  <rewrite>
    <outboundRules>
      <rule name="Remove RESPONSE_Server" >
        <match serverVariable="RESPONSE_Server" pattern=".+" />
        <action type="Rewrite" value="Company name" />
      </rule>
    </outboundRules>
  </rewrite>
</system.webServer>

URL Rewrite

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

parseDouble returns a primitive double containing the value of the string:

Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

valueOf returns a Double instance, if already cached, you'll get the same cached instance.

Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

To avoid the overhead of creating a new Double object instance, you should normally use valueOf

How can I check the size of a collection within a Django template?

A list is considered to be False if it has no elements, so you can do something like this:

{% if mylist %}
    <p>I have a list!</p>
{% else %}
    <p>I don't have a list!</p>
{% endif %}

Multiple HttpPost method in Web API controller

use:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

it's not a RESTful approach anymore, but you can now call your actions by name (rather than let the Web API automatically determine one for you based on the verb) like this:

[POST] /api/VTRouting/TSPRoute

[POST] /api/VTRouting/Route

Contrary to popular belief, there is nothing wrong with this approach, and it's not abusing Web API. You can still leverage on all the awesome features of Web API (delegating handlers, content negotiation, mediatypeformatters and so on) - you just ditch the RESTful approach.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

uppercase first character in a variable with bash

Using awk only

foo="uNcapItalizedstrIng"
echo $foo | awk '{print toupper(substr($0,0,1))tolower(substr($0,2))}'

MySQL SELECT only not null values

You should use IS NOT NULL. (The comparison operators = and <> both give UNKNOWN with NULL on either side of the expression.)

SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;

Just for completeness I'll mention that in MySQL you can also negate the null safe equality operator but this is not standard SQL.

SELECT *
FROM table 
WHERE NOT (YourColumn <=> NULL);

Edited to reflect comments. It sounds like your table may not be in first normal form in which case changing the structure may make your task easier. A couple of other ways of doing it though...

SELECT val1 AS val
FROM  your_table
WHERE val1 IS NOT NULL
UNION ALL
SELECT val2 
FROM  your_table
WHERE val2 IS NOT NULL
/*And so on for all your columns*/

The disadvantage of the above is that it scans the table multiple times once for each column. That may possibly be avoided by the below but I haven't tested this in MySQL.

SELECT CASE idx
         WHEN 1 THEN val1
         WHEN 2 THEN val2
       END AS val
FROM   your_table
        /*CROSS JOIN*/
       JOIN (SELECT 1 AS idx
                   UNION ALL
                   SELECT 2) t
HAVING val IS NOT NULL  /*Can reference alias in Having in MySQL*/

How to access html form input from asp.net code behind

What I'm guessing is that you need to set those input elements to runat="server".

So you won't be able to access the control

<input type="text" name="email" id="myTextBox" />

But you'll be able to work with

<input type="text" name="email" id="myTextBox" runat="server" />

And read from it by using

string myStringFromTheInput = myTextBox.Value;

Difference between git pull and git pull --rebase

git pull = git fetch + git merge against tracking upstream branch

git pull --rebase = git fetch + git rebase against tracking upstream branch

If you want to know how git merge and git rebase differ, read this.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

Select from one table where not in another

So there's loads of posts on the web that show how to do this, I've found 3 ways, same as pointed out by Johan & Sjoerd. I couldn't get any of these queries to work, well obviously they work fine it's my database that's not working correctly and those queries all ran slow.

So I worked out another way that someone else may find useful:

The basic jist of it is to create a temporary table and fill it with all the information, then remove all the rows that ARE in the other table.

So I did these 3 queries, and it ran quickly (in a couple moments).

CREATE TEMPORARY TABLE

`database1`.`newRows`

SELECT

`t1`.`id` AS `columnID`

FROM

`database2`.`table` AS `t1`

.

CREATE INDEX `columnID` ON `database1`.`newRows`(`columnID`)

.

DELETE FROM `database1`.`newRows`

WHERE

EXISTS(
    SELECT `columnID` FROM `database1`.`product_details` WHERE `columnID`=`database1`.`newRows`.`columnID`
)

How to pass a null variable to a SQL Stored Procedure from C#.net code

I use a method to convert to DBNull if it is null

    // Converts to DBNull, if Null
    public static object ToDBNull(object value)
    {
        if (null != value)
            return value;
        return DBNull.Value;
    }

So when setting the parameter, just call the function

    sqlComm.Parameters.Add(new SqlParameter("@NoteNo", LibraryHelper.ToDBNull(NoteNo)));

This will ensure any nulls, get changed to DBNull.Value, else it will stay the same.

HTML5 required attribute seems not working

Yes, you missed the form encapsulation:

JSFiddle

<form>
   <input id="tbQuestion" type="text" placeholder="Post a question?" required/>
   <input id="btnSubmit" type="submit" />
</form>

Difference between JOIN and INNER JOIN

Similarly with OUTER JOINs, the word "OUTER" is optional. It's the LEFT or RIGHT keyword that makes the JOIN an "OUTER" JOIN.

However for some reason I always use "OUTER" as in LEFT OUTER JOIN and never LEFT JOIN, but I never use INNER JOIN, but rather I just use "JOIN":

SELECT ColA, ColB, ...
FROM MyTable AS T1
     JOIN MyOtherTable AS T2
         ON T2.ID = T1.ID
     LEFT OUTER JOIN MyOptionalTable AS T3
         ON T3.ID = T1.ID

Randomize numbers with jQuery?

This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

var number = 1 + Math.floor(Math.random() * 6);

Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

setInterval(function() {
  var number = 1 + Math.floor(Math.random() * 6);
  $('#my_div').text(number);
},
1000); // every 1 second

Ruby 'require' error: cannot load such file

you need to give the path. Atleast you should give the path from the current directory. It will work for sure. ./filename

How to change MySQL data directory?

First stop your mysql

sudo service mysql stop

copy mysql data to the new location.

sudo cp -rp /var/lib/mysql /yourdirectory/

if you use apparmor, edit the following file and do the following

sudo vim /etc/apparmor.d/usr.sbin.mysqld

Replace where /var/lib/ by /yourdirectory/ then add the follwoing if no exist to the file

    /yourdirectory/mysql/ r,
    /yourdirectory/mysql/** rwk,

Save the file with the command

:wq

Edit the file my.cnf

sudo vim /etc/mysql/my.cnf

Replace where /var/lib/ by /yourdirectory/ then save with the command

:wq

finally start mysql

sudo service mysql start

@see more about raid0, optimization ici

Modifying CSS class property values on the fly with JavaScript / jQuery

Like @benvie said, its more efficient to change a style sheet rather than using jQuery.css (which will loop through all of the elements in the set). It is also important not to add a new style to the head every time the function is called because it will create a memory leak and thousands of CSS rules that have to be individually applied by the browser. I would do something like this:

//Add the stylesheet once and store a cached jQuery object
var $style = $("<style type='text/css'>").appendTo('head'); 

function onResize() {
    var css = "\
        .someClass {\
            left:   "+leftVal+";\
            width:  "+widthVal+";\
            height: "+heightVal+";\
        }";

    $style.html(css);
}

This solution will change your styles by modifying the DOM only once per resize. Note that for effective js minification and compression, you probably don't want to pretty-print the css, but I did for clarity.

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

I was getting the same error even after doing above changes and what i did is

Right click on the project->properties->java compiler->Compiler compliance level->changes it to 1.6

This change is particular for the project. This should hopefully work.

C++ terminate called without an active exception

First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable.

Cocoa Autolayout: content hugging vs content compression resistance priority

The Content hugging priority is like a Rubber band that is placed around a view. The higher the priority value, the stronger the rubber band and the more it wants to hug to its content size. The priority value can be imagined like the "strength" of the rubber band

And the Content Compression Resistance is, how much a view "resists" getting smaller The View with higher resistance priority value is the one that will resist compression.

Meaning of 'const' last in a function declaration of a class?

These const mean that compiler will Error if the method 'with const' changes internal data.

class A
{
public:
    A():member_()
    {
    }

    int hashGetter() const
    {
        state_ = 1;
        return member_;
    }
    int goodGetter() const
    {
        return member_;
    }
    int getter() const
    {
        //member_ = 2; // error
        return member_;
    }
    int badGetter()
    {
        return member_;
    }
private:
    mutable int state_;
    int member_;
};

The test

int main()
{
    const A a1;
    a1.badGetter(); // doesn't work
    a1.goodGetter(); // works
    a1.hashGetter(); // works

    A a2;
    a2.badGetter(); // works
    a2.goodGetter(); // works
    a2.hashGetter(); // works
}

Read this for more information

SimpleDateFormat and locale based format string

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String formatted = dateFormat.format(the_date_you_want_here);

How to downgrade tensorflow, multiple versions possible?

Click to green checkbox on installed tensorflow and choose needed versionscreenshot Anaconda navigator

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

List method to delete last element in list as well as all elements

To delete the last element of the lists, you could use:

def deleteLast(self):
    if self.Ans:
        del self.Ans[-1]
    if self.masses:
        del self.masses[-1]

C++ preprocessor __VA_ARGS__ number of arguments

There are some C++11 solutions for finding the number of arguments at compile-time, but I'm surprised to see that no one has suggested anything so simple as:

#define VA_COUNT(...) detail::va_count(__VA_ARGS__)

namespace detail
{
    template<typename ...Args>
    constexpr std::size_t va_count(Args&&...) { return sizeof...(Args); }
}

This doesn't require inclusion of the <tuple> header either.

How does one convert a HashMap to a List in Java?

Solution using Java 8 and Stream Api:

private static <K, V>  List<V> createListFromMapEntries (Map<K, V> map){
        return map.values().stream().collect(Collectors.toList());
    }

Usage:

  public static void main (String[] args)
    {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "one");
        map.put(2, "two");
        map.put(3, "three");

        List<String> result = createListFromMapEntries(map);
        result.forEach(System.out :: println);
    }

Get protocol + host name from URL

This is a bit obtuse, but uses urlparse in both directions:

import urlparse
def uri2schemehostname(uri):
    urlparse.urlunparse(urlparse.urlparse(uri)[:2] + ("",) * 4)

that odd ("",) * 4 bit is because urlparse expects a sequence of exactly len(urlparse.ParseResult._fields) = 6

How to programmatically close a JFrame

If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...) will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.

If by Alt-F4 or X you mean hide the window, then frame.setVisible(false) is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.

If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose() is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).

dispose() might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?

The Java Swing Tutorial on Window Listeners may help clarify things for you.

Adding/removing items from a JavaScript object with jQuery

Adding an object in a json array

var arrList = [];
var arr = {};   
arr['worker_id'] = worker_id;
arr['worker_nm'] = worker_nm;
arrList.push(arr);

Removing an object from a json

It worker for me.

  arrList = $.grep(arrList, function (e) { 

        if(e.worker_id == worker_id) {
            return false;
        } else {
            return true;
        }
    });

It returns an array without that object.

Hope it helps.

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

Permissions for /var/www/html

I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.

1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)

2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.

3) add your user account to the group that has permission on the folder (mine was www-data).

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

$_ is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ... so $_ represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:

write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH

How to check if directory exists in %PATH%?

This routine will search for a path\ or file.ext in the path variable it returns 0 if found. Path\ or file may contain spaces if quoted. If a variable is passed as the last argument it will be set to d:\path\file.

@echo off&goto :PathCheck
:PathCheck.CMD
echo.PathCheck.CMD: Checks for existence of a path or file in %%PATH%% variable
echo.Usage: PathCheck.CMD [Checkpath] or [Checkfile] [PathVar]
echo.Checkpath must have a trailing \ but checkfile must not
echo.If Checkpath contains spaces use quotes ie. "C:\Check path\"
echo.Checkfile must not include a path, just the filename.ext
echo.If Checkfile contains spaces use quotes ie. "Check File.ext"
echo.Returns 0 if found, 1 if not or -1 if checkpath does not exist at all
echo.If PathVar is not in command line it will be echoed with surrounding quotes
echo.If PathVar is passed it will be set to d:\path\checkfile with no trailing \
echo.Then %%PathVar%% will be set to the fully qualified path to Checkfile
echo.Note: %%PathVar%% variable set will not be surrounded with quotes
echo.To view the path listing line by line use: PathCheck.CMD /L
exit/b 1

:PathCheck
if "%~1"=="" goto :PathCheck.CMD
setlocal EnableDelayedExpansion
set "PathVar=%~2"
set "pth="
set "pcheck=%~1"
if "%pcheck:~-1%" equ "\" (
  if not exist %pcheck% endlocal&exit/b -1
  set/a pth=1
) 
for %%G in ("%path:;=" "%") do (
  set "Pathfd=%%~G\"
  set "Pathfd=!Pathfd:\\=\!"
  if /i "%pcheck%" equ "/L" echo.!Pathfd!
  if defined pth (
    if /i "%pcheck%" equ "!Pathfd!" endlocal&exit/b 0
  ) else (
    if exist "!Pathfd!%pcheck%" goto :CheckfileFound
  )
)
endlocal&exit/b 1

:CheckfileFound
endlocal&(
  if not "%PathVar%"=="" (
    call set "%~2=%Pathfd%%pcheck%"
  ) else (echo."%Pathfd%%pcheck%")
  exit/b 0
)

Django: Calling .update() on a single model instance retrieved by .get()?

As of Django 1.5, there is an update_fields property on model save. eg:

obj.save(update_fields=['field1', 'field2', ...])

https://docs.djangoproject.com/en/dev/ref/models/instances/

I prefer this approach because it doesn't create an atomicity problem if you have multiple web app instances changing different parts of a model instance.

How can I split this comma-delimited string in Python?

How about a list?

mystring.split(",")

It might help if you could explain what kind of info we are looking at. Maybe some background info also?

EDIT:

I had a thought you might want the info in groups of two?

then try:

re.split(r"\d*,\d*", mystring)

and also if you want them into tuples

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

in a more readable form:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

How to free memory in Java?

No one seems to have mentioned explicitly setting object references to null, which is a legitimate technique to "freeing" memory you may want to consider.

For example, say you'd declared a List<String> at the beginning of a method which grew in size to be very large, but was only required until half-way through the method. You could at this point set the List reference to null to allow the garbage collector to potentially reclaim this object before the method completes (and the reference falls out of scope anyway).

Note that I rarely use this technique in reality but it's worth considering when dealing with very large data structures.

ORA-01861: literal does not match format string

Remove the TO_DATE in the WHERE clause

TO_DATE (alarm_datetime,'DD.MM.YYYY HH24:MI:SS')

and change the code to

alarm_datetime

The error comes from to_date conversion of a date column.

Added Explanation: Oracle converts your alarm_datetime into a string using its nls depended date format. After this it calls to_date with your provided date mask. This throws the exception.

Different ways of loading a file as an InputStream

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./myfile.txt.

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt") and String.class.getClassLoader().getResourceAsStream("/myfile.txt") will both look for a file in your classpath at the following location: ./myfile.txt.

Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) instead of this.getClass().getClassLoader().getResourceAsStream(fileName). this.getClass().getResourceAsStream() will also work.

Read this article for more detailed information about that particular problem.


Warning for users of Tomcat 7 and below

One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.

So I've looked at the source code of Tomcat's WebAppClassLoader for several versions of Tomcat. The implementation of findResource(String name) (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.

In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt") may not produce the same result as classLoader.getResourceAsStream("resource.txt") event though it should (since that what the Javadoc specifies). [source code]

In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]

As a result, you have to be extra careful when using ClassLoader.getResourceAsStream() or Class.getResourceAsStream() on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt") actually calls classLoader.getResourceAsStream("resource.txt") (the leading / is stripped).

How to create a simple map using JavaScript/JQuery

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);

Set the layout weight of a TextView programmatically

TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);

1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space

How do I get the coordinates of a mouse click on a canvas element?

Update (5/5/16): patriques' answer should be used instead, as it's both simpler and more reliable.


Since the canvas isn't always styled relative to the entire page, the canvas.offsetLeft/Top doesn't always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a div element containing the canvas with a position: relative style applied. To account for this you need to loop through the chain of offsetParents, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all.

function relMouseCoords(event){
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var canvasX = 0;
    var canvasY = 0;
    var currentElement = this;

    do{
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    }
    while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that's needed to get the useful coordinates is

coords = canvas.relMouseCoords(event);
canvasX = coords.x;
canvasY = coords.y;

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

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

string source = "/once/upon/a/time/";
int count = 0, n = 0;
while ((n = source.IndexOf('/', n) + 1) != 0) count++;

A variation on Richard Watson's answer, slightly faster with improving efficiency the more times the char occurs in the string, and less code!

Though I must say, without extensively testing every scenario, I did see a very significant speed improvement by using:

int count = 0;
for (int n = 0; n < source.Length; n++) if (source[n] == '/') count++;

Bootstrap 3.0: How to have text and input on same line?

Straight from documentation http://getbootstrap.com/css/#forms-horizontal.

Use Bootstrap's predefined grid classes to align labels and groups of form controls in a horizontal layout by adding .form-horizontal to the form (which doesn't have to be a <form>). Doing so changes .form-groups to behave as grid rows, so no need for .row.

Sample:

<form class="form-horizontal">
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <div class="checkbox">
        <label>
          <input type="checkbox"> Remember me
        </label>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Sign in</button>
    </div>
  </div>
</form>

How to convert a time string to seconds?

without imports

time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 

Get all photos from Instagram which have a specific hashtag with PHP

To get more than 20 you can use a load more button.

index.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Instagram more button example</title>
  <!--
    Instagram PHP API class @ Github
    https://github.com/cosenary/Instagram-PHP-API
  -->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
    ul {
      width: 950px;
    }
    ul > li {
      float: left;
      list-style: none;
      padding: 4px;
    }
    #more {
      bottom: 8px;
      margin-left: 80px;
      position: fixed;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#more').click(function() {
        var tag   = $(this).data('tag'),
            maxid = $(this).data('maxid');

        $.ajax({
          type: 'GET',
          url: 'ajax.php',
          data: {
            tag: tag,
            max_id: maxid
          },
          dataType: 'json',
          cache: false,
          success: function(data) {
            // Output data
            $.each(data.images, function(i, src) {
              $('ul#photos').append('<li><img src="' + src + '"></li>');
            });

            // Store new maxid
            $('#more').data('maxid', data.next_id);
          }
        });
      });
    });
  </script>
</head>
<body>

<?php
  /**
   * Instagram PHP API
   */

   require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('ENTER CLIENT ID HERE');

    // Get latest photos according to geolocation for Växjö
    // $geo = $instagram->searchMedia(56.8770413, 14.8092744);

    $tag = 'sweden';

    // Get recently tagged media
    $media = $instagram->getTagMedia($tag);

    // Display first results in a <ul>
    echo '<ul id="photos">';

    foreach ($media->data as $data) 
    {
        echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
    }
    echo '</ul>';

    // Show 'load more' button
    echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>

</body>
</html>

ajax.php

<?php
    /**
     * Instagram PHP API
     */

     require_once 'instagram.class.php';

      // Initialize class for public requests
      $instagram = new Instagram('ENTER CLIENT ID HERE');

      // Receive AJAX request and create call object
      $tag = $_GET['tag'];
      $maxID = $_GET['max_id'];
      $clientID = $instagram->getApiKey();

      $call = new stdClass;
      $call->pagination->next_max_id = $maxID;
      $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

      // Receive new data
      $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

      // Collect everything for json output
      $images = array();
      foreach ($media->data as $data) {
        $images[] = $data->images->thumbnail->url;
      }

      echo json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images'  => $images
      ));
?>

instagram.class.php

Find the function getTagMedia() and replace with:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}

How to kill a child process after a given timeout in Bash?

(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")

If you don't mind downloading something, use timeout (sudo apt-get install timeout) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils)

timeout 10 ping www.goooooogle.com

If you don't want to download something, do what timeout does internally:

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )

In case that you want to do a timeout for longer bash code, use the second option as such:

( cmdpid=$BASHPID; 
    (sleep 10; kill $cmdpid) \
   & while ! ping -w 1 www.goooooogle.com 
     do 
         echo crap; 
     done )

How to insert Records in Database using C# language?

You should form the command with the contents of the textboxes:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";

This, of course, provided that you manage to open the connection correctly.

It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.

You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).

Simple way to unzip a .zip file using zlib

zlib handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.

You can try libzip. It is free, portable and easy to use.

UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:

#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, name, 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);

    //Do something with the contents
    //delete allocated memory
    delete[] contents;
}

How to delete multiple files at once in Bash on Linux?

Use a wildcard (*) to match multiple files.

For example, the command below will delete all files with names beginning with abc.log.2012-03-.

rm -f abc.log.2012-03-*

I'd recommend running ls abc.log.2012-03-* to list the files so that you can see what you are going to delete before running the rm command.

For more details see the Bash man page on filename expansion.

What is two way binding?

Worth mentioning that there are many different solutions which offer two way binding and play really nicely.

I have had a pleasant experience with this model binder - https://github.com/theironcook/Backbone.ModelBinder. which gives sensible defaults yet a lot of custom jquery selector mapping of model attributes to input elements.

There is a more extended list of backbone extensions/plugins on github

Check if string contains \n Java

The second one:

word.contains("\n");

What is the instanceof operator in JavaScript?

I just found a real-world application and will use it more often now, I think.

If you use jQuery events, sometimes you want to write a more generic function which may also be called directly (without event). You can use instanceof to check if the first parameter of your function is an instance of jQuery.Event and react appropriately.

var myFunction = function (el) {                
    if (el instanceof $.Event) 
        // event specific code
    else
        // generic code
};

$('button').click(recalc);    // Will execute event specific code
recalc('myParameter');  // Will execute generic code

In my case, the function needed to calculate something either for all (via click event on a button) or only one specific element. The code I used:

var recalc = function (el) { 
    el = (el == undefined || el instanceof $.Event) ? $('span.allItems') : $(el);
    // calculate...
};

how does Request.QueryString work?

The Request object is the entire request sent out to some server. This object comes with a QueryString dictionary that is everything after '?' in the URL.

Not sure exactly what you were looking for in an answer, but check out http://en.wikipedia.org/wiki/Query_string

How do you make an anchor link non-clickable or disabled?

Simply in SASS:

.some_class{
     // styles...

     &.active {
       pointer-events:none;
     }
}

Hide/Show components in react native

Most of the time i'm doing something like this :

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isHidden: false};
    this.onPress = this.onPress.bind(this);
  }
  onPress() {
    this.setState({isHidden: !this.state.isHidden})
  }
  render() {
    return (
      <View style={styles.myStyle}>

        {this.state.isHidden ? <ToHideAndShowComponent/> : null}

        <Button title={this.state.isHidden ? "SHOW" : "HIDE"} onPress={this.onPress} />
      </View>
    );
  }
}

If you're kind of new to programming, this line must be strange to you :

{this.state.isHidden ? <ToHideAndShowComponent/> : null}

This line is equivalent to

if (this.state.isHidden)
{
  return ( <ToHideAndShowComponent/> );
}
else
{
  return null;
}

But you can't write an if/else condition in JSX content (e.g. the return() part of a render function) so you'll have to use this notation.

This little trick can be very useful in many cases and I suggest you to use it in your developments because you can quickly check a condition.

Regards,

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

Python: Binding Socket: "Address already in use"

Try using the SO_REUSEADDR socket option before binding the socket.

comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Edit: I see you're still having trouble with this. There is a case where SO_REUSEADDR won't work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR enabled), then TIME_WAIT will still be in effect. It will however allow you to connect to a different host:port.

A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.

How to create .ipa file using Xcode?

At the time of Building select device as iOS device. Then build the application. Select Product->Archive then select Share and save the .ipa file. Rename the ipa file to .zip and double click on zip file and you will get .app file in the folder. then compress the .app file of the application and iTunesArtwork image. it will be in the format .zip rename .zip to .ipa file.

How to install mysql-connector via pip

If loading via pip install mysql-connector and leads an error Unable to find Protobuf include directory then this would be useful pip install mysql-connector==2.1.4

mysql-connector is obsolete, so use pip install mysql-connector-python. Same here

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

How do I increase modal width in Angular UI Bootstrap?

If you want to just go with the default large size you can add 'modal-lg':

var modal = $modal.open({
          templateUrl: "/partials/welcome",
          controller: "welcomeCtrl",
          backdrop: "static",
          scope: $scope,
          windowClass: 'modal-lg'
});

What are the differences between Visual Studio Code and Visual Studio?

Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.

How to deselect all selected rows in a DataGridView control?

Thanks Cody heres the c# for ref:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }

Calling class staticmethod within the class body?

staticmethod objects apparently have a __func__ attribute storing the original raw function (makes sense that they had to). So this will work:

class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        return 42

    _ANS = stat_func.__func__()  # call the staticmethod

    def method(self):
        ret = Klass.stat_func()
        return ret

As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&P from my Python session):

>>> class Foo(object):
...     @staticmethod
...     def foo():
...         return 3
...     global z
...     z = foo

>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>

Similar sorts of digging in an interactive session (dir is very helpful) can often solve these sorts of question very quickly.

Nested ifelse statement

If you are using any spreadsheet application there is a basic function if() with syntax:

if(<condition>, <yes>, <no>)

Syntax is exactly the same for ifelse() in R:

ifelse(<condition>, <yes>, <no>)

The only difference to if() in spreadsheet application is that R ifelse() is vectorized (takes vectors as input and return vector on output). Consider the following comparison of formulas in spreadsheet application and in R for an example where we would like to compare if a > b and return 1 if yes and 0 if not.

In spreadsheet:

  A  B C
1 3  1 =if(A1 > B1, 1, 0)
2 2  2 =if(A2 > B2, 1, 0)
3 1  3 =if(A3 > B3, 1, 0)

In R:

> a <- 3:1; b <- 1:3
> ifelse(a > b, 1, 0)
[1] 1 0 0

ifelse() can be nested in many ways:

ifelse(<condition>, <yes>, ifelse(<condition>, <yes>, <no>))

ifelse(<condition>, ifelse(<condition>, <yes>, <no>), <no>)

ifelse(<condition>, 
       ifelse(<condition>, <yes>, <no>), 
       ifelse(<condition>, <yes>, <no>)
      )

ifelse(<condition>, <yes>, 
       ifelse(<condition>, <yes>, 
              ifelse(<condition>, <yes>, <no>)
             )
       )

To calculate column idnat2 you can:

df <- read.table(header=TRUE, text="
idnat idbp idnat2
french mainland mainland
french colony overseas
french overseas overseas
foreign foreign foreign"
)

with(df, 
     ifelse(idnat=="french",
       ifelse(idbp %in% c("overseas","colony"),"overseas","mainland"),"foreign")
     )

R Documentation

What is the condition has length > 1 and only the first element will be used? Let's see:

> # What is first condition really testing?
> with(df, idnat=="french")
[1]  TRUE  TRUE  TRUE FALSE
> # This is result of vectorized function - equality of all elements in idnat and 
> # string "french" is tested.
> # Vector of logical values is returned (has the same length as idnat)
> df$idnat2 <- with(df,
+   if(idnat=="french"){
+   idnat2 <- "xxx"
+   }
+   )
Warning message:
In if (idnat == "french") { :
  the condition has length > 1 and only the first element will be used
> # Note that the first element of comparison is TRUE and that's whay we get:
> df
    idnat     idbp idnat2
1  french mainland    xxx
2  french   colony    xxx
3  french overseas    xxx
4 foreign  foreign    xxx
> # There is really logic in it, you have to get used to it

Can I still use if()? Yes, you can, but the syntax is not so cool :)

test <- function(x) {
  if(x=="french") {
    "french"
  } else{
    "not really french"
  }
}

apply(array(df[["idnat"]]),MARGIN=1, FUN=test)

If you are familiar with SQL, you can also use CASE statement in sqldf package.

GitHub Error Message - Permission denied (publickey)

In case you are not accessing your own repository, or cloning inside a cloned repository (using some "git submodule... " commands):

In the home directory of your repository:

$ ls -a

1. Open ".gitmodules", and you will find something like this:

[submodule "XXX"]
    path = XXX
    url = [email protected]:YYY/XXX.git

Change the last line to be the HTTPS of the repository you need to pull:

[submodule "XXX"]
    path = XXX
    https://github.com/YYY/XXX.git

Save ".gitmodules", and run the command for submodules, and ".git" will be updated.

2. Open ".git", go to "config" file, and you will find something like this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/YYY/XXX.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[submodule "XXX"]
    url = [email protected]:YYY/XXX.git

Change the last line to be the HTTPS of the repository you need to pull:

    url = https://github.com/YYY/XXX.git

So, in this case, the main problem is simply with the url. HTTPS of any repository can be found now on top of the repository page.

How can I update npm on Windows?

1. Installing latest npm version

npm install –g npm@latest 

(You can type "npm –version" to check that)


2. Installing Node

a. Install node new version via following URL: https://nodejs.org/en/download/current/ Follow the default choices
b. Remove C:\Users\\AppData\Roaming\NPM
c. Remove C:\Users\\AppData\Roaming\npm-cache


Optionally:

d. (Delete node_modules folder in your current project folder)
e. npm cache verify
f. npm install

Get client IP address via third party web service

    <script type="application/javascript">
            function getip(json){
            alert(json.ip); // alerts the ip address
    }
    </script>

    <script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>

what is the size of an enum type data in C++?

An enum is kind of like a typedef for the int type (kind of).

So the type you've defined there has 12 possible values, however a single variable only ever has one of those values.

Think of it this way, when you define an enum you're basically defining another way to assign an int value.

In the example you've provided, january is another way of saying 0, feb is another way of saying 1, etc until december is another way of saying 11.

UML diagram shapes missing on Visio 2013

Software & Database is usually not in the Standard edition of Visio, only the Pro version.

Try looking here for some templates that will work in standard edition

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:

#!/usr/bin/perl

use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.

=cut

print "Multi Line Comment Example \n";

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

jQuery when element becomes visible

There are no events in JQuery to detect css changes.
Refer here: onHide() type event in jQuery

It is possible:

DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.
Source: Event detect when css property changed using Jquery

Without events, you can use setInterval function, like this:

var maxTime = 5000, // 5 seconds
    startTime = Date.now();

var interval = setInterval(function () {
        if ($('#element').is(':visible')) {
            // visible, do something
            clearInterval(interval);
        } else {
            // still hidden
            if (Date.now() - startTime > maxTime) {
                // hidden even after 'maxTime'. stop checking.
                clearInterval(interval);
            }
        }
    },
    100 // 0.1 second (wait time between checks)
);

Note that using setInterval this way, for keeping a watch, may affect your page's performance.

7th July 2018:
Since this answer is getting some visibility and up-votes recently, here is additional update on detecting css changes:

Mutation Events have been now replaced by the more performance friendly Mutation Observer.

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.

Refer: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Why doesn't Java offer operator overloading?

Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.

At least I think that's the reason. I'm on your side anyway. :)

Backup a single table with its data from a database in sql server 2008

select * into mytable_backup from mytable

Makes a copy of table mytable, and every row in it, called mytable_backup.

In PHP, how do you change the key of an array element?

You can use this function based on array_walk:

function mapToIDs($array, $id_field_name = 'id')
{
    $result = [];
    array_walk($array, 
        function(&$value, $key) use (&$result, $id_field_name)
        {
            $result[$value[$id_field_name]] = $value;
        }
    );
    return $result;
}

$arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];
print_r($arr);
print_r(mapToIDs($arr));

It gives:

Array(
    [0] => Array(
        [id] => one
        [fruit] => apple
    )
    [1] => Array(
        [id] => two
        [fruit] => banana
    )
)

Array(
    [one] => Array(
        [id] => one
        [fruit] => apple
    )
    [two] => Array(
        [id] => two
        [fruit] => banana
    )
)

Why maven settings.xml file is not there?

I also underwent the same issue as Maven doesn't create the settings.xml file under .m2 folder. What I did was the following and it works smoothly without any issues.

Go to the location where you maven was unzipped.

Direct to following path,

\apache-maven-3.0.4\conf\ and copy the settings.xml file and paste it inside your .m2 folder.

Now create a maven project.

Specifying a custom DateTime format when serializing with Json.Net

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

Hello,

I'm using this property when I need set JsonSerializerSettings

Simple PHP Pagination script

 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    }
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!

How to configure log4j.properties for SpringJUnit4ClassRunner?

The new tests you wrote (directly or indirectly) use classes that log using Log4j.

Log4J needs to be configured for this logging to work properly.

Put a log4j.properties (or log4j.xml) file in the root of your test classpath.

It should have some basic configuration such as

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# An alternative logging format:
# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n

An appender outputs to the console by default, but you can also explicitly set the target like this:

log4j.appender.A1.Target=System.out

This will redirect all output in a nice format to the console. More info can be found here in the Log4J manual,

Log4J Logging will then be properly configured and this warning will disappear.

Convert integer to hexadecimal and back again

I created my own solution for converting int to Hex string and back before I found this answer. Not surprisingly, it's considerably faster than the .net solution since there's less code overhead.

        /// <summary>
        /// Convert an integer to a string of hexidecimal numbers.
        /// </summary>
        /// <param name="n">The int to convert to Hex representation</param>
        /// <param name="len">number of digits in the hex string. Pads with leading zeros.</param>
        /// <returns></returns>
        private static String IntToHexString(int n, int len)
        {
            char[] ch = new char[len--];
            for (int i = len; i >= 0; i--)
            {
                ch[len - i] = ByteToHexChar((byte)((uint)(n >> 4 * i) & 15));
            }
            return new String(ch);
        }

        /// <summary>
        /// Convert a byte to a hexidecimal char
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private static char ByteToHexChar(byte b)
        {
            if (b < 0 || b > 15)
                throw new Exception("IntToHexChar: input out of range for Hex value");
            return b < 10 ? (char)(b + 48) : (char)(b + 55);
        }

        /// <summary>
        /// Convert a hexidecimal string to an base 10 integer
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static int HexStringToInt(String str)
        {
            int value = 0;
            for (int i = 0; i < str.Length; i++)
            {
                value += HexCharToInt(str[i]) << ((str.Length - 1 - i) * 4);
            }
            return value;
        }

        /// <summary>
        /// Convert a hex char to it an integer.
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private static int HexCharToInt(char ch)
        {
            if (ch < 48 || (ch > 57 && ch < 65) || ch > 70)
                throw new Exception("HexCharToInt: input out of range for Hex value");
            return (ch < 58) ? ch - 48 : ch - 55;
        }

Timing code:

static void Main(string[] args)
        {
            int num = 3500;
            long start = System.Diagnostics.Stopwatch.GetTimestamp();
            for (int i = 0; i < 2000000; i++)
                if (num != HexStringToInt(IntToHexString(num, 3)))
                    Console.WriteLine(num + " = " + HexStringToInt(IntToHexString(num, 3)));
            long end = System.Diagnostics.Stopwatch.GetTimestamp();
            Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);

            for (int i = 0; i < 2000000; i++)
                if (num != Convert.ToInt32(num.ToString("X3"), 16))
                    Console.WriteLine(i);
            end = System.Diagnostics.Stopwatch.GetTimestamp();
            Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);
            Console.ReadLine(); 
        }

Results:

Digits : MyCode : .Net
1 : 0.21 : 0.45
2 : 0.31 : 0.56
4 : 0.51 : 0.78
6 : 0.70 : 1.02
8 : 0.90 : 1.25

How can I resize an image using Java?

Image Magick has been mentioned. There is a JNI front end project called JMagick. It's not a particularly stable project (and Image Magick itself has been known to change a lot and even break compatibility). That said, we've had good experience using JMagick and a compatible version of Image Magick in a production environment to perform scaling at a high throughput, low latency rate. Speed was substantially better then with an all Java graphics library that we previously tried.

http://www.jmagick.org/index.html

How to align an input tag to the center without specifying the width?

write this:

#siteInfo{text-align:center}
p, input{display:inline-block}

http://jsfiddle.net/XfSz6/

How to find cube root using Python?

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

Here is the full answer for both negative and positive numbers.

>>> 
2.0
-2.0
>>> 

Or here is a one-liner;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Encode String to UTF-8

A quick step-by-step guide how to configure NetBeans default encoding UTF-8. In result NetBeans will create all new files in UTF-8 encoding.

NetBeans default encoding UTF-8 step-by-step guide

  • Go to etc folder in NetBeans installation directory

  • Edit netbeans.conf file

  • Find netbeans_default_options line

  • Add -J-Dfile.encoding=UTF-8 inside quotation marks inside that line

    (example: netbeans_default_options="-J-Dfile.encoding=UTF-8")

  • Restart NetBeans

You set NetBeans default encoding UTF-8.

Your netbeans_default_options may contain additional parameters inside the quotation marks. In such case, add -J-Dfile.encoding=UTF-8 at the end of the string. Separate it with space from other parameters.

Example:

netbeans_default_options="-J-client -J-Xss128m -J-Xms256m -J-XX:PermSize=32m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.dpiaware=true -J-Dsun.zip.disableMemoryMapping=true -J-Dfile.encoding=UTF-8"

here is link for Further Details

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

bootstrap.yml or bootstrap.properties

It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).

From the documentation:

A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.

Note that the bootstrap.yml or bootstrap.properties can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.

Typically it contains two properties:

  • location of the configuration server (spring.cloud.config.uri)
  • name of the application (spring.application.name)

Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.

application.yml or application.properties

Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

The active firewall on the server might be causing this. You can try to (temporarily) turn it off and see if it resolves the issue.

If it is indeed caused by the firewall, you should allegedly be able to resolve it by adding an inbound rule for TCP port 1433 set to allowed, but I personally haven't been able to connect this way.

How to clear textarea on click?

<textarea name="post" id="post" onclick="if(this.value == 'Write Something here..............') this.value='';" onblur="if(this.value == '') this.value='Write Something here..............';" >Write Something here..............</textarea>

Use dynamic variable names in JavaScript

I needed to draw multiple FormData on the fly and object way worked well

var forms = {}

Then in my loops whereever i needed to create a form data i used

forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);

What does the following Oracle error mean: invalid column index

I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:

<security:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"

It turns out that I needed to add: "1 as enabled" to the query:

<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"

Everything worked after that. I believe this could be a bug in the Spring JDBC core package...

How to delete a folder in C++?

Try use system "rmdir -s -q file_to_delte".
This will delete the folder and all files in it.

How to find out what character key is pressed?

Use this one:

function onKeyPress(evt){
  evt = (evt) ? evt : (window.event) ? event : null;
  if (evt)
  {
    var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
    if (charCode == 13) 
        alert('User pressed Enter');
  }
}

Consider defining a bean of type 'service' in your configuration [Spring boot]

Consider defining a bean of type 'moviecruser.repository.MovieRepository' in your configuration.

This type of issue will generate if you did not add correct dependency. Its the same issue I faced but after I found my JPA dependency is not working correctly, so make sure that first dependency is correct or not.

For example:-

The dependency I used:

    <dependency>
       <groupId>org.springframework.data</groupId>      
       <artifactId>spring-data-jpa</artifactId>
    </dependency>

Description (got this exception):-

Parameter 0 of constructor in moviecruser.serviceImple.MovieServiceImpl required a bean of type 'moviecruser.repository.MovieRepository' that could not be found.

Action:

After change dependency:-

    <!-- 
    <dependency>
       <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

Response:-

2019-09-06 23:08:23.202 INFO 7780 -
[main]moviecruser.MovieCruserApplication]:Started MovieCruserApplication in 10.585 seconds (JVM running for 11.357)

How to diff a commit with its parent?

Uses aliases, so doesn't answer your question exactly but I find these useful for doing what you intend...

alias gitdiff-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"

alias gitlog-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"

Rounding a variable to two decimal places C#

Use Math.Round and specify the number of decimal places.

Math.Round(pay,2);

Math.Round Method (Double, Int32)

Rounds a double-precision floating-point value to a specified number of fractional digits.

Or Math.Round Method (Decimal, Int32)

Rounds a decimal value to a specified number of fractional digits.

List of All Folders and Sub-folders

find . -type d > list.txt

Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the . to that other path.

If you want to exclude certain directories, you can filter them out with a negative condition:

find . -type d ! -name "~snapshot" > list.txt

Get git branch name in Jenkins Pipeline/Jenkinsfile

If you have a jenkinsfile for your pipeline, check if you see at execution time your branch name in your environment variables.

You can print them with:

pipeline {
    agent any

    environment {
        DISABLE_AUTH = 'true'
        DB_ENGINE    = 'sqlite'
    }

    stages {
        stage('Build') {
            steps {
                sh 'printenv'
            }
        }
    }
}

However, PR 91 shows that the branch name is only set in certain pipeline configurations:

remove inner shadow of text input

I'm working on firefox. and I was having the same issue, input type text are auto defined something looks like boxshadow inset, but it's not. the you want to change is border... just setting border:0; and you're done.

Getting today's date in YYYY-MM-DD in Python?

You can use strftime:

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'

Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples)

>>> datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
'2021-01-26-16:50:03'

How to enumerate an enum with String type?

(Improvement on Karthik Kumar answer)

This solution is using the compiler to guarantee you won't miss a case.

enum Suit: String {
    case spades = "?"
    case hearts = "?"
    case diamonds = "?"
    case clubs = "?"

    static var enumerate: [Suit] {
        switch Suit.spades {
        // make sure the two lines are identical ^_^
        case        .spades, .hearts, .diamonds, .clubs:
            return [.spades, .hearts, .diamonds, .clubs]
        }
    }
}

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

PUT

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H answer

DELETE

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

How does String substring work in Swift

I'm quite mechanical thinking. Here are the basics...

Swift 4 Swift 5

  let t = "abracadabra"

  let start1 = t.index(t.startIndex, offsetBy:0)
  let   end1 = t.index(t.endIndex, offsetBy:-5)
  let start2 = t.index(t.endIndex, offsetBy:-5)
  let   end2 = t.index(t.endIndex, offsetBy:0)

  let t2 = t[start1 ..< end1]
  let t3 = t[start2 ..< end2]                

  //or a shorter form 

  let t4 = t[..<end1]
  let t5 = t[start2...]

  print("\(t2) \(t3) \(t)")
  print("\(t4) \(t5) \(t)")

  // result:
  // abraca dabra abracadabra

The result is a substring, meaning that it is a part of the original string. To get a full blown separate string just use e.g.

    String(t3)
    String(t4)

This is what I use:

    let mid = t.index(t.endIndex, offsetBy:-5)
    let firstHalf = t[..<mid]
    let secondHalf = t[mid...]

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

I just had the same problem, but none of these answers helped me. I did find the dll on my pc in the location Mostey noted: (C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll), but this is not the one that was referenced in the project I was trying to get building.

The reference in our project in Visual Studio 2012 was pointing to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\. This location was empty for me, but it worked fine for everyone else. It took a number of tries, but I finally tracked down a working installer. I hope this saves others the same hassle!

--> Office Tools Bundle installer for VS2012 <--

This was located on the Office Documentation and Download page. Scroll down to Tools Downloads. There's also currently one for VS2013.

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

How to center content in a bootstrap column?

Bootstrap naming conventions carry styles of their own, col-XS-1 refers to a column being 8.33% of the containing element wide. Your text, would most likely expand far beyond the specified width, and couldn't possible be centered within it. If you wanted it to constrain to the div, you could use something like css word-break.

For centering the content within an element large enough to expand beyond the text, you have two options.

Option 1: HTML Center Tag

<div class="row">
  <div class="col-xs-1 center-block">
    <center>
      <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
    </center>
  </div>
</div>

Option 2: CSS Text-Align

<div class="row">
  <div class="col-xs-1 center-block" style="text-align:center;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

If you wanted everything to constrain to the width of the column

<div class="row">
  <div class="col-xs-1 center-block" style="text-align:center;word-break:break-all;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

UPDATE - Using Bootstrap's text-center class

<div class="row">
  <div class="col-xs-1 center-block text-center">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

FlexBox Method

<div class="row">
  <div class="flexBox" style="
    display: flex;
    flex-flow: row wrap;
    justify-content: center;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

http://jsfiddle.net/usth0kd2/13/

Xcopy Command excluding files and folders

Like Andrew said /exclude parameter of xcopy should be existing file that has list of excludes.

Documentation of xcopy says:

Using /exclude

List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

Example:

xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

and list-of-excluded-files.txt should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:

exclusion.txt

Singleton design pattern vs Singleton beans in Spring container

Spring singleton bean is described as 'per container per bean'. Singleton scope in Spring means that same object at same memory location will be returned to same bean id. If one creates multiple beans of different ids of the same class then container will return different objects to different ids. This is like a key value mapping where key is bean id and value is the bean object in one spring container. Where as Singleton pattern ensures that one and only one instance of a particular class will ever be created per classloader.

How do I send a file as an email attachment using Linux command line?

Send a Plaintext body email with one plaintext attachment with mailx:

(
  /usr/bin/uuencode attachfile.txt myattachedfilename.txt; 
  /usr/bin/echo "Body of text"
) | mailx -s 'Subject' [email protected]

Below is the same command as above, without the newlines

( /usr/bin/uuencode /home/el/attachfile.txt myattachedfilename.txt; /usr/bin/echo "Body of text" ) | mailx -s 'Subject' [email protected]

Make sure you have a file /home/el/attachfile.txt defined with this contents:

<html><body>
Government discriminates against programmers with cruel/unusual 35 year prison
sentences for making the world's information free, while bankers that pilfer 
trillions in citizens assets through systematic inflation get the nod and 
walk free among us.
</body></html>

If you don't have uuencode read this: https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work

On Linux, Send HTML body email with a PDF attachment with sendmail:

Make sure you have ksh installed: yum info ksh

Make sure you have sendmail installed and configured.

Make sure you have uuencode installed and available: https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work

Make a new file called test.sh and put it in your home directory: /home/el

Put the following code in test.sh:

#!/usr/bin/ksh
export MAILFROM="[email protected]"
export MAILTO="[email protected]"
export SUBJECT="Test PDF for Email"
export BODY="/home/el/email_body.htm"
export ATTACH="/home/el/pdf-test.pdf"
export MAILPART=`uuidgen` ## Generates Unique ID
export MAILPART_BODY=`uuidgen` ## Generates Unique ID

(
 echo "From: $MAILFROM"
 echo "To: $MAILTO"
 echo "Subject: $SUBJECT"
 echo "MIME-Version: 1.0"
 echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\""
 echo ""
 echo "--$MAILPART"
 echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\""
 echo ""
 echo "--$MAILPART_BODY"
 echo "Content-Type: text/plain; charset=ISO-8859-1"
 echo "You need to enable HTML option for email"
 echo "--$MAILPART_BODY"
 echo "Content-Type: text/html; charset=ISO-8859-1"
 echo "Content-Disposition: inline"
 cat $BODY
 echo "--$MAILPART_BODY--"

 echo "--$MAILPART"
 echo 'Content-Type: application/pdf; name="'$(basename $ATTACH)'"'
 echo "Content-Transfer-Encoding: uuencode"
 echo 'Content-Disposition: attachment; filename="'$(basename $ATTACH)'"'
 echo ""
 uuencode $ATTACH $(basename $ATTACH)
 echo "--$MAILPART--"
) | /usr/sbin/sendmail $MAILTO

Change the export variables on the top of test.sh to reflect your address and filenames.

Download a test pdf document and put it in /home/el called pdf-test.pdf

Make a file called /home/el/email_body.htm and put this line in it:

<html><body><b>this is some bold text</b></body></html>

Make sure the pdf file has sufficient 755 permissions.

Run the script ./test.sh

Check your email inbox, the text should be in HTML format and the pdf file automatically interpreted as a binary file. Take care not to use this function more than say 15 times in a day, even if you send the emails to yourself, spam filters in gmail can blacklist a domain spewing emails without giving you an option to let them through. And you'll find this no longer works, or it only lets through the attachment, or the email doesn't come through at all. If you have to do a lot of testing on this, spread them out over days or you'll be labelled a spammer and this function won't work any more.

Find and replace with a newline in Visual Studio Code

With VS Code release 1.38 you can press CTRL + Enter in the editor find box to add a newline character.

enter image description here

With VS Code release 1.30 you can type Shift + Enter in the search box to add a newline character without needing to use regex mode.

enter image description here

Since VS Code release 1.3, the regex find has supported newline characters. To use this feature set the find window to regex mode and use \n as the newline character.

Multiline find in VS Code gif

How to transition to a new view controller with code only using Swift

Updated for Swift 3, some of these answers are a bit outdated.

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let vc : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "myStoryboardID") as UIViewController
        self.present(vc, animated: true, completion: nil)    }

How to get $(this) selected option in jQuery?

 $(this).find('option:selected').text();

MySQL, Check if a column exists in a table with SQL

Following is another way of doing it using plain PHP without the information_schema database:

$chkcol = mysql_query("SELECT * FROM `my_table_name` LIMIT 1");
$mycol = mysql_fetch_array($chkcol);
if(!isset($mycol['my_new_column']))
  mysql_query("ALTER TABLE `my_table_name` ADD `my_new_column` BOOL NOT NULL DEFAULT '0'");

Windows Batch: How to add Host-Entries?

Sometime I have to work from home and connect to office through vpn. Internal domain names should be resolved to different IPs at home. There are several names that have to be changed between office and home. For example:

At office, a => 192.168.0.3, b => 192.168.0.52. 
At home, a => 10.6.1.7, b => 10.4.5.23. 

My solution is to create two files: C:\WINDOWS\system32\drivers\etc\hosts-home and C:\WINDOWS\system32\drivers\etc\hosts-office. Each of them contains set of name-to-IP mapping. From Administrator PowerShell, When I work at the office, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-office .\drivers\etc\hosts

When I arrive at home, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-home .\drivers\etc\hosts

Adding a Scrollable JTextArea (Java)

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".

How to make bootstrap 3 fluid layout without horizontal scrollbar

This was introduced in v3.1.0: http://getbootstrap.com/css/#grid-example-fluid

Commit #62736046 added ".container-fluid variation for full-width containers and layouts".

Creating executable files in Linux

It's really not that big of a deal. You could just make a script with the single command:

chmod a+x *.pl

And run the script after creating a perl file. Alternatively, you could open a file with a command like this:

touch filename.pl && chmod a+x filename.pl && vi filename.pl # choose your favorite editor

Fatal error: Class 'SoapClient' not found

For PHP 8:

sudo apt update
sudo apt-get install php8.0-soap

How do I use ROW_NUMBER()?

You can use Row_Number for limit query result.

Example:

SELECT * FROM (
    select row_number() OVER (order by createtime desc) AS ROWINDEX,* 
    from TABLENAME ) TB
WHERE TB.ROWINDEX between 0 and 10

-- With above query, I will get PAGE 1 of results from TABLENAME.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

You should only use &rsquo; if your intention is to make either a closed single quotation mark or an apostrophe. Both of these punctuation marks are curved in shape in most fonts. If your intent is to make a foot mark, go the other route. A foot mark is always a straight vertical mark.

It’s a matter of typography. One way is correct; the other is not.

AngularJS - difference between pristine/dirty and touched/untouched

$pristine/$dirty tells you whether the user actually changed anything, while $touched/$untouched tells you whether the user has merely been there/visited.

This is really useful for validation. The reason for $dirty was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.

With Angular 1.3 and ng-touched, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.

Here's a CodePen that shows the difference in behavior.

sendUserActionEvent() is null

Even i face similar problem after I did some modification in code related to Cursor.

public boolean onContextItemSelected(MenuItem item) 
{
        AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
        Cursor c = (Cursor)adapter.getItem(info.position);
        long id = c.getLong(...);
        String tempCity = c.getString(...);
            //c.close();
...
}

After i commented out //c.close(); It is working fine. Try out at your end and update Initial setup is as... I have a list view in Fragment, and trying to delete and item from list via contextMenu.

Detect the Enter key in a text input field

The solution that work for me is the following

$("#element").addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // do something
    }
});

What is the difference between association, aggregation and composition?

I think this link will do your homework: http://ootips.org/uml-hasa.html

To understand the terms I remember an example in my early programming days:

If you have a 'chess board' object that contains 'box' objects that is composition because if the 'chess board' is deleted there is no reason for the boxes to exist anymore.

If you have a 'square' object that have a 'color' object and the square gets deleted the 'color' object may still exist, that is aggregation

Both of them are associations, the main difference is conceptual

What's the difference between fill_parent and wrap_content?

Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.

fill_parent (deprecated and renamed MATCH_PARENT in API Level 8 and higher)

Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill.

Setting a top level layout or control to fill_parent will force it to take up the whole screen.

wrap_content

Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.

It's roughly the equivalent of setting a Windows Form Control's Autosize property to True.

Online Documentation

There's some details in the Android code documentation here.

Run/install/debug Android applications over Wi-Fi?

first you shold connect your device with usb to pc after that run cmd and drag and drop adb.exe that is in sdk/platform-tools path and write below code :

    ....\Sdk\platform-tools\adb.exe devices

    .....\Sdk\platform-tools\adb.exe tcpip 5555

    .....\Sdk\platform-tools\adb.exe connect Ip address:5555

SOAP or REST for Web Services?

I think that both has its own place. In my opinion:

SOAP: A better choice for integration between legacy/critical systems and a web/web-service system, on the foundation layer, where WS-* make sense (security, policy, etc.).

RESTful: A better choice for integration between websites, with public API, on the TOP of layer (VIEW, ie, javascripts taking calls to URIs).

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

To view the differences:

git difftool --dir-diff master origin/master

This will display the changes or differences between the two branches. In araxis (My favorite) it displays it in a folder diff style. Showing each of the changed files. I can then click on a file to see the details of the changes in the file.

How can I check the current status of the GPS receiver?

Setting time interval to check for fix is not a good choice.. i noticed that onLocationChanged is not called if you are not moving.. what is understandable since location is not changing :)

Better way would be for example:

  • check interval to last location received (in gpsStatusChanged)
  • if that interval is more than 15s set variable: long_interval = true
  • remove the location listener and add it again, usually then you get updated position if location really is available, if not - you probably lost location
  • in onLocationChanged you just set long_interval to false..

Custom ImageView with drop shadow

I believe this answer from UIFuel

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

     <!-- Drop Shadow Stack -->
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <!-- Background -->
    <item>
    <shape>
            <solid android:color="@color/white" />
        <corners android:radius="3dp" />
    </shape>
    </item>
</layer-list>

Why does overflow:hidden not work in a <td>?

That's just the way TD's are. I believe It may be because the TD element's 'display' property is inherently set to 'table-cell' rather than 'block'.

In your case, the alternative may be to wrap the contents of the TD in a DIV and apply width and overflow to the DIV.

<td style="border: solid green 1px; width:200px;">
    <div style="width:200px; overflow:hidden;">
        This_is_a_terrible_example_of_thinking_outside_the_box.
    </div>
</td>

There may be some padding or cellpadding issues to deal with, and you're better off removing the inline styles and using external css instead, but this should be a start.

How to make scipy.interpolate give an extrapolated result beyond the input range?

The below code gives you the simple extrapolation module. k is the value to which the data set y has to be extrapolated based on the data set x. The numpy module is required.

 def extrapol(k,x,y):
        xm=np.mean(x);
        ym=np.mean(y);
        sumnr=0;
        sumdr=0;
        length=len(x);
        for i in range(0,length):
            sumnr=sumnr+((x[i]-xm)*(y[i]-ym));
            sumdr=sumdr+((x[i]-xm)*(x[i]-xm));

        m=sumnr/sumdr;
        c=ym-(m*xm);
        return((m*k)+c)

How do you convert epoch time in C#?

In case you need to convert a timeval struct (seconds, microseconds) containing UNIX time to DateTime without losing precision, this is how:

DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private DateTime UnixTimeToDateTime(Timeval unixTime)
{
    return _epochTime.AddTicks(
        unixTime.Seconds * TimeSpan.TicksPerSecond +
        unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
}

Truncate Decimal number not Round Off

Try this

double d = 2.22912312515;
int demention = 3;
double truncate = Math.Truncate(d) + Math.Truncate((d - Math.Truncate(d)) * Math.Pow(10.0, demention)) / Math.Pow(10.0, demention);

How to print Unicode character in C++?

In Linux, I can just do:

std::cout << "?";

I just copy-pasted characters from here and it didn't fail for at least the random sample that I tried on.

psql: FATAL: database "<user>" does not exist

Try using-

psql -d postgres

I was also facing the same issue when I ran psql

How do I parse command line arguments in Bash?

getopt()/getopts() is a good option. Copied from here:

The simple use of "getopt" is shown in this mini-script:

#!/bin/bash
echo "Before getopt"
for i
do
  echo $i
done
args=`getopt abc:d $*`
set -- $args
echo "After getopt"
for i
do
  echo "-->$i"
done

What we have said is that any of -a, -b, -c or -d will be allowed, but that -c is followed by an argument (the "c:" says that).

If we call this "g" and try it out:

bash-2.05a$ ./g -abc foo
Before getopt
-abc
foo
After getopt
-->-a
-->-b
-->-c
-->foo
-->--

We start with two arguments, and "getopt" breaks apart the options and puts each in its own argument. It also added "--".

Count number of occurences for each unique value

length(unique(df$col)) is the most simple way I can see.

How to convert 2D float numpy array to 2D int numpy array?

If you're not sure your input is going to be a Numpy array, you can use asarray with dtype=int instead of astype:

>>> np.asarray([1,2,3,4], dtype=int)
array([1, 2, 3, 4])

If the input array already has the correct dtype, asarray avoids the array copy while astype does not (unless you specify copy=False):

>>> a = np.array([1,2,3,4])
>>> a is np.asarray(a)  # no copy :)
True
>>> a is a.astype(int)  # copy :(
False
>>> a is a.astype(int, copy=False)  # no copy :)
True

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

Why is conversion from string constant to 'char*' valid in C but invalid in C++

Up through C++03, your first example was valid, but used a deprecated implicit conversion--a string literal should be treated as being of type char const *, since you can't modify its contents (without causing undefined behavior).

As of C++11, the implicit conversion that had been deprecated was officially removed, so code that depends on it (like your first example) should no longer compile.

You've noted one way to allow the code to compile: although the implicit conversion has been removed, an explicit conversion still works, so you can add a cast. I would not, however, consider this "fixing" the code.

Truly fixing the code requires changing the type of the pointer to the correct type:

char const *p = "abc"; // valid and safe in either C or C++.

As to why it was allowed in C++ (and still is in C): simply because there's a lot of existing code that depends on that implicit conversion, and breaking that code (at least without some official warning) apparently seemed to the standard committees like a bad idea.

Replace \n with <br />

The Problem is When you denote '\n' in the replace() call , '\n' is treated as a String length=4 made out of ' \ n '
To get rid of this, use ascii notation. http://www.asciitable.com/

example:

newLine = chr(10)
thatLine=thatLine.replace(newLine , '<br />')

print(thatLine) #python3

print thatLine #python2 .

how to break the _.each function in underscore.js

You can have a look to _.some instead of _.each. _.some stops traversing the list once a predicate is true. Result(s) can be stored in an external variable.

_.some([1, 2, 3], function(v) {
    if (v == 2) return true;
})

See http://underscorejs.org/#some

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

What is the purpose of the single underscore "_" variable in Python?

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

how to change onclick event with jquery?

@Amirali

console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");

throws:

Uncaught TypeError: document.getElementById(...).attribute is not a function

in chrome.

Element exists and is dumped in console;

How to tell if a string contains a certain character in JavaScript?

String's search function is useful too. It searches for a character as well as a sub_string in a given string.

'apple'.search('pl') returns 2

'apple'.search('x') return -1

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

To complete @cpu-100 answer,

in case you don't want to enable/use web interface, you can create a new credentials using command line like below and use it in your code to connect to RabbitMQ.

$ rabbitmqctl add_user YOUR_USERNAME YOUR_PASSWORD
$ rabbitmqctl set_user_tags YOUR_USERNAME administrator
$ rabbitmqctl set_permissions -p / YOUR_USERNAME ".*" ".*" ".*"

When is std::weak_ptr useful?

Another answer, hopefully simpler. (for fellow googlers)

Suppose you have Team and Member objects.

Obviously it's a relationship : the Team object will have pointers to its Members. And it's likely that the members will also have a back pointer to their Team object.

Then you have a dependency cycle. If you use shared_ptr, objects will no longer be automatically freed when you abandon reference on them, because they reference each other in a cyclic way. This is a memory leak.

You break this by using weak_ptr. The "owner" typically use shared_ptr and the "owned" use a weak_ptr to its parent, and convert it temporarily to shared_ptr when it needs access to its parent.

Store a weak ptr :

weak_ptr<Parent> parentWeakPtr_ = parentSharedPtr; // automatic conversion to weak from shared

then use it when needed

shared_ptr<Parent> tempParentSharedPtr = parentWeakPtr_.lock(); // on the stack, from the weak ptr
if( !tempParentSharedPtr ) {
  // yes, it may fail if the parent was freed since we stored weak_ptr
} else {
  // do stuff
}
// tempParentSharedPtr is released when it goes out of scope

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Here is a way to do it without adding an ID to the form elements.

<form method="post">
    ...
    <select name="List">
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
    <select name="List">
        <option value="3">Test3</option>
        <option value="4">Test4</option>
    </select>
    ...
</form>

public ActionResult OrderProcessor()
{
    string[] ids = Request.Form.GetValues("List");
}

Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:

public class OrderModel
{
    public string[] List { get; set; }
}

public ActionResult OrderProcessor(OrderModel model)
{
    string[] ids = model.List;
}

Hope this helps.

Are lists thread-safe?

To clarify a point in Thomas' excellent answer, it should be mentioned that append() is thread safe.

This is because there is no concern that data being read will be in the same place once we go to write to it. The append() operation does not read data, it only writes data to the list.

How to apply slide animation between two activities in Android?

Kotlin example:

    private val SPLASH_DELAY: Long = 1000

    internal val mRunnable: Runnable = Runnable {
        if (!isFinishing) {
            val intent = Intent(applicationContext, HomeActivity::class.java)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
            finish()
        }
    }


   private fun navigateToHomeScreen() {
        //Initialize the Handler
        mDelayHandler = Handler()

        //Navigate with delay
        mDelayHandler!!.postDelayed(mRunnable, SPLASH_DELAY)

    }

    public override fun onDestroy() {

        if (mDelayHandler != null) {
            mDelayHandler!!.removeCallbacks(mRunnable)
        }

        super.onDestroy()
    }

put animations in anim folder:

slide_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="@android:integer/config_longAnimTime"
        android:fromXDelta="100%p"
        android:toXDelta="0%p">
</translate>

slide_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="@android:integer/config_longAnimTime"
        android:fromXDelta="0%p"
        android:toXDelta="-100%p">
</translate>

USAGE

  navigateToHomeScreen();

Add custom header in HttpWebRequest

You can add values to the HttpWebRequest.Headers collection.

According to MSDN, it should be supported in windows phone: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.95%29.aspx

HTML Input - already filled in text

TO give the prefill value in HTML Side as below:

HTML:

<input type="text" id="abc" value="any value">

JQUERY:

$(document).ready(function ()
 {
  $("#abc").val('any value');
 });

How to start an application using android ADB tools?

Or, you could use this:

adb shell am start -n com.package.name/.ActivityName

How do I create a readable diff of two spreadsheets using git diff?

Diff Doc may be what you're looking for.

  • Compare documents of MS Word (DOC, DOCX etc), Excel, PDF, Rich Text (RTF), Text, HTML, XML, PowerPoint, or Wordperfect and retain formatting
  • Choose any portion of any document (file) and compare it against any portion of the same or different document (file).

Jenkins "Console Output" log location in filesystem

I found the console output of my job in the browser at the following location:

http://[Jenkins URL]/job/[Job Name]/default/[Build Number]/console

Swift Open Link in Safari

Swift 3 & IOS 10.2

UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)

Swift 3 & IOS 10.2

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

Is there a function to copy an array in C/C++?

As others have mentioned, in C you would use memcpy. Note however that this does a raw memory copy, so if your data structures have pointer to themselves or to each other, the pointers in the copy will still point to the original objects.

In C++ you can also use memcpy if your array members are POD (that is, essentially types which you could also have used unchanged in C), but in general, memcpy will not be allowed. As others mentioned, the function to use is std::copy.

Having said that, in C++ you rarely should use raw arrays. Instead you should either use one of the standard containers (std::vector is the closest to a built-in array, and also I think the closest to Java arrays — closer than plain C++ arrays, indeed —, but std::deque or std::list may be more appropriate in some cases) or, if you use C++11, std::array which is very close to built-in arrays, but with value semantics like other C++ types. All the types I mentioned here can be copied by assignment or copy construction. Moreover, you can "cross-copy" from opne to another (and even from a built-in array) using iterator syntax.

This gives an overview of the possibilities (I assume all relevant headers have been included):

int main()
{
  // This works in C and C++
  int a[] = { 1, 2, 3, 4 };
  int b[4];
  memcpy(b, a, 4*sizeof(int)); // int is a POD

  // This is the preferred method to copy raw arrays in C++ and works with all types that can be copied:
  std::copy(a, a+4, b);

  // In C++11, you can also use this:
  std::copy(std::begin(a), std::end(a), std::begin(b));

  // use of vectors
  std::vector<int> va(a, a+4); // copies the content of a into the vector
  std::vector<int> vb = va;    // vb is a copy of va

  // this initialization is only valid in C++11:
  std::vector<int> vc { 5, 6, 7, 8 }; // note: no equal sign!

  // assign vc to vb (valid in all standardized versions of C++)
  vb = vc;

  //alternative assignment, works also if both container types are different
  vb.assign(vc.begin(), vc.end());

  std::vector<int> vd; // an *empty* vector

  // you also can use std::copy with vectors
  // Since vd is empty, we need a `back_inserter`, to create new elements:
  std::copy(va.begin(), va.end(), std::back_inserter(vd));

  // copy from array a to vector vd:
  // now vd already contains four elements, so this new copy doesn't need to
  // create elements, we just overwrite the existing ones.
  std::copy(a, a+4, vd.begin());

  // C++11 only: Define a `std::array`:
  std::array<int, 4> sa = { 9, 10, 11, 12 };

  // create a copy:
  std::array<int, 4> sb = sa;

  // assign the array:
  sb = sa;
}

How to embed an autoplaying YouTube video in an iframe?

Nowadays I include a new attribute "allow" on iframe tag, for example:

allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"

The final code is:

<iframe src="https://www.youtube.com/embed/[VIDEO-CODE]?autoplay=1" 
frameborder="0" style="width: 100%; height: 100%;"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>

Difference between Hive internal tables and external tables?

Internal tables are useful if you want Hive to manage the complete lifecycle of your data including the deletion, whereas external tables are useful when the files are being used outside of Hive.

Docker - Cannot remove dead container

  1. For Deleting all dead container docker rm -f $(docker ps --all -q -f status=dead)

  2. For deleting all exited container docker rm -f $(docker ps --all -q -f status=exited)

As I have -f is necessary

Error: Cannot invoke an expression whose type lacks a call signature

I think what you want is:

abstract class Component {
  public deps: any = {};
  public props: any = {};

  public makePropSetter<T>(prop: string): (val: T) => T {
    return function(val) {
      this.props[prop] = val
      return val
    }
  }
}

class Post extends Component {
  public toggleBody: (val: boolean) => boolean;

  constructor () {
    super()
    this.toggleBody = this.makePropSetter<boolean>('showFullBody')
  }

  showMore (): boolean {
    return this.toggleBody(true)
  }

  showLess (): boolean {
    return this.toggleBody(false)
  }
}

The important change is in setProp (i.e., makePropSetter in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.

The <T> on makePropSetter allows you to lock that function in to a specific type. The <boolean> in the subclass's constructor is actually optional. Since you're assigning to toggleBody, and that already has the type fully specified, the TS compiler will be able to work it out on its own.

Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody respect that same signature.

How can I return NULL from a generic method in C#?

Two options:

  • Return default(T) which means you'll return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char, etc. (Default values table (C# Reference))
  • Restrict T to be a reference type with the where T : class constraint and then return null as normal

How does DateTime.Now.Ticks exactly work?

I had a similar problem.

I would also look at this answer: Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?.

About half-way down is an answer by "Robert P" with some extension functions I found useful.

How to add a changed file to an older (not last) commit in Git

To "fix" an old commit with a small change, without changing the commit message of the old commit, where OLDCOMMIT is something like 091b73a:

git add <my fixed files>
git commit --fixup=OLDCOMMIT
git rebase --interactive --autosquash OLDCOMMIT^

You can also use git commit --squash=OLDCOMMIT to edit the old commit message during rebase.

See documentation for git commit and git rebase. As always, when rewriting git history, you should only fixup or squash commits you have not yet published to anyone else (including random internet users and build servers).


Detailed explanation

  • git commit --fixup=OLDCOMMIT copies the OLDCOMMIT commit message and automatically prefixes fixup! so it can be put in the correct order during interactive rebase. (--squash=OLDCOMMIT does the same but prefixes squash!.)
  • git rebase --interactive will bring up a text editor (which can be configured) to confirm (or edit) the rebase instruction sequence. There is info for rebase instruction changes in the file; just save and quit the editor (:wq in vim) to continue with the rebase.
  • --autosquash will automatically put any --fixup=OLDCOMMIT commits in the correct order. Note that --autosquash is only valid when the --interactive option is used.
  • The ^ in OLDCOMMIT^ means it's a reference to the commit just before OLDCOMMIT. (OLDCOMMIT^ is the first parent of OLDCOMMIT.)

Optional automation

The above steps are good for verification and/or modifying the rebase instruction sequence, but it's also possible to skip/automate the interactive rebase text editor by:

The given key was not present in the dictionary. Which key?

This exception is thrown when you try to index to something that isn't there, for example:

Dictionary<String, String> test = new Dictionary<String,String>();
test.Add("Key1","Value1");
string error = test["Key2"];

Often times, something like an object will be the key, which undoubtedly makes it harder to get. However, you can always write the following (or even wrap it up in an extension method):

if (test.ContainsKey(myKey))
   return test[myKey];
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Or more efficient (thanks to @ScottChamberlain)

T retValue;
if (test.TryGetValue(myKey, out retValue))
    return retValue;
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Microsoft chose not to do this, probably because it would be useless when used on most objects. Its simple enough to do yourself, so just roll your own!

How to move columns in a MySQL table?

I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';

SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS c2 
    WHERE c2.TABLE_NAME = t.TABLE_NAME);

How can I output the value of an enum class in C++11

It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).

The solution is to write a generic operator<< function which will work for any scoped enum. The solution employs SFINAE via std::enable_if and is as follows.

#include <iostream>
#include <type_traits>

// Scoped enum
enum class Color
{
    Red,
    Green,
    Blue
};

// Unscoped enum
enum Orientation
{
    Horizontal,
    Vertical
};

// Another scoped enum
enum class ExecStatus
{
    Idle,
    Started,
    Running
};

template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
    return stream << static_cast<typename std::underlying_type<T>::type>(e);
}

int main()
{
    std::cout << Color::Blue << "\n";
    std::cout << Vertical << "\n";
    std::cout << ExecStatus::Running << "\n";
    return 0;
}

How do I print my Java object without getting "SomeType@2f92e0f4"?

By default, every Object in Java has the toString() method which outputs the ObjectType@HashCode.

If you want more meaningfull information then you need to override the toString() method in your class.

public class Person {
  private String name;

  // constructor and getter/setter omitted

  // overridding toString() to print name
  public String toString(){
     return name;  
  }
}

Now when you print the person object using System.out.prtinln(personObj); it will print the name of the person instead of the classname and hashcode.

In your second case when you are trying to print the array, it prints [Lcom.foo.Person;@28a418fc the Array type and it's hashcode.


If you want to print the person names, there are many ways.

You could write your own function that iterates each person and prints

void printPersonArray(Person[] persons){
    for(Person person: persons){
        System.out.println(person);
    }
}

You could print it using Arrays.toString(). This seems the simplest to me.

 System.out.println(Arrays.toString(persons));
 System.out.println(Arrays.deepToString(persons));  // for nested arrays  

You could print it the java 8 way (using streams and method reference).

 Arrays.stream(persons).forEach(System.out::println);

There might be other ways as well. Hope this helps. :)

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

How do I install the OpenSSL libraries on Ubuntu?

How could I have figured that out for myself (other than asking this question here)? Can I somehow tell apt-get to list all packages, and grep for ssl? Or do I need to know the "lib*-dev" naming convention?

If you're linking with -lfoo then the library is likely libfoo.so. The library itself is probably part of the libfoo package, and the headers are in the libfoo-dev package as you've discovered.

Some people use the GUI "synaptic" app (sudo synaptic) to (locate and) install packages, but I prefer to use the command line. One thing that makes it easier to find the right package from the command line is the fact that apt-get supports bash completion.

Try typing sudo apt-get install libssl and then hit tab to see a list of matching package names (which can help when you need to select the correct version of a package that has multiple versions or other variations available).

Bash completion is actually very useful... for example, you can also get a list of commands that apt-get supports by typing sudo apt-get and then hitting tab.

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Find a file with a certain extension in folder

The method below returns only the files with certain extension (eg: file with .txt but not .txt1)

public static IEnumerable<string> GetFilesByExtension(string directoryPath, string extension, SearchOption searchOption)
    {
        return
            Directory.EnumerateFiles(directoryPath, "*" + extension, searchOption)
                .Where(x => string.Equals(Path.GetExtension(x), extension, StringComparison.InvariantCultureIgnoreCase));
    }