Programs & Examples On #Domain masking

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

How can a windows service programmatically restart itself?

It would depend on why you want it to restart itself.

If you are just looking for a way to have the service clean itself out periodically then you could have a timer running in the service that periodically causes a purge routine.

If you are looking for a way to restart on failure - the service host itself can provide that ability when it is setup.

So why do you need to restart the server? What are you trying to achieve?

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

Function to convert timestamp to human date in javascript

To calculate date in timestamp from the given date

//To get the timestamp date from normal date: In format - 1560105000000

//input date can be in format : "2019-06-09T18:30:00.000Z"

this.calculateDateInTimestamp = function (inputDate) {
    var date = new Date(inputDate);
    return date.getTime();
}

output : 1560018600000

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

Adding to @behzad.nouri 's answer - we can create a helper routine to handle this common scenario:

def csvDf(dat,**kwargs): 
  from numpy import array
  data = array(dat)
  if data is None or len(data)==0 or len(data[0])==0:
    return None
  else:
    return pd.DataFrame(data[1:,1:],index=data[1:,0],columns=data[0,1:],**kwargs)

Let's try it out:

data = [['','a','b','c'],['row1','row1cola','row1colb','row1colc'],
     ['row2','row2cola','row2colb','row2colc'],['row3','row3cola','row3colb','row3colc']]
csvDf(data)

In [61]: csvDf(data)
Out[61]:
             a         b         c
row1  row1cola  row1colb  row1colc
row2  row2cola  row2colb  row2colc
row3  row3cola  row3colb  row3colc

Cloud Firestore collection count

Took me a while to get this working based on some of the answers above, so I thought I'd share it for others to use. I hope it's useful.

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.countDocumentsChange = functions.firestore.document('library/{categoryId}/documents/{documentId}').onWrite((change, context) => {

    const categoryId = context.params.categoryId;
    const categoryRef = db.collection('library').doc(categoryId)
    let FieldValue = require('firebase-admin').firestore.FieldValue;

    if (!change.before.exists) {

        // new document created : add one to count
        categoryRef.update({numberOfDocs: FieldValue.increment(1)});
        console.log("%s numberOfDocs incremented by 1", categoryId);

    } else if (change.before.exists && change.after.exists) {

        // updating existing document : Do nothing

    } else if (!change.after.exists) {

        // deleting document : subtract one from count
        categoryRef.update({numberOfDocs: FieldValue.increment(-1)});
        console.log("%s numberOfDocs decremented by 1", categoryId);

    }

    return 0;
});

SQL Server copy all rows from one table into another i.e duplicate table

Either you can use RAW SQL:

INSERT INTO DEST_TABLE (Field1, Field2) 
SELECT Source_Field1, Source_Field2 
FROM SOURCE_TABLE

Or use the wizard:

  1. Right Click on the Database -> Tasks -> Export Data
  2. Select the source/target Database
  3. Select source/target table and fields
  4. Copy the data

Then execute:

TRUNCATE TABLE SOURCE_TABLE

What is the equivalent of "!=" in Excel VBA?

Try to use <> instead of !=.

PHPUnit assert that an exception was thrown?

You can use assertException extension to assert more than one exception during one test execution.

Insert method into your TestCase and use:

public function testSomething()
{
    $test = function() {
        // some code that has to throw an exception
    };
    $this->assertException( $test, 'InvalidArgumentException', 100, 'expected message' );
}

I also made a trait for lovers of nice code..

What's the difference between primitive and reference types?

Primitive data type

The primitive data type is a basic type provided by a programming language as a basic building block. So it's predefined data types. A primitive type has always a value. It storing simple value.

It specifies the size and type of variable values, so the size of a primitive type depends on the data type and it has no additional methods.

And these are reserved keywords in the language. So we can't use these names as variable, class or method name. A primitive type starts with a lowercase letter. When declaring the primitive types we don't need to allocate memory. (memory is allocated and released by JRE-Java Runtime Environment in Java)

8 primitive data types in Java

+================+=========+===================================================================================+
| Primitive type | Size    | Description                                                                       |
+================+=========+===================================================================================+
| byte           | 1 byte  | Stores whole numbers from -128 to 127                                             |
+----------------+---------+-----------------------------------------------------------------------------------+
| short          | 2 bytes | Stores whole numbers from -32,768 to 32,767                                       |
+----------------+---------+-----------------------------------------------------------------------------------+
| int            | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647                         |
+----------------+---------+-----------------------------------------------------------------------------------+
| long           | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
+----------------+---------+-----------------------------------------------------------------------------------+
| float          | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits           |
+----------------+---------+-----------------------------------------------------------------------------------+
| double         | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits               |
+----------------+---------+-----------------------------------------------------------------------------------+
| char           | 2 bytes | Stores a single character/letter or ASCII values                                  |
+----------------+---------+-----------------------------------------------------------------------------------+
| boolean        | 1 bit   | Stores true or false values                                                       |
+----------------+---------+-----------------------------------------------------------------------------------+

Reference data type

Reference data type refers to objects. Most of these types are not defined by programming language(except for String, arrays in JAVA). Reference types of value can be null. It storing an address of the object it refers to. Reference or non-primitive data types have all the same size. and reference types can be used to call methods to perform certain operations.

when declaring the reference type need to allocate memory. In Java, we used new keyword to allocate memory, or alternatively, call a factory method.

Example:

List< String > strings = new ArrayList<>() ;  // Calling `new`  to instantiate an object and thereby allocate memory.

Point point = Point(1,2) ;           // Calling a factory method.

What is the easiest way to encrypt a password when I save it to the registry?

Tom Scott got it right in his coverage of how (not) to store passwords, on Computerphile.

https://www.youtube.com/watch?v=8ZtInClXe1Q

  1. If you can at all avoid it, do not try to store passwords yourself. Use a separate, pre-established, trustworthy user authentication platform (e.g.: OAuth providers, you company's Active Directory domain, etc.) instead.

  2. If you must store passwords, don't follow any of the guidance here. At least, not without also consulting more recent and reputable publications applicable to your language of choice.

There's certainly a lot of smart people here, and probably even some good guidance given. But the odds are strong that, by the time you read this, all of the answers here (including this one) will already be outdated.


The right way to store passwords changes over time.

Probably more frequently than some people change their underwear.


All that said, here's some general guidance that will hopefully remain useful for awhile.

  1. Don't encrypt passwords. Any storage method that allows recovery of the stored data is inherently insecure for the purpose of holding passwords - all forms of encryption included.
  2. Process the passwords exactly as entered by the user during the creation process. Anything you do to the password before sending it to the cryptography module will probably just weaken it. Doing any of the following also just adds complexity to the password storage & verification process, which could cause other problems (perhaps even introduce vulnerabilities) down the road.

    • Don't convert to all-uppercase/all-lowercase.
    • Don't remove whitespace.
    • Don't strip unacceptable characters or strings.
    • Don't change the text encoding.
    • Don't do any character or string substitutions.
    • Don't truncate passwords of any length.
  3. Reject creation of any passwords that can't be stored without modification. Reinforcing the above. If there's some reason your password storage mechanism can't appropriately handle certain characters, whitespaces, strings, or password lengths, then return an error and let the user know about the system's limitations so they can retry with a password that fits within them. For a better user experience, make a list of those limitations accessible to the user up-front. Don't even worry about, let alone bother, hiding the list from attackers - they'll figure it out easily enough on their own anyway.

  4. Use a long, random, and unique salt for each account. No two accounts' passwords should ever look the same in storage, even if the passwords are actually identical.
  5. Use slow and cryptographically strong hashing algorithms that are designed for use with passwords. MD5 is certainly out. SHA-1/SHA-2 are no-go. But I'm not going to tell you what you should use here either. (See the first #2 bullet in this post.)
  6. Iterate as much as you can tolerate. While your system might have better things to do with its processor cycles than hash passwords all day, the people who will be cracking your passwords have systems that don't. Make it as hard on them as you can, without quite making it "too hard" on you.

Most importantly...

Don't just listen to anyone here.

Go look up a reputable and very recent publication on the proper methods of password storage for your language of choice. Actually, you should find multiple recent publications from multiple separate sources that are in agreement before you settle on one method.

It's extremely possible that everything that everyone here (myself included) has said has already been superseded by better technologies or rendered insecure by newly developed attack methods. Go find something that's more probably not.

How to set ssh timeout?

try this:

timeout 5 ssh user@ip

timeout executes the ssh command (with args) and sends a SIGTERM if ssh doesn't return after 5 second. for more details about timeout, read this document: http://man7.org/linux/man-pages/man1/timeout.1.html

or you can use the param of ssh:

ssh -o ConnectTimeout=3 user@ip

How to install XNA game studio on Visual Studio 2012?

I found another issue, for some reason if the extensions are cached in the local AppData folder, the XNA extensions never get loaded.

You need to remove the files extensionSdks.en-US.cache and extensions.en-US.cache from the %LocalAppData%\Microsoft\VisualStudio\11.0\Extensions folder. These files are rebuilt the next time you launch

If you need access to the Visual Studio startup log to debug what's happening, run devenv.exe /log command from the C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE directory (assuming you are on a 64 bit machine). The log file generated is located here:

%AppData%\Microsoft\VisualStudio\11.0\ActivityLog.xml

What is stdClass in PHP?

Please bear in mind that 2 empty stdClasses are not strictly equal. This is very important when writing mockery expectations.

php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >

How to set time delay in javascript

ES-6 Solution

Below is a sample code which uses aync/await to have an actual delay.

There are many constraints and this may not be useful, but just posting here for fun..

_x000D_
_x000D_
function delay(delayInms) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(2);
    }, delayInms);
  });
}

async function sample() {
  console.log('a');
  console.log('waiting...')
  let delayres = await delay(3000);
  console.log('b');
}
sample();
_x000D_
_x000D_
_x000D_

img tag displays wrong orientation

This answer builds on bsap's answer using Exif-JS , but doesn't rely on jQuery and is fairly compatible even with older browsers. The following are example html and js files:

rotate.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">
  <html>
  <head>
    <style>
      .rotate90 {
       -webkit-transform: rotate(90deg);
       -moz-transform: rotate(90deg);
       -o-transform: rotate(90deg);
       -ms-transform: rotate(90deg);
       transform: rotate(90deg);
      }
      .rotate180 {
       -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
       -o-transform: rotate(180deg);
       -ms-transform: rotate(180deg);
       transform: rotate(180deg);
      }
      .rotate270 {
       -webkit-transform: rotate(270deg);
       -moz-transform: rotate(270deg);
       -o-transform: rotate(270deg);
       -ms-transform: rotate(270deg);
       transform: rotate(270deg);
      }
    </style>
  </head>
  <body>
    <img src="pic/pic03.jpg" width="200" alt="Cat 1" id="campic" class="camview">
    <script type="text/javascript" src="exif.js"></script>
    <script type="text/javascript" src="rotate.js"></script>
  </body>
  </html>

rotate.js:

window.onload=getExif;
var newimg = document.getElementById('campic');
function getExif() {
    EXIF.getData(newimg, function() {
            var orientation = EXIF.getTag(this, "Orientation");
            if(orientation == 6) {
                newimg.className = "camview rotate90";
            } else if(orientation == 8) {
                newimg.className = "camview rotate270";
            } else if(orientation == 3) {
                newimg.className = "camview rotate180";
            }
        });
};

Chrome / Safari not filling 100% height of flex parent

For Mobile Safari There is a Browser fix. you need to add -webkit-box for iOS devices.

Ex.

display: flex;
display: -webkit-box;
flex-direction: column;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
align-items: stretch;

if you're using align-items: stretch; property for parent element, remove the height : 100% from the child element.

What are all the escape characters?

Java Escape Sequences:

\u{0000-FFFF}  /* Unicode [Basic Multilingual Plane only, see below] hex value 
                  does not handle unicode values higher than 0xFFFF (65535),
                  the high surrogate has to be separate: \uD852\uDF62
                  Four hex characters only (no variable width) */
\b             /* \u0008: backspace (BS) */
\t             /* \u0009: horizontal tab (HT) */
\n             /* \u000a: linefeed (LF) */
\f             /* \u000c: form feed (FF) */
\r             /* \u000d: carriage return (CR) */
\"             /* \u0022: double quote (") */
\'             /* \u0027: single quote (') */
\\             /* \u005c: backslash (\) */
\{0-377}       /* \u0000 to \u00ff: from octal value 
                  1 to 3 octal digits (variable width) */

The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F / &#77887; and would have to be broken into "\uD80C\uDC3F" (UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F".

LAST_INSERT_ID() MySQL

For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;

CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title ); 
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1); 
END

And you can use it...

SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;

Swift how to sort array of custom objects by property value

Sort using KeyPath

you can sort by KeyPath like this:

myArray.sorted(by: \.fileName, <) /* using `<` for ascending sorting */

By implementing this little helpful extension.

extension Collection{
    func sorted<Value: Comparable>(
        by keyPath: KeyPath<Element, Value>,
        _ comparator: (_ lhs: Value, _ rhs: Value) -> Bool) -> [Element] {
        sorted { comparator($0[keyPath: keyPath], $1[keyPath: keyPath]) }
    }
}

Hope Swift add this in the near future in the core of the language.

Date in to UTC format Java

SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );

Min/Max of dates in an array?

This is a particularly great way to do this (you can get max of an array of objects using one of the object properties): Math.max.apply(Math,array.map(function(o){return o.y;}))

This is the accepted answer for this page: Finding the max value of an attribute in an array of objects

Regular expressions inside SQL Server

You can write queries like this in SQL Server:

--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'

how to use DEXtoJar

  1. old link

  2. dex2jar syntax

  3. want dex to jar

    • if you have dex file (eg. using FDex2 dump from a running android apk/app), then you can:
    • sh d2j-dex2jar.sh -f ~/path/to/dex_to_decompile.dex
    • can got the converted jar from dex.
    • example:
    • /xxx/dex-tools-2.1-SNAPSHOT/d2j-dex2jar.sh -f com.huili.readingclub8825612.dex dex2jar com.huili.readingclub8825612.dex -> ./com.huili.readingclub8825612-dex2jar.jar
  4. want jar to java src

    • if you continue want convert from jar to java sourcecode, then you, have multiple choice:
      • using Jadx directly convert dex to java sourcecode
      • first convert dex to jar, second convertjartojava sourcecode`

Note

how to got d2j-dex2jar.sh?

download from dex2jar github release, got dex-tools-2.1-SNAPSHOT.zip, unzip then got

  • you expected Linux's d2j-dex2jar.sh
    • and Windows's d2j-dex2jar.bat
    • and related other tools
    • d2j-jar2dex.sh
    • d2j-dex2smali.sh
    • d2j-baksmali.sh
    • d2j-apk-sign.sh
    • etc.

what's the full process of convert dex to java sourcecode ?

you can refer my (crifan)'s full answer in another post: android - decompiling DEX into Java sourcecode - Stack Overflow

or refer my full tutorial (but written in Chinese): ??????????

How to enable bulk permission in SQL Server

Try this:

USE master;

GO;
 
GRANT ADMINISTER BULK OPERATIONS TO shira;

Conda environments not showing up in Jupyter Notebook

I had similar issue and I found a solution that is working for Mac, Windows and Linux. It takes few key ingredients that are in the answer above:

To be able to see conda env in Jupyter notebook, you need:

  • the following package in you base env:
    conda install nb_conda

  • the following package in each env you create:
    conda install ipykernel

  • check the configurationn of jupyter_notebook_config.py
    first check if you have a jupyter_notebook_config.py in one of the location given by jupyter --paths
    if it doesn't exist, create it by running jupyter notebook --generate-config
    add or be sure you have the following: c.NotebookApp.kernel_spec_manager_class='nb_conda_kernels.manager.CondaKernelSpecManager'

The env you can see in your terminal: enter image description here

On Jupyter Lab you can see the same env as above both the Notebook and Console: enter image description here

And you can choose your env when have a notebook open: enter image description here

The safe way is to create a specific env from which you will run your example of envjupyter lab command. Activate your env. Then add jupyter lab extension example jupyter lab extension. Then you can run jupyter lab

How to get these two divs side-by-side?

Best that works for me:

 .left{
   width:140px;
   float:left;
   height:100%;
 }

 .right{
   margin-left:140px;
 }


http://jsfiddle.net/jiantongc/7uVNN/

VB.NET Switch Statement GoTo Case

you should declare label first use this :

    Select Case parameter 
        Case "userID"
                    ' does something here.
            Case "packageID"
                    ' does something here.
            Case "mvrType" 
                    If otherFactor Then 
                            ' does something here. 
                    Else 
                            GoTo else
                    End If 

            Case Else 
else :
                    ' does some processing... 
                    Exit Select 
    End Select

C++: How to round a double to an int?

Casting is not a mathematical operation and doesn't behave as such. Try

int y = (int)round(x);

Calculate age given the birth date in the format YYYYMMDD

With momentjs:

/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')

Add another class to a div

I am facing the same issue. If parent element is hidden then after showing the element chosen drop down are not showing. This is not a perfect solution but it solved my issue. After showing the element you can use following code.

function onshowelement() { $('.chosen').chosen('destroy'); $(".chosen").chosen({ width: '100%' }); }

PHP date add 5 year to current date

try this ,

$presentyear = '2013-08-16 12:00:00';

$nextyear  = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($presentyear )),   date("d",strtotime($presentyear )),   date("Y",strtotime($presentyear ))+5));

echo $nextyear;

JQuery: Change value of hidden input field

If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.

Xpath for href element

This works properly try this code-

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

Where does R store packages?

You do not want the '='

Use .libPaths("C:/R/library") in you Rprofile.site file

And make sure you have correct " symbol (Shift-2)

Java: Sending Multiple Parameters to Method

The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?

If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:

public class MyClass
{
  public void doSomething(int i) 
  {
    ...
  }

  public void doSomething(int i, String s) 
  {
    ...
  }

  public void doSomething(int i, String s, boolean b) 
  {
    ...
  }
}

If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:

public MyClass 
{
  public void doSomething(int... integers)
  {
    for (int i : integers) 
    {
      ...
    }
  }
}

Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

Checking if a variable exists in javascript

if ( typeof variableName !== 'undefined' && variableName )
//// could throw an error if var doesnt exist at all

if ( window.variableName )
//// could be true if var == 0

////further on it depends on what is stored into that var
// if you expect an object to be stored in that var maybe
if ( !!window.variableName )
//could be the right way

best way => see what works for your case

How do I disable log messages from the Requests library?

For anybody using logging.config.dictConfig you can alter the requests library log level in the dictionary like this:

'loggers': {
    '': {
        'handlers': ['file'],
        'level': level,
        'propagate': False
    },
    'requests.packages.urllib3': {
        'handlers': ['file'],
        'level': logging.WARNING
    }
}

Angular 2 'component' is not a known element

I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50

Resolved by killing the terminal (ng serve) and restarting VScode.

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Right click on project. Properties->Configuration Properties->General->Linker.

I found two options needed to be set. Under System: SubSystem = Windows (/SUBSYSTEM:WINDOWS) Under Advanced: EntryPoint = main

Running a cron job at 2:30 AM everyday

  1. To edit:

    crontab -e
    
  2. Add this command line:

    30 2 * * * /your/command
    
    • Crontab Format:

      MIN HOUR DOM MON DOW CMD

    • Format Meanings and Allowed Value:
    • MIN Minute field 0 to 59
    • HOUR Hour field 0 to 23
    • DOM Day of Month 1-31
    • MON Month field 1-12
    • DOW Day Of Week 0-6
    • CMD Command Any command to be executed.
  3. Restart cron with latest data:

    service crond restart
    

Using awk to print all columns from the nth to the last

Perl solution:

perl -lane 'splice @F,0,1; print join " ",@F' file

These command-line options are used:

  • -n loop around every line of the input file, do not automatically print every line

  • -l removes newlines before processing, and adds them back in afterwards

  • -a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace

  • -e execute the perl code

splice @F,0,1 cleanly removes column 0 from the @F array

join " ",@F joins the elements of the @F array, using a space in-between each element


Python solution:

python -c "import sys;[sys.stdout.write(' '.join(line.split()[1:]) + '\n') for line in sys.stdin]" < file

What causes javac to issue the "uses unchecked or unsafe operations" warning

I have ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;. Because value is a complex structure (I want to clean JSON), there can happen any combinations on numbers, booleans, strings, arrays. So, I used the solution of @Dan Dyer:

@SuppressWarnings("unchecked")
ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;

Node Multer unexpected field

We have to make sure the type= file with name attribute should be same as the parameter name passed in upload.single('attr')

var multer  = require('multer');
var upload = multer({ dest: 'upload/'});
var fs = require('fs');

/** Permissible loading a single file, 
    the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('recfile');

app.post('/upload', type, function (req,res) {

  /** When using the "single"
      data come in "req.file" regardless of the attribute "name". **/
  var tmp_path = req.file.path;

  /** The original name of the uploaded file
      stored in the variable "originalname". **/
  var target_path = 'uploads/' + req.file.originalname;

  /** A better way to copy the uploaded file. **/
  var src = fs.createReadStream(tmp_path);
  var dest = fs.createWriteStream(target_path);
  src.pipe(dest);
  src.on('end', function() { res.render('complete'); });
  src.on('error', function(err) { res.render('error'); });

});

Automatic exit from Bash shell script on error

To exit the script as soon as one of the commands failed, add this at the beginning:

set -e

This causes the script to exit immediately when some command that is not part of some test (like in a if [ ... ] condition or a && construct) exits with a non-zero exit code.

Git: How to pull a single file from a server repository in Git?

I was looking for slightly different task, but this looks like what you want:

git archive --remote=$REPO_URL HEAD:$DIR_NAME -- $FILE_NAME |
tar xO > /where/you/want/to/have.it

I mean, if you want to fetch path/to/file.xz, you will set DIR_NAME to path/to and FILE_NAME to file.xz. So, you'll end up with something like

git archive --remote=$REPO_URL HEAD:path/to -- file.xz |
tar xO > /where/you/want/to/have.it

And nobody keeps you from any other form of unpacking instead of tar xO of course (It was me who need a pipe here, yeah).

Experimental decorators warning in TypeScript compilation

  1. Open VScode.
  2. Press ctrl+comma
  3. Follow the directions in the screen shot
    1. Search about experimentalDecorators
    2. Edit it

How To Check If A Key in **kwargs Exists?

You want

if 'errormessage' in kwargs:
    print("found it")

To get the value of errormessage

if 'errormessage' in kwargs:
    print("errormessage equals " + kwargs.get("errormessage"))

In this way, kwargs is just another dict. Your first example, if kwargs['errormessage'], means "get the value associated with the key "errormessage" in kwargs, and then check its bool value". So if there's no such key, you'll get a KeyError.

Your second example, if errormessage in kwargs:, means "if kwargs contains the element named by "errormessage", and unless "errormessage" is the name of a variable, you'll get a NameError.

I should mention that dictionaries also have a method .get() which accepts a default parameter (itself defaulting to None), so that kwargs.get("errormessage") returns the value if that key exists and None otherwise (similarly kwargs.get("errormessage", 17) does what you might think it does). When you don't care about the difference between the key existing and having None as a value or the key not existing, this can be handy.

Npm Please try using this command again as root/administrator

  1. Close the IDE
  2. Close the node terminals running ng serve or npm start
  3. Go to your project folder/node_modules and see you if can find the package that you are trying to install
  4. If you find the package you are searching then delete package folder
  5. In case, this is your 1st npm install then skip step 4 and delete everything inside the node_modules. If you don't find node_modules then create one folder in your project.
  6. Open the terminal in admin mode and do npm install.

That should fix the issue hopefully

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

Is mongodb running?

For quickly checking if mongodb is running, this quick nc trick will let you know.

nc -zvv localhost 27017

The above command assumes that you are running it on the default port on localhost.

For auto-starting it, you might want to look at this thread.

How can I tell what edition of SQL Server runs on the machine?

You can get just the edition name by using the following steps.

  • Open "SQL Server Configuration Manager"
  • From the List of SQL Server Services, Right Click on "SQL Server (Instance_name)" and Select Properties.
  • Select "Advanced" Tab from the Properties window.
  • Verify Edition Name from the "Stock Keeping Unit Name"
  • Verify Edition Id from the "Stock Keeping Unit Id"
  • Verify Service Pack from the "Service Pack Level"
  • Verify Version from the "Version"

screen shot

Classes vs. Functions

Never create classes. At least the OOP kind of classes in Python being discussed.

Consider this simplistic class:

class Person(object):
    def __init__(self, id, name, city, account_balance):
        self.id = id
        self.name = name
        self.city = city
        self.account_balance = account_balance

    def adjust_balance(self, offset):
        self.account_balance += offset


if __name__ == "__main__":
    p = Person(123, "bob", "boston", 100.0)
    p.adjust_balance(50.0)
    print("done!: {}".format(p.__dict__))

vs this namedtuple version:

from collections import namedtuple

Person = namedtuple("Person", ["id", "name", "city", "account_balance"])


def adjust_balance(person, offset):
    return person._replace(account_balance=person.account_balance + offset)


if __name__ == "__main__":
    p = Person(123, "bob", "boston", 100.0)
    p = adjust_balance(p, 50.0)
    print("done!: {}".format(p))

The namedtuple approach is better because:

  • namedtuples have more concise syntax and standard usage.
  • In terms of understanding existing code, namedtuples are basically effortless to understand. Classes are more complex. And classes can get very complex for humans to read.
  • namedtuples are immutable. Managing mutable state adds unnecessary complexity.
  • class inheritance adds complexity, and hides complexity.

I can't see a single advantage to using OOP classes. Obviously, if you are used to OOP, or you have to interface with code that requires classes like Django.

BTW, most other languages have some record type feature like namedtuples. Scala, for example, has case classes. This logic applies equally there.

How do I make bootstrap table rows clickable?

You can use in this way using bootstrap css. Just remove the active class if already assinged to any row and reassign to the current row.

    $(".table tr").each(function () {
        $(this).attr("class", "");
    });
    $(this).attr("class", "active");

Git commit date

if you got troubles with windows cmd command and .bat just escape percents like that

git show -s --format=%%ct

The % character has a special meaning for command line parameters and FOR parameters. To treat a percent as a regular character, double it: %%

Syntax : Escape Characters, Delimiters and Quotes

How should I print types like off_t and size_t?

Which version of C are you using?

In C90, the standard practice is to cast to signed or unsigned long, as appropriate, and print accordingly. I've seen %z for size_t, but Harbison and Steele don't mention it under printf(), and in any case that wouldn't help you with ptrdiff_t or whatever.

In C99, the various _t types come with their own printf macros, so something like "Size is " FOO " bytes." I don't know details, but that's part of a fairly large numeric format include file.

Using sed and grep/egrep to search and replace

Use this command:

egrep -lRZ "\.jpg|\.png|\.gif" . \
    | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
  • egrep: find matching lines using extended regular expressions

    • -l: only list matching filenames

    • -R: search recursively through all given directories

    • -Z: use \0 as record separator

    • "\.jpg|\.png|\.gif": match one of the strings ".jpg", ".gif" or ".png"

    • .: start the search in the current directory

  • xargs: execute a command with the stdin as argument

    • -0: use \0 as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.

    • -l: use one line per command as parameter

  • sed: the stream editor

    • -i: replace the input file with the output without making a backup

    • -e: use the following argument as expression

    • 's/\.jpg\|\.gif\|\.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"

How do I use the JAVA_OPTS environment variable?

Just figured it out in Oracle Java the environmental variable is called: JAVA_TOOL_OPTIONS rather than JAVA_OPTS

How to mention C:\Program Files in batchfile

Surround the script call with "", generally it's good practices to do so with filepath.

"C:\Program Files"

Although for this particular name you probably should use environment variable like this :

"%ProgramFiles%\batch.cmd"

or for 32 bits program on 64 bit windows :

"%ProgramFiles(x86)%\batch.cmd"

Generating random, unique values C#

randomNumber function return unqiue integer value between 0 to 100000

  bool check[] = new bool[100001];
  Random r = new Random();
  public int randomNumber() {
      int num = r.Next(0,100000);
       while(check[num] == true) {
             num = r.Next(0,100000);
     }
    check[num] = true;
   return num;
 }

php form action php self

The easiest way to do it is leaving action blank action="" or omitting it completely from the form tag, however it is bad practice (if at all you care about it).

Incase you do care about it, the best you can do is:

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="<?php echo($_SERVER['PHP_SELF'] . http_build_query($_GET));?>">

The best thing about using this is that even arrays are converted so no need to do anything else for any kind of data.

Compute row average in pandas

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

As said, JsonMappingException: out of START_ARRAY token exception is thrown by Jackson object mapper as it's expecting an Object {} whereas it found an Array [{}] in response.

A simpler solution could be replacing the method getLocations with:

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeReference<List<Location>> typeReference = new TypeReference<>() {};
        return objectMapper.readValue(inputStream, typeReference);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

On the other hand, if you don't have a pojo like Location, you could use:

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

Console.log not working at all

It was because I had turned off "Logs" in the list of boxes earlier. enter image description here

Resize to fit image in div, and center horizontally and vertically

This is one way to do it:

Fiddle here: http://jsfiddle.net/4Mvan/1/

HTML:

<div class='container'>
    <a href='#'>
    <img class='resize_fit_center'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
    </a>
</div>

CSS:

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

Storing an object in state of a React component?

Easier way to do it in one line of code

this.setState({ object: { ...this.state.object, objectVarToChange: newData } })

MongoDB/Mongoose querying at a specific date?

We had an issue relating to duplicated data in our database, with a date field having multiple values where we were meant to have 1. I thought I'd add the way we resolved the issue for reference.

We have a collection called "data" with a numeric "value" field and a date "date" field. We had a process which we thought was idempotent, but ended up adding 2 x values per day on second run:

{ "_id" : "1", "type":"x", "value":1.23, date : ISODate("2013-05-21T08:00:00Z")}
{ "_id" : "2", "type":"x", "value":1.23, date : ISODate("2013-05-21T17:00:00Z")}

We only need 1 of the 2 records, so had to resort the javascript to clean up the db. Our initial approach was going to be to iterate through the results and remove any field with a time of between 6am and 11am (all duplicates were in the morning), but during implementation, made a change. Here's the script used to fix it:

var data = db.data.find({"type" : "x"})
var found = [];
while (data.hasNext()){
    var datum = data.next();
    var rdate = datum.date;
    // instead of the next set of conditions, we could have just used rdate.getHour() and checked if it was in the morning, but this approach was slightly better...
    if (typeof found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] !== "undefined") {
       if (datum.value != found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()]) {
           print("DISCREPENCY!!!: " + datum._id + " for date " + datum.date);
       }
       else {
           print("Removing " + datum._id);
           db.data.remove({ "_id": datum._id});
       }
    }
    else {
       found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] = datum.value;
    }
}

and then ran it with mongo thedatabase fixer_script.js

How to test if a double is zero?

The safest way would be bitwise OR ing your double with 0. Look at this XORing two doubles in Java

Basically you should do if ((Double.doubleToRawLongBits(foo.x) | 0 ) ) (if it is really 0)

Nth max salary in Oracle

SELECT sal FROM (
    SELECT sal, row_number() OVER (order by sal desc) AS rn FROM emp
)
WHERE rn = 3

Yes, it will take longer to execute if the table is big. But for "N-th row" queries the only way is to look through all the data and sort it. It will be definitely much faster if you have an index on sal.

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

You can use a user defined type containing an array of strings which will be the inner array. Then you can use an array of this user defined type as your outer array.

Have a look at the following test project:

'1 form with:
'  command button: name=Command1
'  command button: name=Command2
Option Explicit

Private Type MyArray
  strInner() As String
End Type

Private mudtOuter() As MyArray

Private Sub Command1_Click()
  'change the dimensens of the outer array, and fill the extra elements with "1"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldOuter As Integer
  intOldOuter = UBound(mudtOuter)
  ReDim Preserve mudtOuter(intOldOuter + 2) As MyArray
  For intOuter = intOldOuter + 1 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = "1"
    Next intInner
  Next intOuter
End Sub

Private Sub Command2_Click()
  'change the dimensions of the middle inner array, and fill the extra elements with "2"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldInner As Integer
  intOuter = UBound(mudtOuter) / 2
  intOldInner = UBound(mudtOuter(intOuter).strInner)
  ReDim Preserve mudtOuter(intOuter).strInner(intOldInner + 5) As String
  For intInner = intOldInner + 1 To UBound(mudtOuter(intOuter).strInner)
    mudtOuter(intOuter).strInner(intInner) = "2"
  Next intInner
End Sub

Private Sub Form_Click()
  'clear the form and print the outer,inner arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  Cls
  For intOuter = 0 To UBound(mudtOuter)
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      Print CStr(intOuter) & "," & CStr(intInner) & " = " & mudtOuter(intOuter).strInner(intInner)
    Next intInner
    Print "" 'add an empty line between the outer array elements
  Next intOuter
End Sub

Private Sub Form_Load()
  'init the arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  ReDim mudtOuter(5) As MyArray
  For intOuter = 0 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = CStr((intOuter + 1) * (intInner + 1))
    Next intInner
  Next intOuter
  WindowState = vbMaximized
End Sub

Run the project, and click on the form to display the contents of the arrays.

Click on Command1 to enlarge the outer array, and click on the form again to show the results.

Click on Command2 to enlarge an inner array, and click on the form again to show the results.

Be careful though: when you redim the outer array, you also have to redim the inner arrays for all the new elements of the outer array

How can I check if an element exists in the visible DOM?

Try the following. It is the most reliable solution:

window.getComputedStyle(x).display == ""

For example,

var x = document.createElement("html")
var y = document.createElement("body")
var z = document.createElement("div")
x.appendChild(y);
y.appendChild(z);

z.style.display = "block";

console.log(z.closest("html") == null); // 'false'
console.log(z.style.display); // 'block'
console.log(window.getComputedStyle(z).display == ""); // 'true'

C++ Structure Initialization

As others have mentioned this is designated initializer.

This feature is part of C++20

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

What is the difference between DSA and RSA?

And in addition to the above nice answers.

  • DSA uses Discrete logarithm.
  • RSA uses Integer Factorization.

RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.

Event system in Python

You may have a look at pymitter (pypi). Its a small single-file (~250 loc) approach "providing namespaces, wildcards and TTL".

Here's a basic example:

from pymitter import EventEmitter

ee = EventEmitter()

# decorator usage
@ee.on("myevent")
def handler1(arg):
   print "handler1 called with", arg

# callback usage
def handler2(arg):
    print "handler2 called with", arg
ee.on("myotherevent", handler2)

# emit
ee.emit("myevent", "foo")
# -> "handler1 called with foo"

ee.emit("myotherevent", "bar")
# -> "handler2 called with bar"

PHP save image file

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

Python - How to concatenate to a string in a for loop?

If you must, this is how you can do it in a for loop:

mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
  endstring += s

but you should consider using join():

''.join(mylist)

How to create a String with carriage returns?

Try append characters .append('\r').append('\n'); instead of String .append("\\r\\n");

How to change link color (Bootstrap)

You can use .text-reset class to reset the color from default blue to anything you want. Hopefully this is helpful.

Source: https://getbootstrap.com/docs/4.5/utilities/text/#reset-color

Check if at least two out of three booleans are true

return 1 << $a << $b << $c >= 1 << 2;

Combine two (or more) PDF's

Combining two byte[] using iTextSharp up to version 5.x:

internal static MemoryStream mergePdfs(byte[] pdf1, byte[] pdf2)
{
    MemoryStream outStream = new MemoryStream();
    using (Document document = new Document())
    using (PdfCopy copy = new PdfCopy(document, outStream))
    {
        document.Open();
        copy.AddDocument(new PdfReader(pdf1));
        copy.AddDocument(new PdfReader(pdf2));
    }
    return outStream;
}

Instead of the byte[]'s it's possible to pass also Stream's

javac not working in windows command prompt

Ensure you don't allow spaces (white space) in between paths in the Path variable. My problem was I had white space in and I believe Windows treated it as a NULL and didn't read my path in for Java.

error: (-215) !empty() in function detectMultiScale

This error means that the XML file could not be found. The library needs you to pass it the full path, even though you’re probably just using a file that came with the OpenCV library.

You can use the built-in pkg_resources module to automatically determine this for you. The following code looks up the full path to a file inside wherever the cv2 module was loaded from:

import pkg_resources
haar_xml = pkg_resources.resource_filename(
    'cv2', 'data/haarcascade_frontalface_default.xml')

For me this was '/Users/andrew/.local/share/virtualenvs/foo-_b9W43ee/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml'; yours is guaranteed to be different. Just let python’s pkg_resources library figure it out.

classifier = cv2.CascadeClassifier(haar_xml)
faces = classifier.detectMultiScale(frame)

Success!

Why compile Python code?

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.

how to increase the limit for max.print in R

See ?options:

options(max.print=999999)

Git log to get commits only for a specific branch

You could try something like this:

#!/bin/bash

all_but()
{
    target="$(git rev-parse $1)"
    echo "$target --not"
    git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
    while read entry
    do
        eval "$entry"

        test "$ref" != "$target" && echo "$ref"
    done
}

git log $(all_but $1)

Or, borrowing from the recipe in the Git User's Manual:

#!/bin/bash
git log $1 --not $( git show-ref --heads | cut -d' ' -f2 | grep -v "^$1" )

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

You could use DateTime.TryParse() instead of DateTime.Parse().
With TryParse() you have a return value if it was successful and with Parse() you have to handle an exception

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How to prevent custom views from losing state across screen orientation changes

I found that this answer was causing some crashes on Android versions 9 and 10. I think it's a good approach but when I was looking at some Android code I found out it was missing a constructor. The answer is quite old so at the time there probably was no need for it. When I added the missing constructor and called it from the creator the crash was fixed.

So here is the edited code:

public class CustomView extends LinearLayout {

    private int stateToSave;

    ...

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        // your custom state
        ss.stateToSave = this.stateToSave;

        return ss;
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container)
    {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        // your custom state
        this.stateToSave = ss.stateToSave;
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
    {
        dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState {
        int stateToSave;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.stateToSave = in.readInt();
        }

        // This was the missing constructor
        @RequiresApi(Build.VERSION_CODES.N)
        SavedState(Parcel in, ClassLoader loader)
        {
            super(in, loader);
            this.stateToSave = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.stateToSave);
        }    
        
        public static final Creator<SavedState> CREATOR =
            new ClassLoaderCreator<SavedState>() {
          
            // This was also missing
            @Override
            public SavedState createFromParcel(Parcel in, ClassLoader loader)
            {
                return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(in, loader) : new SavedState(in);
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in, null);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

How do I initialize Kotlin's MutableList to empty MutableList?

Various forms depending on type of List, for Array List:

val myList = mutableListOf<Kolory>() 
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()

For LinkedList:

val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()

For other list types, will be assumed Mutable if you construct them directly:

val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()

This holds true for anything implementing the List interface (i.e. other collections libraries).

No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:

val myList: List<Kolory> = ArrayList()

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]: 
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
          0.65459882])

In [41]: np.polyfit(x, y, 4)
Out[41]: 
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
         84.29340846])

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

How to set session timeout in web.config

The value you are setting in the timeout attribute is the one of the correct ways to set the session timeout value.

The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.

By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.

To test this, create a simple aspx page, and write this code in the Page_Load event,

Response.Write(Session.SessionID);

Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.

Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -

Session["UserId"] = 1;

Now, you will have to perform a check on every page for this variable like this -

if(Session["UserId"] == null)
    Response.Redirect("login.aspx");

This is a bare-bones example of how this will work.

But, for making your production quality secure apps, use Roles & Membership classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use.

what exactly is device pixel ratio?

Boris Smus's article High DPI Images for Variable Pixel Densities has a more accurate definition of device pixel ratio: the number of device pixels per CSS pixel is a good approximation, but not the whole story.

Note that you can get the DPR used by a device with window.devicePixelRatio.

Difference between clustered and nonclustered index

A comparison of a non-clustered index with a clustered index with an example

As an example of a non-clustered index, let’s say that we have a non-clustered index on the EmployeeID column. A non-clustered index will store both the value of the

EmployeeID

AND a pointer to the row in the Employee table where that value is actually stored. But a clustered index, on the other hand, will actually store the row data for a particular EmployeeID – so if you are running a query that looks for an EmployeeID of 15, the data from other columns in the table like

EmployeeName, EmployeeAddress, etc

. will all actually be stored in the leaf node of the clustered index itself.

This means that with a non-clustered index extra work is required to follow that pointer to the row in the table to retrieve any other desired values, as opposed to a clustered index which can just access the row directly since it is being stored in the same order as the clustered index itself. So, reading from a clustered index is generally faster than reading from a non-clustered index.

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

Replacement for "rename" in dplyr

dplyr >= 1.0.0

In addition to dplyr::rename in newer versions of dplyr is rename_with()

rename_with() renames columns using a function.

You can apply a function over a tidy-select set of columns using the .cols argument:

iris %>% 
  dplyr::rename_with(.fn = ~ gsub("^S", "s", .), .cols = where(is.numeric))

    sepal.Length sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5          1.4         0.2     setosa
2            4.9         3.0          1.4         0.2     setosa
3            4.7         3.2          1.3         0.2     setosa
4            4.6         3.1          1.5         0.2     setosa
5            5.0         3.6          1.4         0.2     setosa

C# Dictionary get item by index

If you need to extract an element key based on index, this function can be used:

public string getCard(int random)
{
    return Karta._dict.ElementAt(random).Key;
}

If you need to extract the Key where the element value is equal to the integer generated randomly, you can used the following function:

public string getCard(int random)
{
    return Karta._dict.FirstOrDefault(x => x.Value == random).Key;
}

Side Note: The first element of the dictionary is The Key and the second is the Value

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

Path.Combine for URLs?

I have combined all the previous answers:

    public static string UrlPathCombine(string path1, string path2)
    {
        path1 = path1.TrimEnd('/') + "/";
        path2 = path2.TrimStart('/');

        return Path.Combine(path1, path2)
            .Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
    }

    [TestMethod]
    public void TestUrl()
    {
        const string P1 = "http://msdn.microsoft.com/slash/library//";
        Assert.AreEqual("http://msdn.microsoft.com/slash/library/site.aspx", UrlPathCombine(P1, "//site.aspx"));

        var path = UrlPathCombine("Http://MyUrl.com/", "Images/Image.jpg");

        Assert.AreEqual(
            "Http://MyUrl.com/Images/Image.jpg",
            path);
    }

How to set java_home on Windows 7?

if you have not restarted your computer after installing jdk just restart your computer.

if you want to make a portable java and set path before using java, just make a batch file i explained below.

if you want to run this batch file when your computer start just put your batch file shortcut in startup folder. In windows 7 startup folder is "C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

make a batch file like this:

set Java_Home=C:\Program Files\Java\jdk1.8.0_11
set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_11\bin

note: java_home and path are variables. you can make any variable as you wish. for example set amir=good_boy and you can see amir by %amir% or you can see java_home by %java_home%

What's the easiest way to escape HTML in Python?

No libraries, pure python, safely escapes text into html text:

text.replace('&', '&amp;').replace('>', '&gt;').replace('<', '&lt;'
        ).replace('\'','&#39;').replace('"','&#34;').encode('ascii', 'xmlcharrefreplace')

Finding absolute value of a number without using Math.abs()

Yes:

abs_number = (number < 0) ? -number : number;

For integers, this works fine (except for Integer.MIN_VALUE, whose absolute value cannot be represented as an int).

For floating-point numbers, things are more subtle. For example, this method -- and all other methods posted thus far -- won't handle the negative zero correctly.

To avoid having to deal with such subtleties yourself, my advice would be to stick to Math.abs().

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

Can an int be null in Java?

I'm no expert, but I do believe that the null equivalent for an int is 0.

For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.

In some situations, this may be of use.

Multiple Errors Installing Visual Studio 2015 Community Edition

Since the marked answer mentioned repairing the VC Redist 2015, I list all the ones I can find instead of burying them in the comments.

Visual C++ Redistributable for Visual Studio 2015

Visual C++ Redistributable for Visual Studio 2015 Update 1

Microsoft Visual C++ 2015 Redistributable Update 3

This thread discussed the Visual C++ Redistributable for Visual Studio 2015 Update 2. But all the links are broken and I didn't find it.

Update Eclipse with Android development tools v. 23

I did this to solve the same issue (in OS X):

  1. Help > Install New Software > Add or select this repository "http://download.eclipse.org/eclipse/updates/4.3"
  2. Under "Eclipse platform" select the newest version of Eclipse.
  3. The installer will ask if you want to uninstall the ADT, click finish.
  4. Restart Eclipse and install ONLY the ADT 23 using this repository: https://dl-ssl.google.com/android/eclipse.
  5. Restart Eclipse and install DDMS, Hierarchy Viewer, Trace View etc.
  6. Restart Eclipse again.

Hope it helps.

MySQL vs MongoDB 1000 reads

On Single Server, MongoDb would not be any faster than mysql MyISAM on both read and write, given table/doc sizes are small 1 GB to 20 GB.
MonoDB will be faster on Parallel Reduce on Multi-Node clusters, where Mysql can NOT scale horizontally.

jQuery DIV click, with anchors

I know that if you were to change that to an href you'd do:

$("a#link1").click(function(event) {
  event.preventDefault();
  $('div.link1').show();
  //whatever else you want to do
});

so if you want to keep it with the div, I'd try

$("div.clickable").click(function(event) {
  event.preventDefault();
  window.location = $(this).attr("url");
});

ASP.NET Core 1.0 on IIS error 502.5

I got this issue on my production server after my VS project was automatically upgraded to .NET Core 1.1.2.

I simply installed the 1.1.2 .net core runtime from here on my production server: https://www.microsoft.com/net/download/core#/runtime

How do you use the ? : (conditional) operator in JavaScript?

I want to add some to the given answers.

In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.


Instead of:

var welcomeMessage  = 'Hello ' + (username ? username : 'guest');

You can use:

var welcomeMessage  = 'Hello ' + (username || 'guest');

This is Javascripts equivallent of PHP's shorthand ternary operator ?:

Or even:

var welcomeMessage  = 'Hello ' + (username || something || maybethis || 'guest');

It evaluates the variable, and if it's false or unset, it goes on to the next.

Redirecting unauthorized controller in ASP.NET MVC

Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.

EDIT: I have a couple of blog posts that go into more detail:

Example:

    [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
    public class MasterEventAuthorizationAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// The name of the master page or view to use when rendering the view on authorization failure.  Default
        /// is null, indicating to use the master page of the specified view.
        /// </summary>
        public virtual string MasterName { get; set; }

        /// <summary>
        /// The name of the view to render on authorization failure.  Default is "Error".
        /// </summary>
        public virtual string ViewName { get; set; }

        public MasterEventAuthorizationAttribute()
            : base()
        {
            this.ViewName = "Error";
        }

        protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
        {
            validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
        }

        public override void OnAuthorization( AuthorizationContext filterContext )
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException( "filterContext" );
            }

            if (AuthorizeCore( filterContext.HttpContext ))
            {
                SetCachePolicy( filterContext );
            }
            else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                // auth failed, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
            {
                // is authenticated and is in the SuperUser role
                SetCachePolicy( filterContext );
            }
            else
            {
                ViewDataDictionary viewData = new ViewDataDictionary();
                viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
                filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
            }

        }

        protected void SetCachePolicy( AuthorizationContext filterContext )
        {
            // ** IMPORTANT **
            // Since we're performing authorization at the action level, the authorization code runs
            // after the output caching module. In the worst case this could allow an authorized user
            // to cause the page to be cached, then an unauthorized user would later be served the
            // cached page. We work around this by telling proxies not to cache the sensitive page,
            // then we hook our custom authorization code into the caching mechanism so that we have
            // the final say on whether a page should be served from the cache.
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
            cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
            cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
        }


    }

Greyscale Background Css Images

I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.

You can use background-blend-mode property to achieve a greyscale image:

#something {
  background-color: #fff;
  background-image: url("yourimage");
  background-blend-mode: luminosity;
}

If you want to remove the effect, just change the blend-mode to initial.

You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something.

You can also use two images, one with color and the other without and set both as background and play with other blend modes.

https://www.w3schools.com/cssref/pr_background-blend-mode.asp

It won't work on Edge though.

EDIT: I've miss the "fade" part of the question.

If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:

#something {
  background-color: rgba(255,255,255,1);
  background-image: url("yourimage");
  background-blend-mode: luminosity;
  transition: background-color 1s ease-out;
}
#something:hover {
  background-color: rgba(255,255,255,0);
}

I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ

How to do a PUT request with curl?

Using the -X flag with whatever HTTP verb you want:

curl -X PUT -d arg=val -d arg2=val2 localhost:8080

This example also uses the -d flag to provide arguments with your PUT request.

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Okay, here is a solution to reduce the physical size of the transaction file, but without changing the recovery mode to simple.

Within your database, locate the file_id of the log file using the following query.

SELECT * FROM sys.database_files;

In my instance, the log file is file_id 2. Now we want to locate the virtual logs in use, and do this with the following command.

DBCC LOGINFO;

Here you can see if any virtual logs are in use by seeing if the status is 2 (in use), or 0 (free). When shrinking files, empty virtual logs are physically removed starting at the end of the file until it hits the first used status. This is why shrinking a transaction log file sometimes shrinks it part way but does not remove all free virtual logs.

If you notice a status 2's that occur after 0's, this is blocking the shrink from fully shrinking the file. To get around this do another transaction log backup, and immediately run these commands, supplying the file_id found above, and the size you would like your log file to be reduced to.

-- DBCC SHRINKFILE (file_id, LogSize_MB)
DBCC SHRINKFILE (2, 100);
DBCC LOGINFO;

This will then show the virtual log file allocation, and hopefully you'll notice that it's been reduced somewhat. Because virtual log files are not always allocated in order, you may have to backup the transaction log a couple of times and run this last query again; but I can normally shrink it down within a backup or two.

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

How to unzip a file in Powershell?

Hey Its working for me..

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
  $shell.Namespace("destination where files need to unzip").CopyHere($item)
}

Opening a folder in explorer and selecting a file

It might be a bit of a overkill but I like convinience functions so take this one:

    public static void ShowFileInExplorer(FileInfo file) {
        StartProcess("explorer.exe", null, "/select, "+file.FullName.Quote());
    }
    public static Process StartProcess(FileInfo file, params string[] args) => StartProcess(file.FullName, file.DirectoryName, args);
    public static Process StartProcess(string file, string workDir = null, params string[] args) {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.FileName = file;
        proc.Arguments = string.Join(" ", args);
        Logger.Debug(proc.FileName, proc.Arguments); // Replace with your logging function
        if (workDir != null) {
            proc.WorkingDirectory = workDir;
            Logger.Debug("WorkingDirectory:", proc.WorkingDirectory); // Replace with your logging function
        }
        return Process.Start(proc);
    }

This is the extension function I use as <string>.Quote():

static class Extensions
{
    public static string Quote(this string text)
    {
        return SurroundWith(text, "\"");
    }
    public static string SurroundWith(this string text, string surrounds)
    {
        return surrounds + text + surrounds;
    }
}

How do I implement interfaces in python?

Using the abc module for abstract base classes seems to do the trick.

from abc import ABCMeta, abstractmethod

class IInterface:
    __metaclass__ = ABCMeta

    @classmethod
    def version(self): return "1.0"
    @abstractmethod
    def show(self): raise NotImplementedError

class MyServer(IInterface):
    def show(self):
        print 'Hello, World 2!'

class MyBadServer(object):
    def show(self):
        print 'Damn you, world!'


class MyClient(object):

    def __init__(self, server):
        if not isinstance(server, IInterface): raise Exception('Bad interface')
        if not IInterface.version() == '1.0': raise Exception('Bad revision')

        self._server = server


    def client_show(self):
        self._server.show()


# This call will fail with an exception
try:
    x = MyClient(MyBadServer)
except Exception as exc:
    print 'Failed as it should!'

# This will pass with glory
MyClient(MyServer()).client_show()

How to convert a string to lower or upper case in Ruby

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase:

"hello James!".downcase    #=> "hello james!"

Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

"hello James!".upcase      #=> "HELLO JAMES!"
"hello James!".capitalize  #=> "Hello james!"
"hello James!".titleize    #=> "Hello James!"

If you want to modify a string in place, you can add an exclamation point to any of those methods:

string = "hello James!"
string.downcase!
string   #=> "hello james!"

Refer to the documentation for String for more information.

Generic type conversion FROM string

lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx Credit to "Tuna Toksoz"

Usage first:

TConverter.ChangeType<T>(StringValue);  

The class is below.

public static class TConverter
{
    public static T ChangeType<T>(object value)
    {
        return (T)ChangeType(typeof(T), value);
    }

    public static object ChangeType(Type t, object value)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(t);
        return tc.ConvertFrom(value);
    }

    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {

        TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
    }
}

Tips for debugging .htaccess rewrite rules

Online .htaccess rewrite testing

I found this Googling for RegEx help, it saved me a lot of time from having to upload new .htaccess files every time I make a small modification.

from the site:

htaccess tester

To test your htaccess rewrite rules, simply fill in the url that you're applying the rules to, place the contents of your htaccess on the larger input area and press "Check Now" button.

Spark RDD to DataFrame python

See,

There are two ways to convert an RDD to DF in Spark.

toDF() and createDataFrame(rdd, schema)

I will show you how you can do that dynamically.

toDF()

The toDF() command gives you the way to convert an RDD[Row] to a Dataframe. The point is, the object Row() can receive a **kwargs argument. So, there is an easy way to do that.

from pyspark.sql.types import Row

#here you are going to create a function
def f(x):
    d = {}
    for i in range(len(x)):
        d[str(i)] = x[i]
    return d

#Now populate that
df = rdd.map(lambda x: Row(**f(x))).toDF()

This way you are going to be able to create a dataframe dynamically.

createDataFrame(rdd, schema)

Other way to do that is creating a dynamic schema. How?

This way:

from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType

schema = StructType([StructField(str(i), StringType(), True) for i in range(32)])

df = sqlContext.createDataFrame(rdd, schema)

This second way is cleaner to do that...

So this is how you can create dataframes dynamically.

How do I redirect with JavaScript?

Compared to window.location="url"; it is much easyer to do just location="url"; I always use that

how to use the Box-Cox power transformation in R

Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().

Dynamic SELECT TOP @var In SQL Server

SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+

C# looping through an array

Just increment i by 3 in each step:

  Debug.Assert((theData.Length % 3) == 0);  // 'theData' will always be divisible by 3

  for (int i = 0; i < theData.Length; i += 3)
  {
       //grab 3 items at a time and do db insert, 
       // continue until all items are gone..
       string item1 = theData[i+0];
       string item2 = theData[i+1];
       string item3 = theData[i+2];
       // use the items
  }

To answer some comments, it is a given that theData.Length is a multiple of 3 so there is no need to check for theData.Length-2 as an upperbound. That would only mask errors in the preconditions.

Get decimal portion of a number with JavaScript

float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here

Finding median of list in Python

You can try the quickselect algorithm if faster average-case running times are needed. Quickselect has average (and best) case performance O(n), although it can end up O(n²) on a bad day.

Here's an implementation with a randomly chosen pivot:

import random

def select_nth(n, items):
    pivot = random.choice(items)

    lesser = [item for item in items if item < pivot]
    if len(lesser) > n:
        return select_nth(n, lesser)
    n -= len(lesser)

    numequal = items.count(pivot)
    if numequal > n:
        return pivot
    n -= numequal

    greater = [item for item in items if item > pivot]
    return select_nth(n, greater)

You can trivially turn this into a method to find medians:

def median(items):
    if len(items) % 2:
        return select_nth(len(items)//2, items)

    else:
        left  = select_nth((len(items)-1) // 2, items)
        right = select_nth((len(items)+1) // 2, items)

        return (left + right) / 2

This is very unoptimised, but it's not likely that even an optimised version will outperform Tim Sort (CPython's built-in sort) because that's really fast. I've tried before and I lost.

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

How do I crop an image in Java?

You need to read about Java Image API and mouse-related API, maybe somewhere under the java.awt.event package.

For a start, you need to be able to load and display the image to the screen, maybe you'll use a JPanel.

Then from there, you will try implement a mouse motion listener interface and other related interfaces. Maybe you'll get tied on the mouseDragged method...

For a mousedragged action, you will get the coordinate of the rectangle form by the drag...

Then from these coordinates, you will get the subimage from the image you have and you sort of redraw it anew....

And then display the cropped image... I don't know if this will work, just a product of my imagination... just a thought!

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

Why doesn't CSS ellipsis work in table cell?

It's also important to put

table-layout:fixed;

Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.

Datatable to html Table

public static string toHTML_Table(DataTable dt)
{
    if (dt.Rows.Count == 0) return ""; // enter code here

    StringBuilder builder = new StringBuilder();
    builder.Append("<html>");
    builder.Append("<head>");
    builder.Append("<title>");
    builder.Append("Page-");
    builder.Append(Guid.NewGuid());
    builder.Append("</title>");
    builder.Append("</head>");
    builder.Append("<body>");
    builder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
    builder.Append("style='border: solid 1px Silver; font-size: x-small;'>");
    builder.Append("<tr align='left' valign='top'>");
    foreach (DataColumn c in dt.Columns)
    {
        builder.Append("<td align='left' valign='top'><b>");
        builder.Append(c.ColumnName);
        builder.Append("</b></td>");
    }
    builder.Append("</tr>");
    foreach (DataRow r in dt.Rows)
    {
        builder.Append("<tr align='left' valign='top'>");
        foreach (DataColumn c in dt.Columns)
        {
            builder.Append("<td align='left' valign='top'>");
            builder.Append(r[c.ColumnName]);
            builder.Append("</td>");
        }
        builder.Append("</tr>");
    }
    builder.Append("</table>");
    builder.Append("</body>");
    builder.Append("</html>");

    return builder.ToString();
}

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.

You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.

How to open generated pdf using jspdf in new window

This works for me!!!

When you specify window features, it will open in a new window

Just like :

window.open(url,"_blank","top=100,left=200,width=1000,height=500");

scp or sftp copy multiple files with single command

After playing with scp for a while I have found the most robust solution:

(Beware of the single and double quotation marks)

Local to remote:

scp -r "FILE1" "FILE2" HOST:'"DIR"'

Remote to local:

scp -r HOST:'"FILE1" "FILE2"' "DIR"

Notice that whatever after "HOST:" will be sent to the remote and parsed there. So we must make sure they are not processed by the local shell. That is why single quotation marks come in. The double quotation marks are used to handle spaces in the file names.

If files are all in the same directory, we can use * to match them all, such as

scp -r "DIR_IN"/*.txt HOST:'"DIR"'
scp -r HOST:'"DIR_IN"/*.txt' "DIR"

Compared to using the "{}" syntax which is supported only by some shells, this one is universal

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

I use:

IF OBJECT_ID('[dbo].[myView]') IS NOT NULL
DROP VIEW [dbo].[myView]
GO
CREATE VIEW [dbo].[myView]
AS

...

Recently I added some utility procedures for this kind of stuff:

CREATE PROCEDURE dbo.DropView
@ASchema VARCHAR(100),
@AView VARCHAR(100)
AS
BEGIN
  DECLARE @sql VARCHAR(1000);
  IF OBJECT_ID('[' + @ASchema + '].[' + @AView + ']') IS NOT NULL
  BEGIN
    SET @sql  = 'DROP VIEW ' + '[' + @ASchema + '].[' + @AView + '] ';
    EXEC(@sql);
  END 
END

So now I write

EXEC dbo.DropView 'mySchema', 'myView'
GO
CREATE View myView
...
GO

I think it makes my changescripts a bit more readable

TypeError: unhashable type: 'numpy.ndarray'

numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

It is because you set the width:100% which by definition only spans the width of the screen. You want to set the min-width:100% which sets it to the width of the screen... with the ability to grow beyond that.

Also make sure you set min-width:100% for body and html.

Background color in input and text fields

You want to restrict to input fields that are of type text so use the selector input[type=text] rather than input (which will apply to all input fields (e.g. those of type submit as well)).

c# Best Method to create a log file

Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.

Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

If you have access to the element which the event is attached to inside the mouseout method, you can use contains() to see if the event.relatedTarget is a child element or not.

As event.relatedTarget is the element to which the mouse has passed into, if it isn't a child element, you have moused out of the element.

div.onmouseout = function (event) {
    if (!div.contains(event.relatedTarget)) {
        // moused out of div
    }
}

creating custom tableview cells in swift

Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).

Find an element in a list of tuples

Or takewhile, ( addition to this, example of more values is shown ):

>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>> 

if unsorted, like:

>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>> 

SVN how to resolve new tree conflicts when file is added on two branches

I found a post suggesting a solution for that. It's about to run:

svn resolve --accept working <YourPath>

which will claim the local version files as OK.
You can run it for single file or entire project catalogues.

Run java jar file on a server as background process

Run in background and add logs to log file using the following:

nohup java -jar /web/server.jar > log.log 2>&1 &

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

Spring @Transactional read-only propagation

It seem to ignore the settings for the current active transaction, it only apply settings to a new transaction:

org.springframework.transaction.PlatformTransactionManager
TransactionStatus getTransaction(TransactionDefinition definition)
                         throws TransactionException
Return a currently active transaction or create a new one, according to the specified propagation behavior.
Note that parameters like isolation level or timeout will only be applied to new transactions, and thus be ignored when participating in active ones.
Furthermore, not all transaction definition settings will be supported by every transaction manager: A proper transaction manager implementation should throw an exception when unsupported settings are encountered.
An exception to the above rule is the read-only flag, which should be ignored if no explicit read-only mode is supported. Essentially, the read-only flag is just a hint for potential optimization.

With arrays, why is it the case that a[5] == 5[a]?

And, of course

 ("ABCD"[2] == 2["ABCD"]) && (2["ABCD"] == 'C') && ("ABCD"[2] == 'C')

The main reason for this was that back in the 70's when C was designed, computers didn't have much memory (64KB was a lot), so the C compiler didn't do much syntax checking. Hence "X[Y]" was rather blindly translated into "*(X+Y)"

This also explains the "+=" and "++" syntaxes. Everything in the form "A = B + C" had the same compiled form. But, if B was the same object as A, then an assembly level optimization was available. But the compiler wasn't bright enough to recognize it, so the developer had to (A += C). Similarly, if C was 1, a different assembly level optimization was available, and again the developer had to make it explicit, because the compiler didn't recognize it. (More recently compilers do, so those syntaxes are largely unnecessary these days)

How does the FetchMode work in Spring Data JPA

According to Vlad Mihalcea (see https://vladmihalcea.com/hibernate-facts-the-importance-of-fetch-strategy/):

JPQL queries may override the default fetching strategy. If we don’t explicitly declare what we want to fetch using inner or left join fetch directives, the default select fetch policy is applied.

It seems that JPQL query might override your declared fetching strategy so you'll have to use join fetch in order to eagerly load some referenced entity or simply load by id with EntityManager (which will obey your fetching strategy but might not be a solution for your use case).

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

Oracle 'Partition By' and 'Row_Number' keyword

PARTITION BY segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.

In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER

But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency

newid() produces GUID, so what shall you expect by this expression?

select
   hi,ho,
   row_number() over(partition by newid() order by hi,ho)
from tbl;

...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1

Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1

An example, this is your data:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');

Then this is analogous to your query:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho)
from tbl;

What will be the output of that?

HI  HO  COLUMN_2
A   X   1
A   Y   1
A   Z   1
B   W   1
B   W   2
C   L   1
C   L   2

You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.

Now, why is the ORDER BY needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY; whereas in Postgresql, ORDER BY on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

Your ORDER BY on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION with no ORDER BY, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:

SELECT cdt.*,
        ROW_NUMBER ()
        OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
              ORDER BY newid())
           seq_no
   FROM CUSTOMER_DETAILS cdt

You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid() for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION with no ORDER BY

Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table

It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.

Live test: http://www.sqlfiddle.com/#!3/27821/6


But as dbaseman have noticed also, it's useless to partition and order on same columns.

You have a set of data like this:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');

Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

Output:

HI  HO  ROW_QUERY_A
A   X   1
A   X   2
A   X   3
B   Y   1
B   Y   2
C   Z   1
C   Z   2

See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)


You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');

select
   hi,ho,
   row_number() over(partition by hi order by ho) as nr
from tbl;

PARTITION BY hi operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho

Output:

HI  HO  NR
A   D   1
A   E   2
A   F   3
B   E   1
B   F   2
C   D   1
C   E   2

That data set makes more sense

Live test: http://www.sqlfiddle.com/#!3/d0b44/1

And this is similar to your query with same columns on both PARTITION BY and ORDER BY:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

And this is the ouput:

HI  HO  NR
A   D   1
A   E   1
A   F   1
B   E   1
B   F   1
C   D   1
C   E   1

See? no sense?

Live test: http://www.sqlfiddle.com/#!3/d0b44/3


Finally this might be the right query:

SELECT cdt.*,
     ROW_NUMBER ()
     OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
           ORDER BY 
               -- removed: cdt.country_code, cdt.account, 
               cdt.currency) -- keep
        seq_no
FROM CUSTOMER_DETAILS cdt

MySql export schema without data

To get an individual table's creation script:
- select all the table (with shift key)
- just right click on the table name and click Copy to Clipboard > Create Statement.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

How can I programmatically determine if my app is running in the iphone simulator?

/// Returns true if its simulator and not a device

public static var isSimulator: Bool {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        return true
    #else
        return false
    #endif
}

How to read all files in a folder from Java?

list down files from Test folder present inside class path

import java.io.File;
import java.io.IOException;

public class Hello {

    public static void main(final String[] args) throws IOException {

        System.out.println("List down all the files present on the server directory");
        File file1 = new File("/prog/FileTest/src/Test");
        File[] files = file1.listFiles();
        if (null != files) {
            for (int fileIntList = 0; fileIntList < files.length; fileIntList++) {
                String ss = files[fileIntList].toString();
                if (null != ss && ss.length() > 0) {
                    System.out.println("File: " + (fileIntList + 1) + " :" + ss.substring(ss.lastIndexOf("\\") + 1, ss.length()));
                }
            }
        }


    }


}

New line in Sql Query

Pinal Dave explains this well in his blog.

http://blog.sqlauthority.com/2009/07/01/sql-server-difference-between-line-feed-n-and-carriage-return-r-t-sql-new-line-char/

DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS FL ' + @NewLineChar + 'SELECT SecondLine AS SL')

How to make several plots on a single page using matplotlib?

The answer from las3rjock, which somehow is the answer accepted by the OP, is incorrect--the code doesn't run, nor is it valid matplotlib syntax; that answer provides no runnable code and lacks any information or suggestion that the OP might find useful in writing their own code to solve the problem in the OP.

Given that it's the accepted answer and has already received several up-votes, I suppose a little deconstruction is in order.

First, calling subplot does not give you multiple plots; subplot is called to create a single plot, as well as to create multiple plots. In addition, "changing plt.figure(i)" is not correct.

plt.figure() (in which plt or PLT is usually matplotlib's pyplot library imported and rebound as a global variable, plt or sometimes PLT, like so:

from matplotlib import pyplot as PLT

fig = PLT.figure()

the line just above creates a matplotlib figure instance; this object's add_subplot method is then called for every plotting window (informally think of an x & y axis comprising a single subplot). You create (whether just one or for several on a page), like so

fig.add_subplot(111)

this syntax is equivalent to

fig.add_subplot(1,1,1)

choose the one that makes sense to you.

Below I've listed the code to plot two plots on a page, one above the other. The formatting is done via the argument passed to add_subplot. Notice the argument is (211) for the first plot and (212) for the second.

from matplotlib import pyplot as PLT

fig = PLT.figure()

ax1 = fig.add_subplot(211)
ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)])

ax2 = fig.add_subplot(212)
ax2.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])

PLT.show()

Each of these two arguments is a complete specification for correctly placing the respective plot windows on the page.

211 (which again, could also be written in 3-tuple form as (2,1,1) means two rows and one column of plot windows; the third digit specifies the ordering of that particular subplot window relative to the other subplot windows--in this case, this is the first plot (which places it on row 1) hence plot number 1, row 1 col 1.

The argument passed to the second call to add_subplot, differs from the first only by the trailing digit (a 2 instead of a 1, because this plot is the second plot (row 2, col 1).

An example with more plots: if instead you wanted four plots on a page, in a 2x2 matrix configuration, you would call the add_subplot method four times, passing in these four arguments (221), (222), (223), and (224), to create four plots on a page at 10, 2, 8, and 4 o'clock, respectively and in this order.

Notice that each of the four arguments contains two leadings 2's--that encodes the 2 x 2 configuration, ie, two rows and two columns.

The third (right-most) digit in each of the four arguments encodes the ordering of that particular plot window in the 2 x 2 matrix--ie, row 1 col 1 (1), row 1 col 2 (2), row 2 col 1 (3), row 2 col 2 (4).

How to have the cp command create any necessary folders for copying a file to a destination

cp -Rvn /source/path/* /destination/path/
cp: /destination/path/any.zip: No such file or directory

It will create no existing paths in destination, if path have a source file inside. This dont create empty directories.

A moment ago i've seen xxxxxxxx: No such file or directory, because i run out of free space. without error message.

with ditto:

ditto -V /source/path/* /destination/path
ditto: /destination/path/any.zip: No space left on device

once freed space cp -Rvn /source/path/* /destination/path/ works as expected

Is there a way to collapse all code blocks in Eclipse?

The question is a bit old, but let me add a different approach. In addition to the above hot-key approaches, there are default preference settings that can be toggled.

As of Eclipse Galileo (and definitely in my Eclipse Version: Indigo Service Release 2 Build id: 20120216-1857) language specific preferences can open up new files to edit which are already collapsed or expanded.

Here is a link to Eclipse Galileo online docs showing the feature for C/C++: http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.cdt.doc.user/reference/cdt_u_c_editor_folding.htm .

In my Eclipse Indigo I can open the Folding Preferences window via : menu/ Window/ Preferences/ Java/ Editor/ Folding and set all options on so I can open files by default that are completely collapsed.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I eventually figured out there was a byte mark exception and removed it using this code:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
    if (xml.StartsWith(_byteOrderMarkUtf8))
    {
        var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;
        xml = xml.Remove(0, lastIndexOfUtf8);
    }

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

How to unpack an .asar file?

https://www.electronjs.org/apps/asarui

UI for Asar, Extract All, or drag extract file/directory

TCP vs UDP on video stream

While reading the TCP UDP debate I noticed a logical flaw. A TCP packet loss causing a one minute delay that's converted into a one minute buffer cant be correlated to UDP dropping a full minute while experiencing the same loss. A more fair comparison is as follows.

TCP experiences a packet loss. The video is stopped while TCP resend's packets in an attempt to stream mathematically perfect packets. Video is delayed for one minute and picks up where it left off after missing packet makes its destination. We all wait but we know we wont miss a single pixel.

UDP experiences a packet loss. For a second during the video stream a corner of the screen gets a little blurry. No one notices and the show goes on without looking for the lost packets.

Anything that streams gains the most benefits from UDP. The packet loss causing a one minute delay to TCP would not cause a one minute delay to UDP. Considering that most systems use multiple resolution streams making things go blocky when starving for packets, makes even more sense to use UDP.

UDP FTW when streaming.

Use chrome as browser in C#?

You can use WebKit.NET. This is a C# wrapper for WebKit, which is the rendering engine used by Chrome.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

how to update spyder on anaconda

Use this conda install spyder=4.0.0 This will not mess up your anaconda dependencies. https://github.com/spyder-ide/spyder/releases

How do I set the maximum line length in PyCharm?

You can even set a separate right margin for HTML. Under the specified path:

File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)

This is very useful because generally HTML and JS may be usually long in one line than Python. :)

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How do I perform a JAVA callback between classes?

Use the observer pattern. It works like this:

interface MyListener{
    void somethingHappened();
}

public class MyForm implements MyListener{
    MyClass myClass;
    public MyForm(){
        this.myClass = new MyClass();
        myClass.addListener(this);
    }
    public void somethingHappened(){
       System.out.println("Called me!");
    }
}
public class MyClass{
    private List<MyListener> listeners = new ArrayList<MyListener>();

    public void addListener(MyListener listener) {
        listeners.add(listener);
    }
    void notifySomethingHappened(){
        for(MyListener listener : listeners){
            listener.somethingHappened();
        }
    }
}

You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.

This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.

In my example:

MyClass is the producer here as its notifying a list of listeners.

MyListener is the interface.

MyForm is interested in when somethingHappened, so it is implementing MyListener and registering itself with MyClass. Now MyClass can inform MyForm about events without directly referencing MyForm. This is the strength of the observer pattern, it reduces dependency and increases reusability.

Test if element is present using Selenium WebDriver?

I would use something like (with Scala [the code in old "good" Java 8 may be similar to this]):

object SeleniumFacade {

  def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {
    val elements = maybeParent match {
      case Some(parent) => parent.findElements(bySelector).asScala
      case None => driver.findElements(bySelector).asScala
    }
    if (elements.nonEmpty) {
      Try { Some(elements(withIndex)) } getOrElse None
    } else None
  }
  ...
}

so then,

val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))

Definition of int64_t

a) Can you explain to me the difference between int64_t and long (long int)? In my understanding, both are 64 bit integers. Is there any reason to choose one over the other?

The former is a signed integer type with exactly 64 bits. The latter is a signed integer type with at least 32 bits.

b) I tried to look up the definition of int64_t on the web, without much success. Is there an authoritative source I need to consult for such questions?

http://cppreference.com covers this here: http://en.cppreference.com/w/cpp/types/integer. The authoritative source, however, is the C++ standard (this particular bit can be found in §18.4 Integer types [cstdint]).

c) For code using int64_t to compile, I am including <iostream>, which doesn't make much sense to me. Are there other includes that provide a declaration of int64_t?

It is declared in <cstdint> or <cinttypes> (under namespace std), or in <stdint.h> or <inttypes.h> (in the global namespace).

input() error - NameError: name '...' is not defined

You are running Python 2, not Python 3. For this to work in Python 2, use raw_input.

input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)

Asp Net Web API 2.1 get client IP address

It's better to cast it to HttpContextBase, this way you can mock and test it more easily

public string GetUserIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
        if (ctx != null)
        {
            return ctx.Request.UserHostAddress;
        }
    }

    return null;
}

How do I create an Excel chart that pulls data from multiple sheets?

Use the Chart Wizard.

On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.

Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.

Select your new series.

There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.

Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.

Hope that helps.

EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.

Adjust UILabel height to text

If you are using AutoLayout, you can adjust UILabel height by config UI only.

For iOS8 or above

  • Set constraint leading/trailing for your UILabel
  • And change the lines of UILabel from 1 to 0

enter image description here

For iOS7

  • First, you need to add contains height for UILabel
  • Then, modify the Relation from Equal to Greater than or Equal

enter image description here

  • Finally, change the lines of UILabel from 1 to 0

enter image description here

Your UILabel will automatically increase height depending on the text

Bootstrap modal: is not a function

The problem happened to me just in production just because I imported jquery with HTTP and not HTTPS (and production is HTTPS)

Group query results by month and year in postgresql

Take a look at example E of this tutorial -> https://www.postgresqltutorial.com/postgresql-group-by/

You need to call the function on your GROUP BY instead of calling the name of the virtual attribute you created on select. I was doing what all the answers above recommended and I was getting a column 'year_month' does not exist error.

What worked for me was:

SELECT 
    date_trunc('month', created_at), 'MM/YYYY' AS month
FROM 
    "orders"  
GROUP BY 
    date_trunc('month', created_at)

How to connect with Java into Active Directory

Here is a simple code that authenticate and make an LDAP search usin JNDI on a W2K3 :

class TestAD
{
  static DirContext ldapContext;
  public static void main (String[] args) throws NamingException
  {
    try
    {
      System.out.println("Début du test Active Directory");

      Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      //ldapEnv.put(Context.PROVIDER_URL,  "ldap://societe.fr:389");
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://dom.fr:389");
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
      //ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr");
      ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
      ldapContext = new InitialDirContext(ldapEnv);

      // Create the search controls         
      SearchControls searchCtls = new SearchControls();

      //Specify the attributes to return
      String returnedAtts[]={"sn","givenName", "samAccountName"};
      searchCtls.setReturningAttributes(returnedAtts);

      //Specify the search scope
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      //specify the LDAP search filter
      String searchFilter = "(&(objectClass=user))";

      //Specify the Base for the search
      String searchBase = "dc=dom,dc=fr";
      //initialize counter to total the results
      int totalResults = 0;

      // Search for objects using the filter
      NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);

      //Loop through the search results
      while (answer.hasMoreElements())
      {
        SearchResult sr = (SearchResult)answer.next();

        totalResults++;

        System.out.println(">>>" + sr.getName());
        Attributes attrs = sr.getAttributes();
        System.out.println(">>>>>>" + attrs.get("samAccountName"));
      }

      System.out.println("Total results: " + totalResults);
      ldapContext.close();
    }
    catch (Exception e)
    {
      System.out.println(" Search error: " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }
}

Make div 100% Width of Browser Window

There are new units that you can use:

vw - viewport width

vh - viewport height

#neo_main_container1
{
   width: 100%; //fallback
   width: 100vw;
}

Help / MDN

Opera Mini does not support this, but you can use it in all other modern browsers.

CanIUse

enter image description here

Configuring diff tool with .gitconfig

Reproducing my answer from this thread which was more specific to setting beyond compare as diff tool for Git. All the details that I've shared are equally useful for any diff tool in general so sharing it here:

The first command that we run is as below:

git config --global diff.tool bc3

The above command creates below entry in .gitconfig found in %userprofile% directory:

[diff]
    tool = bc3

Then you run below command (Running this command is redundant in this particular case and is required in some specialized cases only. You will know it in a short while):

git config --global difftool.bc3.path "c:/program files/beyond compare 3/bcomp.exe"

Above command creates below entry in .gitconfig file:

[difftool "bc3"]
    path = c:/program files/Beyond Compare 3/bcomp.exe

The thing to know here is the key bc3. This is a well known key to git corresponding to a particular version of well known comparison tools available in market (bc3 corresponds to 3rd version of Beyond Compare tool). If you want to see all pre-defined keys just run git difftool --tool-help command on git bash. It returns below list:

vimdiff
vimdiff2
vimdiff3
araxis
bc
bc3
codecompare
deltawalker
diffmerge
diffuse
ecmerge
emerge
examdiff
gvimdiff
gvimdiff2
gvimdiff3
kdiff3
kompare
meld
opendiff
p4merge
tkdiff
winmerge
xxdiff

You can use any of the above keys or define a custom key of your own. If you want to setup a new tool altogether(or a newly released version of well-known tool) which doesn't map to any of the keys listed above then you are free to map it to any of keys listed above or to a new custom key of your own.

What if you have to setup a comparison tool which is

  • Absolutely new in market

OR

  • A new version of an existing well known tool has got released which is not mapped to any pre-defined keys in git?

Like in my case, I had installed beyond compare 4. beyond compare is a well-known tool to git but its version 4 release is not mapped to any of the existing keys by default. So you can follow any of the below approaches:

  1. I can map beyond compare 4 tool to already existing key bc3 which corresponds to beyond compare 3 version. I didn't have beyond compare version 3 on my computer so I didn't care. If I wanted I could have mapped it to any of the pre-defined keys in the above list also e.g. examdiff.

    If you map well known version of tools to appropriate already existing/well- known key then you would not need to run the second command as their install path is already known to git.

    For e.g. if I had installed beyond compare version 3 on my box then having below configuration in my .gitconfig file would have been sufficient to get going:

    [diff]
    tool = bc3
    

    But if you want to change the default associated tool then you end up mentioning the path attribute separately so that git gets to know the path from where you new tool's exe has to be launched. Here is the entry which foxes git to launch beyond compare 4 instead. Note the exe's path:

    [difftool "bc3"]
    path = c:/program files/Beyond Compare 4/bcomp.exe
    
  2. Most cleanest approach is to define a new key altogether for the new comparison tool or a new version of an well known tool. Like in my case I defined a new key bc4 so that it is easy to remember. In such a case you have to run two commands in all but your second command will not be setting path of your new tool's executable. Instead you have to set cmd attribute for your new tool as shown below:

    git config --global diff.tool bc4
    
    git config --global difftool.bc4.cmd "\"C:\\Program Files\\Beyond Compare 4\\bcomp.exe\" -s \"\$LOCAL\" -d \"\$REMOTE\""
    

    Running above commands creates below entries in your .gitconfig file:

    [diff]
    tool = bc4
    [difftool "bc4"]
    cmd = \"C:\\Program Files\\Beyond Compare 4\\bcomp.exe\" -s \"$LOCAL\" -d \"$REMOTE\"
    

I would strongly recommend you to follow approach # 2 to avoid any confusion for yourself in future.

Reading json files in C++

  1. Yes you can create a nested data structure people which can be indexed by Anna and Ben. However, you can't index it directly by age and profession (I will get to this part in the code).

  2. The data type of people is of type Json::Value (which is defined in jsoncpp). You are right, it is similar to the nested map, but Value is a data structure which is defined such that multiple types can be stored and accessed. It is similar to a map with a string as the key and Json::Value as the value. It could also be a map between an unsigned int as key and Json::Value as the value (In case of json arrays).

Here's the code:

#include <json/value.h>
#include <fstream>

std::ifstream people_file("people.json", std::ifstream::binary);
people_file >> people;

cout<<people; //This will print the entire json object.

//The following lines will let you access the indexed objects.
cout<<people["Anna"]; //Prints the value for "Anna"
cout<<people["ben"]; //Prints the value for "Ben"
cout<<people["Anna"]["profession"]; //Prints the value corresponding to "profession" in the json for "Anna"

cout<<people["profession"]; //NULL! There is no element with key "profession". Hence a new empty element will be created.

As you can see, you can index the json object only based on the hierarchy of the input data.

Hyphen, underscore, or camelCase as word delimiter in URIs?

In general, it's not going to have enough of an impact to worry about, particularly since it's an intranet app and not a general-use Internet app. In particular, since it's intranet, SEO isn't a concern, since your intranet shouldn't be accessible to search engines. (and if it is, it isn't an intranet app).

And any framework worth it's salt either already has a default way to do this, or is fairly easy to change how it deals with multi-word URL components, so I wouldn't worry about it too much.

That said, here's how I see the various options:

Hyphen

  • The biggest danger for hyphens is that the same character (typically) is also used for subtraction and numerical negation (ie. minus or negative).
  • Hyphens feel awkward in URL components. They seem to only make sense at the end of a URL to separate words in the title of an article. Or, for example, the title of a Stack Overflow question that is added to the end of a URL for SEO and user-clarity purposes.

Underscore

  • Again, they feel wrong in URL components. They break up the flow (and beauty/simplicity) of a URL, since they essentially add a big, heavy apparent space in the middle of a clean, flowing URL.
  • They tend to blend in with underlines. If you expect your users to copy-paste your URLs into MS Word or other similar text-editing programs, or anywhere else that might pick up on a URL and style it with an underline (like links traditionally are), then you might want to avoid underscores as word separators. Particularly when printed, an underlined URL with underscores tends to look like it has spaces in it instead of underscores.

CamelCase

  • By far my favorite, since it makes the URLs seem to flow better and doesn't have any of the faults that the previous two options do.
  • Can be slightly harder to read for people that have a hard time differentiating upper-case from lower-case, but this shouldn't be much of an issue in a URL, because most "words" should be URL components and separated by a / anyways. If you find that you have a URL component that is more than 2 "words" long, you should probably try to find a better name for that concept.
  • It does have a possible issue with case sensitivity, but most platforms can be adjusted to be either case-sensitive or case-insensitive. Any it's only really an issue for 2 cases: a.) humans typing the URL in, and b.) Programmers (since we are not human) typing the URL in. Typos are always a problem, regardless of case sensitivity, so this is no different that all one case.

Read XML file using javascript

The code below will convert any XMLObject or string to a native JavaScript object. Then you can walk on the object to extract any value you want.

/**
 * Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
 * If a string is given, it first tries to create an XMLDomElement from the given string.
 * 
 * @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
 * @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
 * @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
 */
Object.fromXML = function( source, includeRoot ) {
    if( typeof source == 'string' )
    {
        try
        {
            if ( window.DOMParser )
                source = ( new DOMParser() ).parseFromString( source, "application/xml" );
            else if( window.ActiveXObject )
            {
                var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" );
                xmlObject.async = false;
                xmlObject.loadXML( source );
                source = xmlObject;
                xmlObject = undefined;
            }
            else
                throw new Error( "Cannot find an XML parser!" );
        }
        catch( error )
        {
            return false;
        }
    }

    var result = {};

    if( source.nodeType == 9 )
        source = source.firstChild;
    if( !includeRoot )
        source = source.firstChild;

    while( source ) {
        if( source.childNodes.length ) {
            if( source.tagName in result ) {
                if( result[source.tagName].constructor != Array ) 
                    result[source.tagName] = [result[source.tagName]];
                result[source.tagName].push( Object.fromXML( source ) );
            }
            else 
                result[source.tagName] = Object.fromXML( source );
        } else if( source.tagName )
            result[source.tagName] = source.nodeValue;
        else if( !source.nextSibling ) {
            if( source.nodeValue.clean() != "" ) {
                result = source.nodeValue.clean();
            }
        }
        source = source.nextSibling;
    }
    return result;
};

String.prototype.clean = function() {
    var self = this;
    return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "");
}

Dynamically Add Variable Name Value Pairs to JSON Object

With ECMAScript 6 there is a better way.

You can use computed property names in object property definitions, for example:

var name1 = 'John'; 
var value1 = '42'; 
var name2 = 'Sarah'; 
var value2 = '35';

var ipID = { 
             [name1] : value1, 
             [name2] : value2 
           }

This is equivalent to the following, where you have variables for the property names.

var ipID = { 
             John: '42', 
             Sarah: '35' 
           }

How to view Plugin Manager in Notepad++

Notepad v7.6 includes a Plugin Admin and from this you can install Plugin Manager(note1) but it doesn't work fine with npp v7.6(note2)

On the other hand Plugin Admin is only available on NPP "Setup version" and after following conditions

  • on Custom installation, "Plugin Admin" checkbox is enabled
  • on Choose Components "Don't use %APPDATA%" checkbox is disabled

Plugin Admin will place plugins at C:\ProgramData\Notepad++\plugins

(note1)Installation from Plugin Admin is not complete and \updater\gpup.exe is missing (note2) Plugin manager is not using new plugins path and folder structure; from version 7.6 npp Plugins will be stored in individual folders (having same name than file.dll)

If you want to use npp7.6 portable, you can copy updater folder from Setup version, copy plugins from Setup version, or copy Plugins from npp v<7.6 and place each one in a individual folder.

![Plugin Admin feature Installation npp76 Install Plugin manager from Plugin Admin

Remote branch is not showing up in "git branch -r"

If you clone with the --depth parameter, it sets .git/config not to fetch all branches, but only master.

You can simply omit the parameter or update the configuration file from

fetch = +refs/heads/master:refs/remotes/origin/master

to

fetch = +refs/heads/*:refs/remotes/origin/*

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

pip install pymysql

Then, edit the __init__.py file in your project origin dir(the same as settings.py)

add:

import pymysql

pymysql.install_as_MySQLdb()

Clean up a fork and restart it from the upstream

The simplest solution would be (using 'upstream' as the remote name referencing the original repo forked):

git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master  
git push origin master --force 

(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")

Be aware that you can lose changes done on the master branch (both locally, because of the reset --hard, and on the remote side, because of the push --force).

An alternative would be, if you want to preserve your commits on master, to replay those commits on top of the current upstream/master.
Replace the reset part by a git rebase upstream/master. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"


A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".

See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream" is.

upstream


Note: recent GitHub repos do protect the master branch against push --force.
So you will have to un-protect master first (see picture below), and then re-protect it after force-pushing).

enter image description here


Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.

Set value of hidden input with jquery

$('input[name="testing"]').val(theValue);

correct way of comparing string jquery operator =

NO, when you are using only one "=" you are assigning the variable.

You must use "==" : You must use "===" :

if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
 $("#code").text(data.DATA[0].ID);
}

You could use fonction like .toLowerCase() to avoid case problem if you want

How do I check what version of Python is running my script?

With six module, you can do it by:

import six

if six.PY2:
  # this is python2.x
else:
  # six.PY3
  # this is python3.x