Programs & Examples On #Countable

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

The Easiest Method:

Just run this below command line in terminal and come back to PhpMyAdmin. Now it works fine :)

sudo sed -i "s/|\s*\((count(\$analyzed_sql_results\['select_expr'\]\)/| (\1)/g" /usr/share/phpmyadmin/libraries/sql.lib.php

Manual Method:

Open sql.lib.php file

nano /usr/share/phpmyadmin/libraries/sql.lib.php

Find for count($analyzed_sql_results['select_expr'] code on file. You can get this at line ~613. You can see this below wrong code

|| (count($analyzed_sql_results['select_expr'] == 1)

Just replace that wrong code with this below one

|| ((count($analyzed_sql_results['select_expr']) == 1)

Save the file and come to PhpMyAdmin.

Now it works fine :)

How do you count the elements of an array in java

Java doesn't have the concept of a "count" of the used elements in an array.

To get this, Java uses an ArrayList. The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20). To get rid of the extra capacity, you use mylist.trimToSize().

Android java.exe finished with non-zero exit value 1

This is likely due to your app exceeding the 65k method count, thus causing a dex error. There is no solution, other than enabling multidexing in your app.

How to open a new file in vim in a new window

You can do so from within vim and use its own windows or tabs.

One way to go is to utilize the built-in file explorer; activate it via :Explore, or :Texplore for a tabbed interface (which I find most comfortable).

:Texplore (and :Sexplore) will also guard you from accidentally exiting the current buffer (editor) on :q once you're inside the explorer.

To toggle between open tabs when using tab pages use gt or gT (next tab and previous tab, respectively).

See also Using tab pages on the vim wiki.

node.js Error: connect ECONNREFUSED; response from server

i ran the local mysql database, but not in administrator mode, which threw this error

Swift - iOS - Dates and times in different format

You have already found NSDateFormatter, just read the documentation on it.

NSDateFormatter Class Reference

For format character definitions
See: ICU Formatting Dates and Times
Also: Date Field SymbolTable..

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

ValueError: math domain error

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. log(0) means that something raised to the power of 2 is 0. An exponent can never result in 0*, which means that log(0) has no answer, thus throwing the math domain error

*Note: 0^0 can result in 0, but can also result in 1 at the same time. This problem is heavily argued over.

Relational Database Design Patterns?

AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)

I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).

Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.

How to submit a form when the return key is pressed?

If you are using asp.net you can use the defaultButton attribute on the form.

How to get the current date and time of your timezone in Java?

using Calendar is simple:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();

Using Node.JS, how do I read a JSON file into (server) memory?

The easiest way I have found to do this is to just use require and the path to your JSON file.

For example, suppose you have the following JSON file.

test.json

{
  "firstName": "Joe",
  "lastName": "Smith"
}

You can then easily load this in your node.js application using require

var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);

Command to list all files in a folder as well as sub-folders in windows

An alternative to the above commands that is a little more bulletproof.

It can list all files irrespective of permissions or path length.

robocopy "C:\YourFolderPath" "C:\NULL" /E /L /NJH /NJS /FP /NS /NC /B /XJ

I have a slight issue with the use of C:\NULL which I have written about in my blog

https://theitronin.com/bulletproofdirectorylisting/

But nevertheless it's the most robust command I know.

Display help message with python argparse when script is called without any arguments

Instead of writing a class, a try/except can be used instead

try:
    options = parser.parse_args()
except:
    parser.print_help()
    sys.exit(0)

The upside is that the workflow is clearer and you don't need a stub class. The downside is that the first 'usage' line is printed twice.

This will need at least one mandatory argument. With no mandatory arguments, providing zero args on the commandline is valid.

Difference between \b and \B in regex

Source © Copyright RexEgg.com

Word Boundary: \b*

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

The regex \bcat\b would, therefore, match cat in a black cat, but it wouldn't match it in catatonic, tomcat or certificate. Removing one of the boundaries, \bcat would match cat in catfish, and cat\b would match cat in tomcat, but not vice-versa. Both, of course, would match cat on its own.

Not-a-word-boundary: \B

\B matches all positions where \b doesn't match. Therefore, it matches:

? When neither side is a word character, for instance at any position in the string $=(@-%++) (including the beginning and end of the string)

? When both sides are a word character, for instance between the H and the i in Hi!

This may not seem very useful, but sometimes \B is just what you want. For instance,

? \Bcat\B will find cat fully surrounded by word characters, as in certificate, but neither on its own nor at the beginning or end of words.

? cat\B will find cat both in certificate and catfish, but neither in tomcat nor on its own.

? \Bcat will find cat both in certificate and tomcat, but neither in catfish nor on its own.

? \Bcat|cat\B will find cat in embedded situation, e.g. in certificate, catfish or tomcat, but not on its own.

JavaScript equivalent to printf/String.Format

String.prototype.repeat = function(n) { 
    return new Array(++n).join(this); 
};

String.prototype.pad = function(requiredLength, paddingStr, paddingType) {    
    var n = requiredLength - this.length; 

    if (n) {
        paddingType = paddingType ? paddingType.toLowerCase() : '';
        paddingStr = paddingStr || ' ';
        paddingStr = paddingStr.repeat( Math.ceil(n / paddingStr.length) ).substr(0, n);

        if (paddingType == 'both') {
            n /= 2;
            return paddingStr.substr( 0, Math.ceil(n) ) + this + paddingStr.substr( 0, Math.floor(n) );
        }   

        if (paddingType == 'left') {
            return paddingStr + this;
        }

        return this + paddingStr;
    } 

    return this; 
}; 

// ????????? ?????????? printf
// '??????, %s!'.format('???') -> "??????, ???!"
// '%.1s.%.1s. %s'.format('????', '????????', '??????') -> "?.?. ??????"
String.prototype.format = function() {
    var i = 0, 
        params = arguments;

    return this.replace(/%(?:%|(?:(|[+-]+)(|0|'.+?)([1-9]\d*)?(?:\.([1-9]\d*))?)?(s|d|f))/g, function(match, sign, padding, width, precision, type) {
        if (match == '%%') { 
            return '%'; 
        }

        var v = params[i++];

        if (type == 'd') { 
            v = Math.round(v); 
        }
        else if (type == 'f') {
            v = v.toFixed(precision ? precision : 6);
        }

        if (/\+/.test(sign) && v > 0) {
            v = '+' + v;
        }

        v += '';

        if (type != 'f' && precision) {
            v = v.substr(0, precision);
        }

        if (width) {
            v = v.pad(width, padding == '' ? ' ' : padding[0] == "'" ? padding.substr(1) : padding, /-/.test(sign) ? 'right' : 'left'); 
        }

        return v;
    });
};

// this.name = '????';
// console.log( '??????, ${name}!'.template(this) );
// "??????, ????!"
String.prototype.template = function(context) {
    return this.replace(/\$\{(.*?)\}/g, function(match, name) {
        return context[name];
    });
};

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

If using mvn, check that you have the correct scope (if you have that defined) in your pom.xml. I once had it incorrectly set to test but needed it for runtime.

Put quotes around a variable string in JavaScript

Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:

function quote(text) {
  var urls = text.split(/ /)
  for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
  return urls.join(" ")
}

This function takes a string like "http://example.com http://blarg.test" and returns a string like "'http://example.com' 'http://blarg.test'".

It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.

Can't create handler inside thread that has not called Looper.prepare()

i use the following code to show message from non main thread "context",

@FunctionalInterface
public interface IShowMessage {
    Context getContext();

    default void showMessage(String message) {
        final Thread mThread = new Thread() {
            @Override
            public void run() {
                try {
                    Looper.prepare();
                    Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
                    Looper.loop();
                } catch (Exception error) {
                    error.printStackTrace();
                    Log.e("IShowMessage", error.getMessage());
                }
            }
        };
        mThread.start();
    }
}

then use as the following:

class myClass implements IShowMessage{

  showMessage("your message!");
 @Override
    public Context getContext() {
        return getApplicationContext();
    }
}

Cancel a UIView animation?

The way I do it is to create a new animation to your end point. Set a very short duration and make sure you use the +setAnimationBeginsFromCurrentState: method to start from the current state. When you set it to YES, the current animation is cut short. Looks something like this:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.1];
[UIView setAnimationCurve: UIViewAnimationCurveLinear];
// other animation properties

// set view properties

[UIView commitAnimations];

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

For more see here

How can I format the output of a bash command in neat columns

If your output is delimited by tabs a quick solution would be to use the tabs command to adjust the size of your tabs.

tabs 20
keys | awk '{ print $1"\t\t" $2 }'

Python string to unicode

>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…

d3.select("#element") not working when code above the html element

Not enough reputation to comment yet so I'll just put this here:

To expand on Micah's answer - the browser runs your code top to bottom, so if you write:

<div id="chart"></div>
<script>var svg = d3.select("#chart").append("svg:svg");</script>

The browser will create a div with id "chart", and then run your script, which will try to find that div, and, hurray, success.

Otherwise if you write:

<script>var svg = d3.select("#chart").append("svg:svg");</script>
<div id="chart"></div>

The browser runs your script, and tries to find a div with id chart, but it hasn't been created yet so it fails.

THEN the browser creates a div with id "chart".

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

How do I remove the height style from a DIV using jQuery?

you can try this:

$('div#someDiv').height('');

Install tkinter for Python

If you're using RHEL, CentOS, Oracle Linux, etc. You can use yum to install tkinter module

yum install tkinter

ASP.NET MVC View Engine Comparison

Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.

How do I add to the Windows PATH variable using setx? Having weird problems

Without admin rights the only way that worked for me is a bat file that contains the following code:

for /F "tokens=2* delims= " %%f IN ('reg query HKCU\Environment /v PATH ^| findstr /i path') do set OLD_SYSTEM_PATH=%%g
setx PATH "%USERPROFILE%\wev-tools;%OLD_SYSTEM_PATH%"

The code is the combination of the answers https://stackoverflow.com/a/45566845/4717152 and https://stackoverflow.com/a/10292113/4717152

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

Is there a command to undo git init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

What is a CSRF token? What is its importance and how does it work?

Cross-Site Request Forgery (CSRF) in simple words

  • Assume you are currently logged into your online banking at www.mybank.com
  • Assume a money transfer from mybank.com will result in a request of (conceptually) the form http://www.mybank.com/transfer?to=<SomeAccountnumber>;amount=<SomeAmount>. (Your account number is not needed, because it is implied by your login.)
  • You visit www.cute-cat-pictures.org, not knowing that it is a malicious site.
  • If the owner of that site knows the form of the above request (easy!) and correctly guesses you are logged into mybank.com (requires some luck!), they could include on their page a request like http://www.mybank.com/transfer?to=123456;amount=10000 (where 123456 is the number of their Cayman Islands account and 10000 is an amount that you previously thought you were glad to possess).
  • You retrieved that www.cute-cat-pictures.org page, so your browser will make that request.
  • Your bank cannot recognize this origin of the request: Your web browser will send the request along with your www.mybank.com cookie and it will look perfectly legitimate. There goes your money!

This is the world without CSRF tokens.

Now for the better one with CSRF tokens:

  • The transfer request is extended with a third argument: http://www.mybank.com/transfer?to=123456;amount=10000;token=31415926535897932384626433832795028841971.
  • That token is a huge, impossible-to-guess random number that mybank.com will include on their own web page when they serve it to you. It is different each time they serve any page to anybody.
  • The attacker is not able to guess the token, is not able to convince your web browser to surrender it (if the browser works correctly...), and so the attacker will not be able to create a valid request, because requests with the wrong token (or no token) will be refused by www.mybank.com.

Result: You keep your 10000 monetary units. I suggest you donate some of that to Wikipedia.

(Your mileage may vary.)

EDIT from comment worth reading:

It would be worthy to note that script from www.cute-cat-pictures.org normally does not have access to your anti-CSRF token from www.mybank.com because of HTTP access control. This note is important for some people who unreasonably send a header Access-Control-Allow-Origin: * for every website response without knowing what it is for, just because they can't use the API from another website.

useState set method not reflecting change immediately

I just finished a rewrite with useReducer, following @kentcdobs article (ref below) which really gave me a solid result that suffers not one bit from these closure problems.

see: https://kentcdodds.com/blog/how-to-use-react-context-effectively

I condensed his readable boilerplate to my preferred level of DRYness -- reading his sandbox implementation will show you how it actually works.

Enjoy, I know I am !!

import React from 'react'

// ref: https://kentcdodds.com/blog/how-to-use-react-context-effectively

const ApplicationDispatch = React.createContext()
const ApplicationContext = React.createContext()

function stateReducer(state, action) {
  if (state.hasOwnProperty(action.type)) {
    return { ...state, [action.type]: state[action.type] = action.newValue };
  }
  throw new Error(`Unhandled action type: ${action.type}`);
}

const initialState = {
  keyCode: '',
  testCode: '',
  testMode: false,
  phoneNumber: '',
  resultCode: null,
  mobileInfo: '',
  configName: '',
  appConfig: {},
};

function DispatchProvider({ children }) {
  const [state, dispatch] = React.useReducer(stateReducer, initialState);
  return (
    <ApplicationDispatch.Provider value={dispatch}>
      <ApplicationContext.Provider value={state}>
        {children}
      </ApplicationContext.Provider>
    </ApplicationDispatch.Provider>
  )
}

function useDispatchable(stateName) {
  const context = React.useContext(ApplicationContext);
  const dispatch = React.useContext(ApplicationDispatch);
  return [context[stateName], newValue => dispatch({ type: stateName, newValue })];
}

function useKeyCode() { return useDispatchable('keyCode'); }
function useTestCode() { return useDispatchable('testCode'); }
function useTestMode() { return useDispatchable('testMode'); }
function usePhoneNumber() { return useDispatchable('phoneNumber'); }
function useResultCode() { return useDispatchable('resultCode'); }
function useMobileInfo() { return useDispatchable('mobileInfo'); }
function useConfigName() { return useDispatchable('configName'); }
function useAppConfig() { return useDispatchable('appConfig'); }

export {
  DispatchProvider,
  useKeyCode,
  useTestCode,
  useTestMode,
  usePhoneNumber,
  useResultCode,
  useMobileInfo,
  useConfigName,
  useAppConfig,
}

with a usage similar to this:

import { useHistory } from "react-router-dom";

// https://react-bootstrap.github.io/components/alerts
import { Container, Row } from 'react-bootstrap';

import { useAppConfig, useKeyCode, usePhoneNumber } from '../../ApplicationDispatchProvider';

import { ControlSet } from '../../components/control-set';
import { keypadClass } from '../../utils/style-utils';
import { MaskedEntry } from '../../components/masked-entry';
import { Messaging } from '../../components/messaging';
import { SimpleKeypad, HandleKeyPress, ALT_ID } from '../../components/simple-keypad';

export const AltIdPage = () => {
  const history = useHistory();
  const [keyCode, setKeyCode] = useKeyCode();
  const [phoneNumber, setPhoneNumber] = usePhoneNumber();
  const [appConfig, setAppConfig] = useAppConfig();

  const keyPressed = btn => {
    const maxLen = appConfig.phoneNumberEntry.entryLen;
    const newValue = HandleKeyPress(btn, phoneNumber).slice(0, maxLen);
    setPhoneNumber(newValue);
  }

  const doSubmit = () => {
    history.push('s');
  }

  const disableBtns = phoneNumber.length < appConfig.phoneNumberEntry.entryLen;

  return (
    <Container fluid className="text-center">
      <Row>
        <Messaging {...{ msgColors: appConfig.pageColors, msgLines: appConfig.entryMsgs.altIdMsgs }} />
      </Row>
      <Row>
        <MaskedEntry {...{ ...appConfig.phoneNumberEntry, entryColors: appConfig.pageColors, entryLine: phoneNumber }} />
      </Row>
      <Row>
        <SimpleKeypad {...{ keyboardName: ALT_ID, themeName: appConfig.keyTheme, keyPressed, styleClass: keypadClass }} />
      </Row>
      <Row>
        <ControlSet {...{ btnColors: appConfig.buttonColors, disabled: disableBtns, btns: [{ text: 'Submit', click: doSubmit }] }} />
      </Row>
    </Container>
  );
};

AltIdPage.propTypes = {};

Now everything persists smoothly everywhere across all my pages

Nice!

Thanks Kent!

How to change font size in html?

Give them a class and add your style to the class.

<style>
  p {
    color: red;
  }
  .paragraph1 {
    font-size: 18px;
  }
  .paragraph2 {
    font-size: 13px;
  }
</style>

<p class="paragraph1">Paragraph 1</p>
<p class="paragraph2">Paragraph 2</p>

Check this EXAMPLE

Using multiple .cpp files in c++ program?

You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.

Like this-

Second.h:

void second();
int third();
double fourth();

main.cpp:

#include <iostream>
#include "second.h"
int main()
{
    //.....
    return 0;
}

second.cpp:

void second()
{
    //...
}

int third()
{ 
    //...
    return foo;
}

double fourth()
{ 
    //...
    return f;
}

Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

AppSettings get value from .config file

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"

CODE WILL BE GENERATED AUTOMATICALLY

    <configuration>
      <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup ..." ... >
          <section name="XX....Properties.Settings" type="System.Configuration.ClientSettingsSection ..." ... />
        </sectionGroup>
      </configSections>
      <applicationSettings>
        <XX....Properties.Settings>
          <setting name="name" serializeAs="String">
            <value>value</value>
          </setting>
          <setting name="name2" serializeAs="String">
            <value>value2</value>
          </setting>
       </XX....Properties.Settings>
      </applicationSettings>
    </configuration>

To get a value

Properties.Settings.Default.Name

OR

Properties.Settings.Default["name"]

How do I find a stored procedure containing <text>?

SELECT OBJECT_NAME(id)     
FROM syscomments 
WHERE [text] LIKE '%Name%' 
AND OBJECTPROPERTY(id, 'IsProcedure') = 1 
GROUP BY OBJECT_NAME(id)

Try This .....

How to create table using select query in SQL Server?

An example statement that uses a sub-select :

select * into MyNewTable
from
(
select 
  * 
from 
[SomeOtherTablename]
where 
  EventStartDatetime >= '01/JAN/2018' 
)
) mysourcedata
;

note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.

The database should reply with a message like: (9999 row(s) affected)

TypeScript and field initializers

To init a class without redeclaring all the properties for defaults:

class MyClass{ 
  prop1!: string  //required to be passed in
  prop2!: string  //required to be passed in
  prop3 = 'some default'
  prop4 = 123

  constructor(opts:{prop1:string, prop2:string} & Partial<MyClass>){
    Object.assign(this,opts)
  }
}

This combines some of the already excellent answers

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

jQuery location href

Use:

window.location.replace(...)

See this Stack Overflow question for more information:

How do I redirect to another webpage?

Or perhaps it was this you remember:

var url = "http://stackoverflow.com";
$(location).attr('href',url);

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

jQuery if div contains this text, replace that part of the text

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????

Here's a working example.

How do you do a ‘Pause’ with PowerShell 2.0?

You may want to use FlushInputBuffer to discard any characters mistakenly typed into the console, especially for long running operations, before using ReadKey:

Write-Host -NoNewLine 'Press any key to continue...'
$Host.UI.RawUI.FlushInputBuffer()
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') | Out-Null

Best XML Parser for PHP

I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement.

Which passwordchar shows a black dot (•) in a winforms textbox?

You can use this one: You can type it by pressing Alt key and typing 0149.

Open a new tab on button click in AngularJS

I solved this question this way.

<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>

$scope.openTab = function() {
    $scope.url = 'www.google.com';
}

How to pass password automatically for rsync SSH command?

The following works for me:

SSHPASS='myPassword'
/usr/bin/rsync -a -r -p -o -g --progress --modify-window=1 --exclude /folderOne -s -u --rsh="/usr/bin/sshpass -p $SSHPASS ssh -o StrictHostKeyChecking=no -l root"  source-path  myDomain:dest-path  >&2

I had to install sshpass

Change icon-bar (?) color in bootstrap

Dude I know totally how you feel, but don't forget about inline styling. It is almost the super saiyan of the CSS specificity

So it should look something like this for you,

<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>

Powershell script to locate specific file/file name?

From a powershell prompt, use the gci cmdlet (alias for Get-ChildItem) and -filter option:

gci -recurse -filter "hosts"

This will return an exact match to filename "hosts".


SteveMustafa points out with current versions of powershell you can use the -File switch to give the following to recursively search for only files named "hosts" (and not directories or other miscellaneous file-system entities):

gci -recurse -filter "hosts" -File 


The commands may print many red error messages like "Access to the path 'C:\Windows\Prefetch' is denied.".

If you want to avoid the error messages then set the -ErrorAction to be silent.

gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue


An additional helper is that you can set the root to search from using -Path. The resulting command to search explicitly search from, for example, the root of the C drive would be

gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"

How to parse/format dates with LocalDateTime? (Java 8)

GET CURRENT UTC TIME IN REQUIRED FORMAT

// Current UTC time
        OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);

        // GET LocalDateTime 
        LocalDateTime localDateTime = utc.toLocalDateTime();
        System.out.println("*************" + localDateTime);

        // formated UTC time
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF.format(localDateTime));

        //GET UTC time for current date
        Date now= new Date();
        LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

Is it possible to add an HTML link in the body of a MAILTO link

Here's what I put together. It works on the select mobile device I needed it for, but I'm not sure how universal the solution is

<a href="mailto:[email protected]?subject=Me&body=%3Chtml%20xmlns%3D%22http:%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%3C%2Fhead%3E%3Cbody%3EPlease%20%3Ca%20href%3D%22http:%2F%2Fwww.w3.org%22%3Eclick%3C%2Fa%3E%20me%3C%2Fbody%3E%3C%2Fhtml%3E">

'Field required a bean of type that could not be found.' error spring restful API using mongodb

Using all @ Annotations fixed my problem. (Yes, I'm new into Spring) If you are using a service class add @Service, and same for @Controller and @Repository.

Then this annotations on the App.java fixed the issue (I'm using JPA + Hibernate)

@SpringBootApplication
@EnableAutoConfiguration(exclude = { ErrorMvcAutoConfiguration.class })
@ComponentScan(basePackages = {"es.unileon.inso2"})
@EntityScan("es.unileon.inso2.model")
@EnableJpaRepositories("es.unileon.inso2.repository")

Package tree:

src/
+-- main/
¦   +-- java/
|       +-- es.unileon.inso2/
|       |   +-- App.java
|       +-- es.unileon.inso2.model/
|       |   +-- User.java
|       +-- es.unileon.inso2.controller/
|       |   +-- IndexController.java
|       |   +-- UserController.java
|       +-- es.unileon.inso2.service/
|       |    +-- UserService.java
|       +-- es.unileon.inso2.repository/
|            +-- UserRepository.java
+-- resources/
    +-- application.properties

What is the purpose of the vshost.exe file?

I'm not sure, but I believe it is a debugging optimization. However, I usually turn it off (see Debug properties for the project) and I don't notice any slowdown and I see no limitations when it comes to debugging.

Disable button after click in JQuery

You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true);

I have made a simple example http://jsfiddle.net/4gnXL/2/

How do Python functions handle the types of the parameters that you pass in?

The other answers have done a good job at explaining duck typing and the simple answer by tzot:

Python does not have variables, like other languages where variables have a type and a value; it has names pointing to objects, which know their type.

However, one interesting thing has changed since 2010 (when the question was first asked), namely the implementation of PEP 3107 (implemented in Python 3). You can now actually specify the type of a parameter and the type of the return type of a function like this:

def pick(l: list, index: int) -> int:
    return l[index]

We can here see that pick takes 2 parameters, a list l and an integer index. It should also return an integer.

So here it is implied that l is a list of integers which we can see without much effort, but for more complex functions it can be a bit confusing as to what the list should contain. We also want the default value of index to be 0. To solve this you may choose to write pick like this instead:

def pick(l: "list of ints", index: int = 0) -> int:
    return l[index]

Note that we now put in a string as the type of l, which is syntactically allowed, but it is not good for parsing programmatically (which we'll come back to later).

It is important to note that Python won't raise a TypeError if you pass a float into index, the reason for this is one of the main points in Python's design philosophy: "We're all consenting adults here", which means you are expected to be aware of what you can pass to a function and what you can't. If you really want to write code that throws TypeErrors you can use the isinstance function to check that the passed argument is of the proper type or a subclass of it like this:

def pick(l: list, index: int = 0) -> int:
    if not isinstance(l, list):
        raise TypeError
    return l[index]

More on why you should rarely do this and what you should do instead is talked about in the next section and in the comments.

PEP 3107 does not only improve code readability but also has several fitting use cases which you can read about here.


Type annotation got a lot more attention in Python 3.5 with the introduction of PEP 484 which introduces a standard module for type hints.

These type hints came from the type checker mypy (GitHub), which is now PEP 484 compliant.

With the typing module comes with a pretty comprehensive collection of type hints, including:

  • List, Tuple, Set, Map - for list, tuple, set and map respectively.
  • Iterable - useful for generators.
  • Any - when it could be anything.
  • Union - when it could be anything within a specified set of types, as opposed to Any.
  • Optional - when it might be None. Shorthand for Union[T, None].
  • TypeVar - used with generics.
  • Callable - used primarily for functions, but could be used for other callables.

These are the most common type hints. A complete listing can be found in the documentation for the typing module.

Here is the old example using the annotation methods introduced in the typing module:

from typing import List

def pick(l: List[int], index: int) -> int:
    return l[index]

One powerful feature is the Callable which allows you to type annotate methods that take a function as an argument. For example:

from typing import Callable, Any, Iterable

def imap(f: Callable[[Any], Any], l: Iterable[Any]) -> List[Any]:
    """An immediate version of map, don't pass it any infinite iterables!"""
    return list(map(f, l))

The above example could become more precise with the usage of TypeVar instead of Any, but this has been left as an exercise to the reader since I believe I've already filled my answer with too much information about the wonderful new features enabled by type hinting.


Previously when one documented Python code with for example Sphinx some of the above functionality could be obtained by writing docstrings formatted like this:

def pick(l, index):
    """
    :param l: list of integers
    :type l: list
    :param index: index at which to pick an integer from *l*
    :type index: int
    :returns: integer at *index* in *l*
    :rtype: int
    """
    return l[index]

As you can see, this takes a number of extra lines (the exact number depends on how explicit you want to be and how you format your docstring). But it should now be clear to you how PEP 3107 provides an alternative that is in many (all?) ways superior. This is especially true in combination with PEP 484 which, as we have seen, provides a standard module that defines a syntax for these type hints/annotations that can be used in such a way that it is unambiguous and precise yet flexible, making for a powerful combination.

In my personal opinion, this is one of the greatest features in Python ever. I can't wait for people to start harnessing the power of it. Sorry for the long answer, but this is what happens when I get excited.


An example of Python code which heavily uses type hinting can be found here.

How to give a pattern for new line in grep?

You can use this way...

grep -P '^\s$' file
  • -P is used for Perl regular expressions (an extension to POSIX grep).
  • \s match the white space characters; if followed by *, it matches an empty line also.
  • ^ matches the beginning of the line. $ matches the end of the line.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Fix of this problem is add SVN directory(C:\Program Files\TortoiseSVN\bin) to Path system property

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

Java difference between FileWriter and BufferedWriter

BufferedWriter is more efficient if you

  • have multiple writes between flush/close
  • the writes are small compared with the buffer size.

In your example, you have only one write, so the BufferedWriter just add overhead you don't need.

so does that mean the first example writes the characters one by one and the second first buffers it to the memory and writes it once

In both cases, the string is written at once.

If you use just FileWriter your write(String) calls

 public void write(String str, int off, int len) 
        // some code
        str.getChars(off, (off + len), cbuf, 0);
        write(cbuf, 0, len);
 }

This makes one system call, per call to write(String).


Where BufferedWriter improves efficiency is in multiple small writes.

for(int i = 0; i < 100; i++) {
    writer.write("foorbar");
    writer.write(NEW_LINE);
}
writer.close();

Without a BufferedWriter this could make 200 (2 * 100) system calls and writes to disk which is inefficient. With a BufferedWriter, these can all be buffered together and as the default buffer size is 8192 characters this become just 1 system call to write.

Query based on multiple where clauses in Firebase

var ref = new Firebase('https://your.firebaseio.com/');

Query query = ref.orderByChild('genre').equalTo('comedy');
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
            Movie movie = dataSnapshot.getValue(Movie.class);
            if (movie.getLead().equals('Jack Nicholson')) {
                console.log(movieSnapshot.getKey());
            }
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

NoClassDefFoundError - Eclipse and Android

I had this problem after updating ADT.

I was storing all of my JAR files in a folder called "lib" and adding the jars to the build path the normal Eclipse way. This worked fine until my update.

After my update, I was getting the NoClassDefFoundError for a class that I could clearly see was included in the jar (checking out the ReferencedLibraries classes).

The solution was to remove my jars from the build path and rename my "lib" folder to "libs". This is an ant convention, and seems to be the way the new ADT finds and includes libraries in an .apk file. Once I did this, everything worked fine.

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

How to determine an object's class?

Use Object.getClass(). It returns the runtime type of the object.

Does VBA have Dictionary Structure?

The scripting runtime dictionary seems to have a bug that can ruin your design at advanced stages.

If the dictionary value is an array, you cannot update values of elements contained in the array through a reference to the dictionary.

Oracle - Insert New Row with Auto Incremental ID

This is a simple way to do it without any triggers or sequences:

insert into WORKQUEUE (ID, facilitycode, workaction, description)
  values ((select max(ID)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES')

It worked for me but would not work with an empty table, I guess.

MVC3 DropDownListFor - a simple example?

     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value

How to create a new object instance from a Type

Compiled expression is best way! (for performance to repeatedly create instance in runtime).

static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(
   Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))
 ).Compile();

X x = YCreator();

Statistics (2012):

    Iterations: 5000000
    00:00:00.8481762, Activator.CreateInstance(string, string)
    00:00:00.8416930, Activator.CreateInstance(type)
    00:00:06.6236752, ConstructorInfo.Invoke
    00:00:00.1776255, Compiled expression
    00:00:00.0462197, new

Statistics (2015, .net 4.5, x64):

    Iterations: 5000000
    00:00:00.2659981, Activator.CreateInstance(string, string)
    00:00:00.2603770, Activator.CreateInstance(type)
    00:00:00.7478936, ConstructorInfo.Invoke
    00:00:00.0700757, Compiled expression
    00:00:00.0286710, new

Statistics (2015, .net 4.5, x86):

    Iterations: 5000000
    00:00:00.3541501, Activator.CreateInstance(string, string)
    00:00:00.3686861, Activator.CreateInstance(type)
    00:00:00.9492354, ConstructorInfo.Invoke
    00:00:00.0719072, Compiled expression
    00:00:00.0229387, new

Statistics (2017, LINQPad 5.22.02/x64/.NET 4.6):

    Iterations: 5000000
    No args
    00:00:00.3897563, Activator.CreateInstance(string assemblyName, string typeName)
    00:00:00.3500748, Activator.CreateInstance(Type type)
    00:00:01.0100714, ConstructorInfo.Invoke
    00:00:00.1375767, Compiled expression
    00:00:00.1337920, Compiled expression (type)
    00:00:00.0593664, new
    Single arg
    00:00:03.9300630, Activator.CreateInstance(Type type)
    00:00:01.3881770, ConstructorInfo.Invoke
    00:00:00.1425534, Compiled expression
    00:00:00.0717409, new

Statistics (2019, x64/.NET 4.8):

Iterations: 5000000
No args
00:00:00.3287835, Activator.CreateInstance(string assemblyName, string typeName)
00:00:00.3122015, Activator.CreateInstance(Type type)
00:00:00.8035712, ConstructorInfo.Invoke
00:00:00.0692854, Compiled expression
00:00:00.0662223, Compiled expression (type)
00:00:00.0337862, new
Single arg
00:00:03.8081959, Activator.CreateInstance(Type type)
00:00:01.2507642, ConstructorInfo.Invoke
00:00:00.0671756, Compiled expression
00:00:00.0301489, new

Statistics (2019, x64/.NET Core 3.0):

Iterations: 5000000
No args
00:00:00.3226895, Activator.CreateInstance(string assemblyName, string typeName)
00:00:00.2786803, Activator.CreateInstance(Type type)
00:00:00.6183554, ConstructorInfo.Invoke
00:00:00.0483217, Compiled expression
00:00:00.0485119, Compiled expression (type)
00:00:00.0434534, new
Single arg
00:00:03.4389401, Activator.CreateInstance(Type type)
00:00:01.0803609, ConstructorInfo.Invoke
00:00:00.0554756, Compiled expression
00:00:00.0462232, new

Full code:

static X CreateY_New()
{
    return new Y();
}

static X CreateY_New_Arg(int z)
{
    return new Y(z);
}

static X CreateY_CreateInstance()
{
    return (X)Activator.CreateInstance(typeof(Y));
}

static X CreateY_CreateInstance_String()
{
    return (X)Activator.CreateInstance("Program", "Y").Unwrap();
}

static X CreateY_CreateInstance_Arg(int z)
{
    return (X)Activator.CreateInstance(typeof(Y), new object[] { z, });
}

private static readonly System.Reflection.ConstructorInfo YConstructor =
    typeof(Y).GetConstructor(Type.EmptyTypes);
private static readonly object[] Empty = new object[] { };
static X CreateY_Invoke()
{
    return (X)YConstructor.Invoke(Empty);
}

private static readonly System.Reflection.ConstructorInfo YConstructor_Arg =
    typeof(Y).GetConstructor(new[] { typeof(int), });
static X CreateY_Invoke_Arg(int z)
{
    return (X)YConstructor_Arg.Invoke(new object[] { z, });
}

private static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(
   Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))
).Compile();
static X CreateY_CompiledExpression()
{
    return YCreator();
}

private static readonly Func<X> YCreator_Type = Expression.Lambda<Func<X>>(
   Expression.New(typeof(Y))
).Compile();
static X CreateY_CompiledExpression_Type()
{
    return YCreator_Type();
}

private static readonly ParameterExpression YCreator_Arg_Param = Expression.Parameter(typeof(int), "z");
private static readonly Func<int, X> YCreator_Arg = Expression.Lambda<Func<int, X>>(
   Expression.New(typeof(Y).GetConstructor(new[] { typeof(int), }), new[] { YCreator_Arg_Param, }),
   YCreator_Arg_Param
).Compile();
static X CreateY_CompiledExpression_Arg(int z)
{
    return YCreator_Arg(z);
}

static void Main(string[] args)
{
    const int iterations = 5000000;

    Console.WriteLine("Iterations: {0}", iterations);

    Console.WriteLine("No args");
    foreach (var creatorInfo in new[]
    {
        new {Name = "Activator.CreateInstance(string assemblyName, string typeName)", Creator = (Func<X>)CreateY_CreateInstance},
        new {Name = "Activator.CreateInstance(Type type)", Creator = (Func<X>)CreateY_CreateInstance},
        new {Name = "ConstructorInfo.Invoke", Creator = (Func<X>)CreateY_Invoke},
        new {Name = "Compiled expression", Creator = (Func<X>)CreateY_CompiledExpression},
        new {Name = "Compiled expression (type)", Creator = (Func<X>)CreateY_CompiledExpression_Type},
        new {Name = "new", Creator = (Func<X>)CreateY_New},
    })
    {
        var creator = creatorInfo.Creator;

        var sum = 0;
        for (var i = 0; i < 1000; i++)
            sum += creator().Z;

        var stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < iterations; ++i)
        {
            var x = creator();
            sum += x.Z;
        }
        stopwatch.Stop();
        Console.WriteLine("{0}, {1}", stopwatch.Elapsed, creatorInfo.Name);
    }

    Console.WriteLine("Single arg");
    foreach (var creatorInfo in new[]
    {
        new {Name = "Activator.CreateInstance(Type type)", Creator = (Func<int, X>)CreateY_CreateInstance_Arg},
        new {Name = "ConstructorInfo.Invoke", Creator = (Func<int, X>)CreateY_Invoke_Arg},
        new {Name = "Compiled expression", Creator = (Func<int, X>)CreateY_CompiledExpression_Arg},
        new {Name = "new", Creator = (Func<int, X>)CreateY_New_Arg},
    })
    {
        var creator = creatorInfo.Creator;

        var sum = 0;
        for (var i = 0; i < 1000; i++)
            sum += creator(i).Z;

        var stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < iterations; ++i)
        {
            var x = creator(i);
            sum += x.Z;
        }
        stopwatch.Stop();
        Console.WriteLine("{0}, {1}", stopwatch.Elapsed, creatorInfo.Name);
    }
}

public class X
{
  public X() { }
  public X(int z) { this.Z = z; }
  public int Z;
}

public class Y : X
{
    public Y() {}
    public Y(int z) : base(z) {}
}

Convert string to List<string> in one line?

I prefer this because it prevents a single item list with an empty item if your source string is empty:

  IEnumerable<string> namesList = 
      !string.isNullOrEmpty(names) ? names.Split(',') : Enumerable.Empty<string>();

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

You can include a legend template in the chart options:

//legendTemplate takes a template as a string, you can populate the template with values from your dataset 
var options = {
  legendTemplate : '<ul>'
                  +'<% for (var i=0; i<datasets.length; i++) { %>'
                    +'<li>'
                    +'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
                    +'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
                  +'</li>'
                +'<% } %>'
              +'</ul>'
  }

  //don't forget to pass options in when creating new Chart
  var lineChart = new Chart(element).Line(data, options);

  //then you just need to generate the legend
  var legend = lineChart.generateLegend();

  //and append it to your page somewhere
  $('#chart').append(legend);

You'll also need to add some basic css to get it looking ok.

TypeError: ObjectId('') is not JSON serializable

This is how I've recently fixed the error

    @app.route('/')
    def home():
        docs = []
        for doc in db.person.find():
            doc.pop('_id') 
            docs.append(doc)
        return jsonify(docs)

Tick symbol in HTML/XHTML

I normally use the fontawesome font(http://fontawesome.io/icon/check/), you can use it in html files:

 <i class="fa fa-check"></i>

or in css:

content: "\f00c";
font-family: FontAwesome;

jQuery returning "parsererror" for ajax request

the problem is that your controller returning string or other object that can't be parsed. the ajax call expected to get Json in return. try to return JsonResult in the controller like that:

 public JsonResult YourAction()
    {
        ...return Json(YourReturnObject);

    }

hope it helps :)

Asynchronous Process inside a javascript for loop

Any recommendation on how to fix this?

Several. You can use bind:

for (i = 0; i < j; i++) {
    asycronouseProcess(function (i) {
        alert(i);
    }.bind(null, i));
}

Or, if your browser supports let (it will be in the next ECMAScript version, however Firefox already supports it since a while) you could have:

for (i = 0; i < j; i++) {
    let k = i;
    asycronouseProcess(function() {
        alert(k);
    });
}

Or, you could do the job of bind manually (in case the browser doesn't support it, but I would say you can implement a shim in that case, it should be in the link above):

for (i = 0; i < j; i++) {
    asycronouseProcess(function(i) {
        return function () {
            alert(i)
        }
    }(i));
}

I usually prefer let when I can use it (e.g. for Firefox add-on); otherwise bind or a custom currying function (that doesn't need a context object).

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

How to set the action for a UIBarButtonItem in Swift

Swift 4/5 example

button.target = self
button.action = #selector(buttonClicked(sender:))

@objc func buttonClicked(sender: UIBarButtonItem) {
        
}

How to reload the current route with the angular 2 router

subscribe to route parameter changes

    // parent param listener ie: "/:id"
    this.route.params.subscribe(params => {
        // do something on parent param change
        let parent_id = params['id']; // set slug
    });

    // child param listener ie: "/:id/:id"
    this.route.firstChild.params.subscribe(params => {
        // do something on child param change
        let child_id = params['id'];
    });

Is there a goto statement in Java?

As was pointed out, there is no goto in Java, but the keyword was reserved in case Sun felt like adding goto to Java one day. They wanted to be able to add it without breaking too much code, so they reserved the keyword. Note that with Java 5 they added the enum keyword and it did not break that much code either.

Although Java has no goto, it has some constructs which correspond to some usages of goto, namely being able to break and continue with named loops. Also, finally can be thought of as a kind of twisted goto.

How to insert text into the textarea at the current cursor position?

A simple solution that work on firefox, chrome, opera, safari and edge but probably won't work on old IE browsers.

  var target = document.getElementById("mytextarea_id")

  if (target.setRangeText) {
     //if setRangeText function is supported by current browser
     target.setRangeText(data)
  } else {
    target.focus()
    document.execCommand('insertText', false /*no UI*/, data);
  }
}

setRangeText function allow you to replace current selection with the provided text or if no selection then insert the text at cursor position. It's only supported by firefox as far as I know.

For other browsers there is "insertText" command which only affect the html element currently focused and has same behavior as setRangeText

Inspired partially by this article

Finding blocking/locking queries in MS SQL (mssql)

You may find this query useful:

SELECT * 
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName' 
AND blocking_session_id <> 0

How to split a comma separated string and process in a loop using JavaScript

you can Try the following snippet:

var str = "How are you doing today?";
var res = str.split("o");
console.log("My Result:",res)

and your output like that

My Result: H,w are y,u d,ing t,day?

How to convert an int to string in C?

This is old but here's another way.

#include <stdio.h>

#define atoa(x) #x

int main(int argc, char *argv[])
{
    char *string = atoa(1234567890);
    printf("%s\n", string);
    return 0;
}

Creating multiple log files of different content with log4j

Demo link: https://github.com/RazvanSebastian/spring_multiple_log_files_demo.git

My solution is based on XML configuration using spring-boot-starter-log4j. The example is a basic example using spring-boot-starter and the two Loggers writes into different log files.

How to add the JDBC mysql driver to an Eclipse project?

you haven't loaded driver into memory. use this following in init()

Class.forName("com.mysql.jdbc.Driver");

Also, you missed a colon (:) in url, use this

String mySqlUrl = "jdbc:mysql://localhost:3306/mysql";

How to integrate sourcetree for gitlab

Those are optional settings. Leave it set as Unknown and you should be good.

Edit: If "unknown" is no longer an option, try leaving everything in that section blank.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

Window.open as modal popup?

That solution will open up a new browser window without the normal features such as address bar and similar.

To implement a modal popup, I suggest you to take a look at jQuery and SimpleModal, which is really slick.

(Here are some simple demos using SimpleModal: http://www.ericmmartin.com/projects/simplemodal-demos/)

C# Create New T()

Just for completion, the best solution here is often to require a factory function argument:

T GetObject<T>(Func<T> factory)
{  return factory(); }

and call it something like this:

string s = GetObject(() => "result");

You can use that to require or make use of available parameters, if needed.

Hibernate Criteria for Dates

If the column is a timestamp you can do the following:

        if(fromDate!=null){
            criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')"));
        }
        if(toDate!=null){               
            criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')"));
        }

        resultDB = criteria.list();

Trying to mock datetime.date.today(), but not working

You can use the following approach, based on Daniel G solution. This one has advantage of not breaking type checking with isinstance(d, datetime.date).

import mock

def fixed_today(today):
    from datetime import date

    class FakeDateType(type):
        def __instancecheck__(self, instance):
            return isinstance(instance, date)

    class FakeDate(date):
        __metaclass__ = FakeDateType

        def __new__(cls, *args, **kwargs):
            return date.__new__(date, *args, **kwargs)

        @staticmethod
        def today():
            return today

    return mock.patch("datetime.date", FakeDate)

Basically, we replace C-based datetime.date class with our own python subclass, that produces original datetime.date instances and responds to isinstance() queries exactly as native datetime.date.

Use it as context manager in your tests:

with fixed_today(datetime.date(2013, 11, 22)):
    # run the code under test
    # note, that these type checks will not break when patch is active:
    assert isinstance(datetime.date.today(), datetime.date)

Similar approach can be used to mock datetime.datetime.now() function.

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

RandomForestClassfier.fit(): ValueError: could not convert string to float

LabelEncoding worked for me (basically you've to encode your data feature-wise) (mydata is a 2d array of string datatype):

myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1);

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for i in range(*NUMBER OF FEATURES*):
    myData[:,i] = le.fit_transform(myData[:,i])

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

Check example link below and click on the div to get the color value in hex.

_x000D_
_x000D_
var color = '';_x000D_
$('div').click(function() {_x000D_
  var x = $(this).css('backgroundColor');_x000D_
  hexc(x);_x000D_
  console.log(color);_x000D_
})_x000D_
_x000D_
function hexc(colorval) {_x000D_
  var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);_x000D_
  delete(parts[0]);_x000D_
  for (var i = 1; i <= 3; ++i) {_x000D_
    parts[i] = parseInt(parts[i]).toString(16);_x000D_
    if (parts[i].length == 1) parts[i] = '0' + parts[i];_x000D_
  }_x000D_
  color = '#' + parts.join('');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class='div' style='background-color: #f5b405'>Click me!</div>
_x000D_
_x000D_
_x000D_

Check working example at http://jsfiddle.net/DCaQb/

How to execute an oracle stored procedure?

I use oracle 12 and it tell me that if you need to invoke the procedure then use call keyword. In your case it should be:

begin
  call temp_proc;
end;

import error: 'No module named' *does* exist

I had the same issue. I solved it by running the command in a different python version. I tried python3 filename.py. Earlier i was using Python 2.7.

Another possibility is that the file from which something is imported may contain BOM (Byte Order Mark). It can be solved by opening the file in some editor which supports multiple encoding like VSCode (Notepad++) and saving in a different encoding statndard like ANSI, UTF-8(without BOM).

How do I format a Microsoft JSON date?

var newDate = dateFormat(jsonDate, "mm/dd/yyyy"); 

Is there another option without using the jQuery library?

java comparator, how to sort by integer?

Simply changing

public int compare(Dog d, Dog d1) {
  return d.age - d1.age;
}

to

public int compare(Dog d, Dog d1) {
  return d1.age - d.age;
}

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable<Dog> {
    private String name;
    private int age;

    public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {
        // Overriding the compare method to sort the age
        public int compare(Dog d, Dog d1) {
            return d.age - d1.age;
        }
    };

    Dog(String n, int a) {
        name = n;
        age = a;
    }

    public String getDogName() {
        return name;
    }

    public int getDogAge() {
        return age;
    }

    // Overriding the compareTo method
    public int compareTo(Dog d) {
        return (this.name).compareTo(d.name);
    }

}

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator
Collections.sort(list, Dog.DESCENDING_COMPARATOR);

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2: Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3: With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator<Dog> DESCENDING_COMPARATOR = 
    Comparator.comparing(Dog::getDogAge).reversed();

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {
    return DESCENDING_COMPARATOR.compare(d, d1);
}

Adding headers when using httpClient.GetAsync

A later answer, but because no one gave this solution...

If you do not want to set the header on the HttpClient instance by adding it to the DefaultRequestHeaders, you could set headers per request.

But you will be obliged to use the SendAsync() method.

This is the right solution if you want to reuse the HttpClient -- which is a good practice for

Use it like this:

using (var requestMessage =
            new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
    requestMessage.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", your_token);
    httpClient.SendAsync(requestMessage);
}

Converting array to list in Java

Another workaround if you use apache commons-lang:

int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(ArrayUtils.toObject(spam));

Where ArrayUtils.toObject converts int[] to Integer[]

Rails 4: before_filter vs. before_action

As we can see in ActionController::Base, before_action is just a new syntax for before_filter.

However all before_filters syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1

How do you stylize a font in Swift?

Xamarin

Label.Font = UIFont.FromName("Copperplate", 10.0f);

Swift

text.font = UIFont.init(name: "Poppins-Regular", size: 14)

To get the list of font family Github/IOS-UIFont-Names

Opacity of div's background without affecting contained element in IE 8?

Try setting the z-index higher on the contained element.

IIS - 401.3 - Unauthorized

Just in case anyone else runs into this. I troubleshooted all of these steps and it turns out because I unzipped some files from a MAC, Microsoft automatically without any notification Encrypted the files. After hours of trying to set folder permissions I went in and saw the file names were green which means the files were encrypted and IIS will throw the same error even if folder permissions are correct.

How to perform Unwind segue programmatically?

  1. Create a manual segue (ctrl-drag from File’s Owner to Exit),
  2. Choose it in the Left Controller Menu below green EXIT button.

Choose it in the Left Controller Menu below green EXIT button

Insert Name of Segue to unwind.

Then,- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender. with your segue identify.

How to read/write arbitrary bits in C/C++

You need to shift and mask the value, so for example...

If you want to read the first two bits, you just need to mask them off like so:

int value = input & 0x3;

If you want to offset it you need to shift right N bits and then mask off the bits you want:

int value = (intput >> 1) & 0x3;

To read three bits like you asked in your question.

int value = (input >> 1) & 0x7;

How do I erase an element from std::vector<> by index?

The erase method will be used in two ways:

  1. Erasing single element:

    vector.erase( vector.begin() + 3 ); // Deleting the fourth element
    
  2. Erasing range of elements:

    vector.erase( vector.begin() + 3, vector.begin() + 5 ); // Deleting from fourth element to sixth element
    

Calling constructors in c++ without new

Ideally, a compiler would optimize the second, but it's not required. The first is the best way. However, it's pretty critical to understand the distinction between stack and heap in C++, sine you must manage your own heap memory.

How to create custom view programmatically in swift having controls text field, button etc

view = MyCustomView(frame: CGRectZero)

In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.

Fixing slow initial load for IIS

Writing a ping service/script to hit your idle website is rather a best way to go because you will have a complete control. Other options that you have mentioned would be available if you have leased a dedicated hosting box.

In a shared hosting space, warmup scripts are the best first level defense (self help is the best help). Here is an article which shares an idea on how to do it from your own web application.

How to provide password to a command that prompts for one in bash?

Take a look at autoexpect (decent tutorial HERE). It's about as quick-and-dirty as you can get without resorting to trickery.

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

How do I concatenate strings in Swift?

This will work too:

var string = "swift"
var resultStr = string + " is a new Programming Language"

How to write a full path in a batch file having a folder name with space?

I made a **

automatic-network-drive connector

** using a batch file.

Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!

looks a little bit different but works:

net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES

Thx for the Hint :)

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

To make @Raghavendra's answer more specific:

Once you've downloaded 2 zip files,

copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.

You'll still get the same warning, however, the installation will run completely without generating any errors.

What does the "+" (plus sign) CSS selector mean?

The Plus (+) will select the first immediate element. When you use + selector you have to give two parameters. This will be more clear by example: here div and span are parameters, so in this case only first span after the div will be styled.

 div+ span{
   color: green;
   padding :100px;
}

     <div>The top or first element  </div>
       <span >this is span immediately after div, this will be selected</span>
       <span>This will not be selected</span>

Above style will only apply to first span after div. It is important to note that second span will not be selected.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

You can use JavaScript functions like replace, and you can wrap the jQuery code in brackets:

var value = ($("#text").val()).replace(".", ":");

Extract digits from string - StringUtils Java

You can use str = str.replaceAll("\\D+","");

Changing Background Image with CSS3 Animations

It works in Chrome 19.0.1084.41 beta!

So at some point in the future, keyframes could really be... frames!

You are living in the future ;)

using if else with eval in aspx page

You can try c#

public string ProcessMyDataItem(object myValue)
 {
  if (myValue == null)
   {
   return "0 %"";
  }
   else
  {
     if(Convert.ToInt32(myValue) < 50)
       return "0";
     else
      return myValue.ToString() + "%";
  }

 }

asp

 <div class="tooltip" style="display: none">                                                                  
      <div style="text-align: center; font-weight: normal">
   Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
 </div>

IntelliJ - show where errors are

Besides, you can choose going to next error only (ignore warning) by:

  1. Right click the Validation Side Bar.
  2. On the context menu, choose the Go to high priority problems only

it works for Intellij Idea 12

Change header text of columns in a GridView

I Think this Works:

 testGV.HeaderRow.Cells[0].Text="Date"

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

How to convert a SVG to a PNG with ImageMagick?

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"

Amazon products API - Looking for basic overview and information

I wrote a blog post on this subject, after spending hours wading through Amazon's obscure documentation. Maybe useful as another view on the process.

How do you create a Spring MVC project in Eclipse?

This is the easiest way :

step 1) install Spring Tool Suite (STS) for eclipse (version 3.7.0RELEASE or above) To do this you can go to Help >> eclipse market place , then type Spring Tool suite in search box.

step 2) now go to file >> new >> spring project as shown in the image below enter image description here

step 3)now choose the template as "spring MVC Project" and give a name to your project on the top as shown below ( I named it 'SpringProject') enter image description here

step 4)now give a base package name like this enter image description here

and that is . The project will be created in a few minutes and Now you can right click on it and run on server.

When should I use the new keyword in C++?

Which method should I use?

This is almost never determined by your typing preferences but by the context. If you need to keep the object across a few stacks or if it's too heavy for the stack you allocate it on the free store. Also, since you are allocating an object, you are also responsible for releasing the memory. Lookup the delete operator.

To ease the burden of using free-store management people have invented stuff like auto_ptr and unique_ptr. I strongly recommend you take a look at these. They might even be of help to your typing issues ;-)

How do I tell what type of value is in a Perl variable?

$x is always a scalar. The hint is the sigil $: any variable (or dereferencing of some other type) starting with $ is a scalar. (See perldoc perldata for more about data types.)

A reference is just a particular type of scalar. The built-in function ref will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype will tell you what type of reference it is:

use Scalar::Util qw(reftype);

my $x = bless {}, 'My::Foo';
my $y = { };

print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";

...produces the output:

type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH

For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.

Note: You should not use ref to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";) -- if you need to make any decisions based on the type of a variable, use isa (i.e if ($a->isa("My::Foo") { ... or if ($a->can("foo") { ...). Also see polymorphism.

Subset and ggplot2

Here 2 options for subsetting:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

You can also use the complementary subsetting:

subset(dat,ID != "P2")

How to post SOAP Request from PHP

Below is a quick example of how to do this (which best explained the matter to me) that I essentially found at this website. That website link also explains WSDL, which is important for working with SOAP services.

However, I don't think the API address they were using in the example below still works, so just switch in one of your own choosing.

$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';

$trace = true;
$exceptions = false;

$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;

$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
$response = $client->GetPlaceList($xml_array);

var_dump($response);

Using fonts with Rails asset pipeline

Here my approach to using fonts in asset pipeline:

1) Put all your font file under app/assets/fonts/, actually you are not restricted to put it under fonts folder name. You can put any subfolder name you like. E.g. app/assets/abc or app/assets/anotherfonts. But i highly recommend you put it under app/assets/fonts/ for better folder structure.

2) From your sass file, using the sass helper font-path to request your font assets like this

@font-face {
    font-family: 'FontAwesome';
    src: url(font-path('fontawesome-webfont.eot') + '?v=4.4.0');
    src: url(font-path('fontawesome-webfont.eot') + '?#iefix&v=4.4.0') format('embedded-opentype'),
         url(font-path('fontawesome-webfont.woff2') + '?v=4.4.0') format('woff2'),
         url(font-path('fontawesome-webfont.woff') + '?v=4.4.0') format('woff'),
         url(font-path('fontawesome-webfont.ttf') + '?v=4.4.0') format('truetype'),
         url(font-path('fontawesome-webfont.svg') + '?v=4.4.0#fontawesomeregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

3) Run bundle exec rake assets:precompile from your local machine and see your application.css result. You should see something like this:

@font-face {
    font-family: 'FontAwesome';
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?v=4.4.0");
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?#iefix&v=4.4.0") format("embedded-opentype"), url("/assets/fontawesome-webfont-3c4a1bb7ce3234407184f0d80cc4dec075e4ad616b44dcc5778e1cfb1bc24019.woff2" "?v=4.4.0") format("woff2"), url("/assets/fontawesome-webfont-a7c7e4930090e038a280fd61d88f0dc03dad4aeaedbd8c9be3dd9aa4c3b6f8d1.woff" "?v=4.4.0") format("woff"), url("/assets/fontawesome-webfont-1b7f3de49d68b01f415574ebb82e6110a1d09cda2071ad8451bdb5124131a292.ttf" "?v=4.4.0") format("truetype"), url("/assets/fontawesome-webfont-7414288c272f6cc10304aa18e89bf24fb30f40afd644623f425c2c3d71fbe06a.svg" "?v=4.4.0#fontawesomeregular") format("svg");
    font-weight: normal;
    font-style: normal;
}

If you want to know more how asset pipeline work, you can visit the following simple guide: https://designcode.commandrun.com/rails-asset-pipeline-simple-guide-830e2e666f6c#.6lejlayk2

UIButton action in table view cell

class TableViewCell: UITableViewCell {
   @IBOutlet weak var oneButton: UIButton!
   @IBOutlet weak var twoButton: UIButton!
}


class TableViewController: UITableViewController {

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell

    cell.oneButton.addTarget(self, action: #selector(TableViewController.oneTapped(_:)), for: .touchUpInside)
    cell.twoButton.addTarget(self, action: #selector(TableViewController.twoTapped(_:)), for: .touchUpInside)

    return cell
}

func oneTapped(_ sender: Any?) {

    print("Tapped")
}

func twoTapped(_ sender: Any?) {

    print("Tapped")
   }
}

In Bash, how do I add a string after each line in a file?

I prefer using awk. If there is only one column, use $0, else replace it with the last column.

One way,

awk '{print $0, "string to append after each line"}' file > new_file

or this,

awk '$0=$0"string to append after each line"' file > new_file

Is there an equivalent of lsusb for OS X

In mac osx , you can use the following command:

system_profiler SPUSBDataType

PHP UML Generator

Well to be honest, first and foremost you shouldn't generate UML model from code, but code from UML model ;).

Even if you are in a rare situation, when you need to do this reverse engineering, it is generally suggested that you do it by hand or at least tidy-up the diagrams, as auto-generated UML has really poor visual (=information) value most of the time.

If you just need to generate the diagrams, it's probably a good thing to ask yourself why exactly? Who is the intended audience and what is the goal? What does the auto-generated diagram have to offer, what code doesn't?

Basicly I accept only one answer to that question. It just got too big and incomprehensible.

Which again is a reason to start with UML in the first place, as opposed to start coding ;) It's called analysis and it's on decline, because every second guy in business thinks it's a bit too expensive and not really necessary.

Child inside parent with min-height: 100% not inheriting height

thought I would share this, as I didnt see this anywhere, and is what I used to fix my solution.

SOLUTION: min-height: inherit;

I had a parent with a specified min height, and I needed a child to also be that height.

_x000D_
_x000D_
.parent {_x000D_
  min-height: 300px;_x000D_
  background-color: rgba(255,255,0,0.5); //yellow_x000D_
}_x000D_
_x000D_
.child {_x000D_
  min-height: inherit;_x000D_
  background-color: rgba(0,255,0,0.5); //blue_x000D_
}_x000D_
_x000D_
p {_x000D_
  padding: 20px;_x000D_
  color: red;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">_x000D_
    <p>Yellow + Blue = Green :)</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This way the child now acts as height 100% of the min-height.

I hope some people find this useful :)

Got a NumberFormatException while trying to parse a text file for objects

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

Cannot get a text value from a numeric cell “Poi”

If you are processing in rows with cellIterator....then this worked for me ....

  DataFormatter formatter = new DataFormatter();   
  while(cellIterator.hasNext())
  {                         
        cell = cellIterator.next();
        String val = "";            
        switch(cell.getCellType()) 
        {
            case Cell.CELL_TYPE_NUMERIC:
                val = String.valueOf(formatter.formatCellValue(cell));
                break;
            case Cell.CELL_TYPE_STRING:
                val = formatter.formatCellValue(cell);
                break;
        }
    .....
    .....
  }

How to prevent caching of my Javascript file?

Add a random query string to the src

You could either do this manually by incrementing the querystring each time you make a change:

<script src="test.js?version=1"></script>

Or if you are using a server side language, you could automatically generate this:

ASP.NET:

<script src="test.js?rndstr=<%= getRandomStr() %>"></script>

More info on cache-busting can be found here:

https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/

How to convert minutes to Hours and minutes (hh:mm) in java

Use java.text.SimpleDateFormat to convert minute into hours and minute

SimpleDateFormat sdf = new SimpleDateFormat("mm");

try {
    Date dt = sdf.parse("90");
    sdf = new SimpleDateFormat("HH:mm");
    System.out.println(sdf.format(dt));
} catch (ParseException e) {
    e.printStackTrace();
}

Get line number while using grep

grep -A20 -B20 pattern file.txt

Search pattern and show 20 lines after and before pattern

How to get the path of running java program

    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){
        System.out.println(url.getFile());
    }

Is there a MessageBox equivalent in WPF?

The equivalent to WinForms' MessageBox in WPF is called System.Windows.MessageBox.

Metadata file '.dll' could not be found

I got this problem in Visual Studio 2012 in a solution that had many projects. Rebuilding each project in the solution manually in the same order as the Project Build Order (right-click and rebuild in Solution Explorer) fixed it for me.

Eventually I got to one that gave me a compile error. I fixed the error, and the solution would build correctly after that.

Aligning a button to the center

Here is what worked for me:

    <input type="submit" style="margin-left: 50%">

If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended. You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

As of 2018-05 this is handled directly with decode, at least for Python 3.

I'm using the below snippet for invalid start byte and invalid continuation byte type errors. Adding errors='ignore' fixed it for me.

with open(out_file, 'rb') as f:
    for line in f:
        print(line.decode(errors='ignore'))

Error CS1705: "which has a higher version than referenced assembly"

I got this after adding Episerver Find to our site and installing the corresponding NuGet package for Episerver Find.

The fix was easy: update all Episerver related add-ons as well (even if they seem unrelated: CMS, CMS.TinyMCE, CMS.UI, etc.)

After updating all possible Episerver add-ons and recompiling, the error went away.

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

This worked for me:

I simply cd "C:\the_path_of_the_project_where_package.json_is"

before I ran "npm start"

Apply CSS to jQuery Dialog Buttons

Why not just inspect the generated markup, note the class on the button of choice and style it yourself?

Which loop is faster, while or for?

I also tried to benchmark the different kinds of loop in C#. I used the same code as Shane, but I also tried with a do-while and found it to be the fastest. This is the code:

using System;
using System.Diagnostics;


public class Program
{
    public static void Main()
    {
        int max = 9999999;
        Stopwatch stopWatch = new Stopwatch();

        Console.WriteLine("Do While Loop: ");
        stopWatch.Start();
        DoWhileLoop(max);
        stopWatch.Stop();
        DisplayElapsedTime(stopWatch.Elapsed);
        Console.WriteLine("");
        Console.WriteLine("");

        Console.WriteLine("While Loop: ");
        stopWatch.Start();
        WhileLoop(max);
        stopWatch.Stop();
        DisplayElapsedTime(stopWatch.Elapsed);
        Console.WriteLine("");
        Console.WriteLine("");

        Console.WriteLine("For Loop: ");
        stopWatch.Start();
        ForLoop(max);
        stopWatch.Stop();
        DisplayElapsedTime(stopWatch.Elapsed);
    }

    private static void DoWhileLoop(int max)
    {
        int i = 0;
        do
        {
            //Performe Some Operation. By removing Speed increases
            var j = 10 + 10;
            j += 25;
            i++;
        } while (i <= max);
    }

    private static void WhileLoop(int max)
    {
        int i = 0;
        while (i <= max)
        {
            //Performe Some Operation. By removing Speed increases
            var j = 10 + 10;
            j += 25;
            i++;
        };
    }

    private static void ForLoop(int max)
    {
        for (int i = 0; i <= max; i++)
        {
            //Performe Some Operation. By removing Speed increases
            var j = 10 + 10;
            j += 25;
        }
    }

    private static void DisplayElapsedTime(TimeSpan ts)
    {
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
        Console.WriteLine(elapsedTime, "RunTime");
    }
}

and these are the results of a live demo on DotNetFiddle:

Do While Loop:
00:00:00.06

While Loop:
00:00:00.13

For Loop:
00:00:00.27

Spring: @Component versus @Bean

Additional Points from above answers

Let’s say we got a module which is shared in multiple apps and it contains a few services. Not all are needed for each app.

If use @Component on those service classes and the component scan in the application,

we might end up detecting more beans than necessary

In this case, you either had to adjust the filtering of the component scan or provide the configuration that even the unused beans can run. Otherwise, the application context won’t start.

In this case, it is better to work with @Bean annotation and only instantiate those beans,

which are required individually in each app

So, essentially, use @Bean for adding third-party classes to the context. And @Component if it is just inside your single application.

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

The reason on using the return:false; is well explained on this other question.

For the other issue, you can check for the referrer to see if it is empty:

    function backAway(){
        if (document.referrer == "") { //alternatively, window.history.length == 0
            window.location = "http://www.example.com";
        } else {
            history.back();
        }
    }

<a href="#" onClick="backAway()">Back Button Here.</a>

How to get form input array into PHP array

I came across this problem as well. Given 3 inputs: field[], field2[], field3[]

You can access each of these fields dynamically. Since each field will be an array, the related fields will all share the same array key. For example, given input data:

Bob and his email and sex will share the same key. With this in mind, you can access the data in a for loop like this:

    for($x = 0; $x < count($first_name); $x++ )
    {
        echo $first_name[$x];
        echo $email[$x];
        echo $sex[$x];
        echo "<br/>";
    }

This scales as well. All you need to do is add your respective array vars whenever you need new fields to be added.

How to create a DataFrame from a text file in Spark

Update - as of Spark 1.6, you can simply use the built-in csv data source:

spark: SparkSession = // create the Spark Session
val df = spark.read.csv("file.txt")

You can also use various options to control the CSV parsing, e.g.:

val df = spark.read.option("header", "false").csv("file.txt")

For Spark version < 1.6: The easiest way is to use spark-csv - include it in your dependencies and follow the README, it allows setting a custom delimiter (;), can read CSV headers (if you have them), and it can infer the schema types (with the cost of an extra scan of the data).

Alternatively, if you know the schema you can create a case-class that represents it and map your RDD elements into instances of this class before transforming into a DataFrame, e.g.:

case class Record(id: Int, name: String)

val myFile1 = myFile.map(x=>x.split(";")).map {
  case Array(id, name) => Record(id.toInt, name)
} 

myFile1.toDF() // DataFrame will have columns "id" and "name"

How to format font style and color in echo

 echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";

MySQL: Check if the user exists and drop it

If you mean you want to delete a drop from a table if it exists, you can use the DELETE command, for example:

 DELETE FROM users WHERE user_login = 'foobar'

If no rows match, it's not an error.

ReSharper "Cannot resolve symbol" even when project builds

For me, I think my solution just got caught in a weird state when I was changing which branch of my local Git repo I was on. Simply switching to the previous branch I was on before the problem started, telling VS to reload all the files, then switching back to the desired branch and reloading again fixed it.

Get lengths of a list in a jinja2 template

I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()

My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:

{{'0' if linked_contacts == None else linked_contacts|length}}

How to capture the "virtual keyboard show/hide" event in Android?

what I did is created simple binding to hide view when keyboard is visible. Solution is based on current AndroidX implementation for WindowInsetsCompat which is still in beta (androidx core 1.5) - source

private fun isKeyboardVisible(insets: WindowInsets): Boolean {
    val insetsCompat = WindowInsetsCompat.toWindowInsetsCompat(insets)
    val systemWindow = insetsCompat.systemWindowInsets
    val rootStable = insetsCompat.stableInsets
    if (systemWindow.bottom > rootStable.bottom) {
        // This handles the adjustResize case on < API 30, since
        // systemWindow.bottom is probably going to be the IME
        return true
    }
    return false
}

@BindingAdapter("goneWhenKeyboardVisible")
fun View.goneWhenKeyboardVisible(enabled: Boolean) {
    if (enabled) {
        setOnApplyWindowInsetsListener { view, insets ->
            visibility = if (isKeyboardVisible(insets)) GONE else VISIBLE
            insets
        }
    } else {
        setOnApplyWindowInsetsListener(null)
        visibility = VISIBLE
    }
}

usage:

<FrameLayout
                android:id="@+id/bottom_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:goneWhenKeyboardVisible="@{true}"
                />

Delete the first three rows of a dataframe in pandas

inp0= pd.read_csv("bank_marketing_updated_v1.csv",skiprows=2)

or if you want to do in existing dataframe

simply do following command

What does "javax.naming.NoInitialContextException" mean?

It basically means that the application wants to perform some "naming operations" (e.g. JNDI or LDAP lookups), and it didn't have sufficient information available to be able to create a connection to the directory server. As the docs for the exception state,

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

And if you dutifully have a look at the javadocs for InitialContext, they describe quite well how the initial context is constructed, and what your options are for supplying the address/credentials/etc.

If you have a go at creating the context and get stuck somewhere else, please post back explaining what you've done so far and where you're running aground.

Setting the character encoding in form submit for Internet Explorer

I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.

Looks like IE can't handle ISO-8859-1. But it can handle ISO-8859-15.

<form accept-charset="ISO-8859-15">
  ...
</form>

So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.

C# DataRow Empty-check

A simple method along the lines of:

bool AreAllColumnsEmpty(DataRow dr)
{
 if (dr == null)
 {
  return true;
 }
 else
 {
  foreach(var value in dr.ItemArray)
  {
    if (value != null)
    {
      return false;
    }
  }
  return true;
 }
}

Should give you what you're after, and to make it "nice" (as there's nothing as far as I'm aware, in the Framework), you could wrap it up as an extension method, and then your resultant code would be:

if (datarow.AreAllColumnsEmpty())
{
}
else
{
}

Storing Data in MySQL as JSON

I know this is really late but I did have a similar situation where I used a hybrid approach of maintaining RDBMS standards of normalizing tables upto a point and then storing data in JSON as text value beyond that point. So for example I store data in 4 tables following RDBMS rules of normalization. However in the 4th table to accomodate dynamic schema I store data in JSON format. Every time I want to retrieve data I retrieve the JSON data, parse it and display it in Java. This has worked for me so far and to ensure that I am still able to index the fields I transform to json data in the table to a normalized manner using an ETL. This ensures that while the user is working on the application he faces minimal lag and the fields are transformed to a RDBMS friendly format for data analysis etc. I see this approach working well and believe that given MYSQL (5.7+) also allows parsing of JSON this approach gives you the benefits of both RDBMS and NOSQL databases.

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

Make body have 100% of the browser height

Only with 1 line of CSS… You can get this done.

body{ height: 100vh; }

Best data type to store money values in MySQL

It depends on your need.

Using DECIMAL(10,2) usually is enough but if you need a little bit more precise values you can set DECIMAL(10,4).

If you work with big values replace 10 with 19.

When should I use a trailing slash in my URL?

Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.

Device not detected in Eclipse when connected with USB cable

On a kitkat Google Nexus 7, I tired everything here, and did not succeed. The device did previously connect properly to this computer.

Then I hit settings - developer-options - Revoke USB debugging authorisations and confirmed that I really did want to revoke them.

I unplugged and plugged the USB. The tablet beeped and asked if wanted to authorise the computer for debugging. I said "Yes" and everything worked again.

Preserve Line Breaks From TextArea When Writing To MySQL

why make is sooooo hard people when it can be soooo easy :)

//here is the pull from the form
$your_form_text = $_POST['your_form_text'];


//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);

//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);

you will obviously need headers and likely have more fields, but this is your textarea take care of

How to upgrade rubygems

You can update gem to any specific version like this,

gem update --system 'version'

gem update --system '2.3.0'

Error: macro names must be identifiers using #ifdef 0

#ifdef 0
...
#endif

#ifdef expect a macro rather than expression when using constant or expression

#if 0
...
#endif

or

#if !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

if #ifdef is used the it reports this error

#ifdef !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

Where #ifdef expect a macro rather than macro expresssion

Fastest way to convert Image to Byte array

The fastest way i could find out is this :

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

Hope to be useful

How do I combine two dataframes?

If you want to update/replace the values of first dataframe df1 with the values of second dataframe df2. you can do it by following steps —

Step 1: Set index of the first dataframe (df1)

df1.set_index('id')

Step 2: Set index of the second dataframe (df2)

df2.set_index('id')

and finally update the dataframe using the following snippet —

df1.update(df2)

How to search a list of tuples in Python

tl;dr

A generator expression is probably the most performant and simple solution to your problem:

l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

result = next((i for i, v in enumerate(l) if v[0] == 53), None)
# 2

Explanation

There are several answers that provide a simple solution to this question with list comprehensions. While these answers are perfectly correct, they are not optimal. Depending on your use case, there may be significant benefits to making a few simple modifications.

The main problem I see with using a list comprehension for this use case is that the entire list will be processed, although you only want to find 1 element.

Python provides a simple construct which is ideal here. It is called the generator expression. Here is an example:

# Our input list, same as before
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

# Call next on our generator expression.
next((i for i, v in enumerate(l) if v[0] == 53), None)

We can expect this method to perform basically the same as list comprehensions in our trivial example, but what if we're working with a larger data set? That's where the advantage of using the generator method comes into play. Rather than constructing a new list, we'll use your existing list as our iterable, and use next() to get the first item from our generator.

Lets look at how these methods perform differently on some larger data sets. These are large lists, made of 10000000 + 1 elements, with our target at the beginning (best) or end (worst). We can verify that both of these lists will perform equally using the following list comprehension:

List comprehensions

"Worst case"

worst_case = ([(False, 'F')] * 10000000) + [(True, 'T')]
print [i for i, v in enumerate(worst_case) if v[0] is True]

# [10000000]
#          2 function calls in 3.885 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.885    3.885    3.885    3.885 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

"Best case"

best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print [i for i, v in enumerate(best_case) if v[0] is True]

# [0]
#          2 function calls in 3.864 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.864    3.864    3.864    3.864 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Generator expressions

Here's my hypothesis for generators: we'll see that generators will significantly perform better in the best case, but similarly in the worst case. This performance gain is mostly due to the fact that the generator is evaluated lazily, meaning it will only compute what is required to yield a value.

Worst case

# 10000000
#          5 function calls in 1.733 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         2    1.455    0.727    1.455    0.727 so_lc.py:10(<genexpr>)
#         1    0.278    0.278    1.733    1.733 so_lc.py:9(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    1.455    1.455 {next}

Best case

best_case  = [(True, 'T')] + ([(False, 'F')] * 10000000)
print next((i for i, v in enumerate(best_case) if v[0] == True), None)

# 0
#          5 function calls in 0.316 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    0.316    0.316    0.316    0.316 so_lc.py:6(<module>)
#         2    0.000    0.000    0.000    0.000 so_lc.py:7(<genexpr>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    0.000    0.000 {next}

WHAT?! The best case blows away the list comprehensions, but I wasn't expecting the our worst case to outperform the list comprehensions to such an extent. How is that? Frankly, I could only speculate without further research.

Take all of this with a grain of salt, I have not run any robust profiling here, just some very basic testing. This should be sufficient to appreciate that a generator expression is more performant for this type of list searching.

Note that this is all basic, built-in python. We don't need to import anything or use any libraries.

I first saw this technique for searching in the Udacity cs212 course with Peter Norvig.

babel-loader jsx SyntaxError: Unexpected token

Since the answer above still leaves some people in the dark, here's what a complete webpack.config.js might look like:

_x000D_
_x000D_
var path = require('path');_x000D_
var config = {_x000D_
    entry: path.resolve(__dirname, 'app/main.js'),_x000D_
    output: {_x000D_
        path: path.resolve(__dirname, 'build'),_x000D_
        filename: 'bundle.js'_x000D_
    },_x000D_
    module: {_x000D_
        loaders: [{_x000D_
            test: /\.jsx?$/,_x000D_
            loader: 'babel',_x000D_
            query:_x000D_
            {_x000D_
                presets:['es2015', 'react']_x000D_
            }_x000D_
        }]_x000D_
    },_x000D_
_x000D_
};_x000D_
_x000D_
module.exports = config;
_x000D_
_x000D_
_x000D_

What characters are allowed in an email address?

Google do an interesting thing with their gmail.com addresses. gmail.com addresses allow only letters (a-z), numbers, and periods(which are ignored).

e.g., [email protected] is the same as [email protected], and both email addresses will be sent to the same mailbox. [email protected] is also delivered to the same mailbox.

So to answer the question, sometimes it depends on the implementer on how much of the RFC standards they want to follow. Google's gmail.com address style is compatible with the standards. They do it that way to avoid confusion where different people would take similar email addresses e.g.

*** gmail.com accepting rules ***
[email protected]   (accepted)
[email protected]   (bounce and account can never be created)
[email protected]     (accepted)
D.Oy'[email protected]   (bounce and account can never be created)

The wikipedia link is a good reference on what email addresses generally allow. http://en.wikipedia.org/wiki/Email_address

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

error TS2339: Property 'x' does not exist on type 'Y'

Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.

See Dotted property for types with string index signatures in TypeScript 2.2 release note.

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

It sounds like you haven't used this IDE before. Read Eclipse's "Before You Begin" page and follow the instructions to the T. This will make sure that Eclipse, which is only an IDE, is actually linked to a compiler.

http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.cdt.doc.user/concepts/cdt_c_before_you_begin.htm

Simple way to understand Encapsulation and Abstraction

Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. Consider your mobile phone, you just need to know what buttons are to be pressed to send a message or make a call, What happens when you press a button, how your messages are sent, how your calls are connected is all abstracted away from the user.

Encapsulation is the process of combining data and functions into a single unit called class. In Encapsulation, the data is not accessed directly; it is accessed through the functions present inside the class. In simpler words, attributes of the class are kept private and public getter and setter methods are provided to manipulate these attributes. Thus, encapsulation makes the concept of data hiding possible.

enter image description here

Where are the recorded macros stored in Notepad++?

In Windows the macros are saved at %AppData%\Notepad++\shortcuts.xml (Windows logo key + E and copy&paste %AppData%\Notepad++\)

Or:

  • In Windows < 7 (including Win2008/R2) the macros are saved at C:\Documents and Settings\%username%\Application Data\Notepad++\shortcuts.xml
  • In Windows 7|8|10 C:\Users\%username%\AppData\Roaming\Notepad++\shortcuts.xml

Note: You will need to close Notepad++ if you have any new macros you want to 'export'.


Here is an example:

<NotepadPlus>
    <InternalCommands />
    <Macros>
        <Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
            <Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
            <Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
        </Macro>
        <Macro name="abc" Ctrl="no" Alt="no" Shift="no" Key="0">
            <Action type="1" message="2170" wParam="0" lParam="0" sParam="a" />
            <Action type="1" message="2170" wParam="0" lParam="0" sParam="b" />
            <Action type="1" message="2170" wParam="0" lParam="0" sParam="c" />
        </Macro>
    </Macros>
    <UserDefinedCommands>....

I added the 'abc' macro as a proof-of-concept.

How do I make a splash screen?

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread t=new Thread()
    {

        public void run()
        {   

            try {

                sleep(2000);
                finish();
                Intent cv=new Intent(MainActivity.this,HomeScreen.class/*otherclass*/);
                startActivity(cv);
            } 

            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

Pure JavaScript Send POST Data Without a Form

Also, RESTful lets you get data back from a POST request.

JS (put in static/hello.html to serve via Python):

<html><head><meta charset="utf-8"/></head><body>
Hello.

<script>

var xhr = new XMLHttpRequest();
xhr.open("POST", "/postman", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    value: 'value'
}));
xhr.onload = function() {
  console.log("HELLO")
  console.log(this.responseText);
  var data = JSON.parse(this.responseText);
  console.log(data);
}

</script></body></html>

Python server (for testing):

import time, threading, socket, SocketServer, BaseHTTPServer
import os, traceback, sys, json


log_lock           = threading.Lock()
log_next_thread_id = 0

# Local log functiondef


def Log(module, msg):
    with log_lock:
        thread = threading.current_thread().__name__
        msg    = "%s %s: %s" % (module, thread, msg)
        sys.stderr.write(msg + '\n')

def Log_Traceback():
    t   = traceback.format_exc().strip('\n').split('\n')
    if ', in ' in t[-3]:
        t[-3] = t[-3].replace(', in','\n***\n***  In') + '(...):'
        t[-2] += '\n***'
    err = '\n***  '.join(t[-3:]).replace('"','').replace(' File ', '')
    err = err.replace(', line',':')
    Log("Traceback", '\n'.join(t[:-3]) + '\n\n\n***\n*** ' + err + '\n***\n\n')

    os._exit(4)

def Set_Thread_Label(s):
    global log_next_thread_id
    with log_lock:
        threading.current_thread().__name__ = "%d%s" \
            % (log_next_thread_id, s)
        log_next_thread_id += 1


class Handler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        Set_Thread_Label(self.path + "[get]")
        try:
            Log("HTTP", "PATH='%s'" % self.path)
            with open('static' + self.path) as f:
                data = f.read()
            Log("Static", "DATA='%s'" % data)
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(data)
        except:
            Log_Traceback()

    def do_POST(self):
        Set_Thread_Label(self.path + "[post]")
        try:
            length = int(self.headers.getheader('content-length'))
            req   = self.rfile.read(length)
            Log("HTTP", "PATH='%s'" % self.path)
            Log("URL", "request data = %s" % req)
            req = json.loads(req)
            response = {'req': req}
            response = json.dumps(response)
            Log("URL", "response data = %s" % response)
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.send_header("content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)
        except:
            Log_Traceback()


# Create ONE socket.
addr = ('', 8000)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addr)
sock.listen(5)

# Launch 100 listener threads.
class Thread(threading.Thread):
    def __init__(self, i):
        threading.Thread.__init__(self)
        self.i = i
        self.daemon = True
        self.start()
    def run(self):
        httpd = BaseHTTPServer.HTTPServer(addr, Handler, False)

        # Prevent the HTTP server from re-binding every handler.
        # https://stackoverflow.com/questions/46210672/
        httpd.socket = sock
        httpd.server_bind = self.server_close = lambda self: None

        httpd.serve_forever()
[Thread(i) for i in range(10)]
time.sleep(9e9)

Console log (chrome):

HELLO
hello.html:14 {"req": {"value": "value"}}
hello.html:16 
{req: {…}}
req
:
{value: "value"}
__proto__
:
Object

Console log (firefox):

GET 
http://XXXXX:8000/hello.html [HTTP/1.0 200 OK 0ms]
POST 
XHR 
http://XXXXX:8000/postman [HTTP/1.0 200 OK 0ms]
HELLO hello.html:13:3
{"req": {"value": "value"}} hello.html:14:3
Object { req: Object }

Console log (Edge):

HTML1300: Navigation occurred.
hello.html
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: "<!DOCTYPE html>".
hello.html (1,1)
Current window: XXXXX/hello.html
HELLO
hello.html (13,3)
{"req": {"value": "value"}}
hello.html (14,3)
[object Object]
hello.html (16,3)
   {
      [functions]: ,
      __proto__: { },
      req: {
         [functions]: ,
         __proto__: { },
         value: "value"
      }
   }

Python log:

HTTP 8/postman[post]: PATH='/postman'
URL 8/postman[post]: request data = {"value":"value"}
URL 8/postman[post]: response data = {"req": {"value": "value"}}

How can I change the default Django date template format?

Within your template, you can use Django's date filter. E.g.:

<p>Birthday: {{ birthday|date:"M d, Y" }}</p>

Gives:

Birthday: Jan 29, 1983

More formatting examples in the date filter docs.

Can jQuery get all CSS styles associated with an element?

Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

Basic usage is pretty simple, but he's written a function for that as well:

$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}

Hope that helps.

How to create folder with PHP code?

In answer to the question in how to write to a file in PHP you can use the following as an example:

    $fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
    if ($fp) {
        fwrite ($fp, $text); //$text is what you are writing to the file
        fclose ($fp);
        $writeSuccess = "Yes";
        #echo ("File written");
    }
    else {
    $writeSuccess = "No";
    #echo ("File was not written");
    }

What's the difference between StaticResource and DynamicResource in WPF?

Found all answers useful, just wanted to add one more use case.

In a composite WPF scenario, your user control can make use of resources defined in any other parent window/control (that is going to host this user control) by referring to that resource as DynamicResource.

As mentioned by others, Staticresource will be looked up at compile time. User controls can not refer to those resources which are defined in hosting/parent control. Though, DynamicResource could be used in this case.

How to Create simple drag and Drop in angularjs

small scripts for drag and drop by angular

(function(angular) {
  'use strict';
angular.module('drag', []).
  directive('draggable', function($document) {
    return function(scope, element, attr) {
      var startX = 0, startY = 0, x = 0, y = 0;
      element.css({
       position: 'relative',
       border: '1px solid red',
       backgroundColor: 'lightgrey',
       cursor: 'pointer',
       display: 'block',
       width: '65px'
      });
      element.on('mousedown', function(event) {
        // Prevent default dragging of selected content
        event.preventDefault();
        startX = event.screenX - x;
        startY = event.screenY - y;
        $document.on('mousemove', mousemove);
        $document.on('mouseup', mouseup);
      });

      function mousemove(event) {
        y = event.screenY - startY;
        x = event.screenX - startX;
        element.css({
          top: y + 'px',
          left:  x + 'px'
        });
      }

      function mouseup() {
        $document.off('mousemove', mousemove);
        $document.off('mouseup', mouseup);
      }
    };
  });
})(window.angular);

source link

Get name of current class?

import sys

def class_meta(frame):
    class_context = '__module__' in frame.f_locals
    assert class_context, 'Frame is not a class context'

    module_name = frame.f_locals['__module__']
    class_name = frame.f_code.co_name
    return module_name, class_name

def print_class_path():
    print('%s.%s' % class_meta(sys._getframe(1)))

class MyClass(object):
    print_class_path()

Error: "an object reference is required for the non-static field, method or property..."

You can't access non-static members from a static method. (Note that Main() is static, which is a requirement of .Net). Just make siprimo and volteado static, by placing the static keyword in front of them. e.g.:

 static private long volteado(long a)

Selenium WebDriver and DropDown Boxes

Example for select an option from the drop down list:

Click on drop down list by using id or csspath or xpath or name. I have used id here.

driver.findElement(By.id("dropdownlistone")).click(); // To click on drop down list
driver.findElement(By.linkText("india")).click(); // To select a data from the drop down list.

Bootstrap 3 - 100% height of custom div inside column

The original question is about Bootstrap 3 and that supports IE8 and 9 so Flexbox would be the best option but it's not part of my answer due the lack of support, see http://caniuse.com/#feat=flexbox and toggle the IE box. Pretty bad, eh?

2 ways:

1. Display-table: You can muck around with turning the row into a display:table and the col- into display:table-cell. It works buuuut the limitations of tables are there, among those limitations are the push and pull and offsets won't work. Plus, I don't know where you're using this -- at what breakpoint. You should make the image full width and wrap it inside another container to put the padding on there. Also, you need to figure out the design on mobile, this is for 768px and up. When I use this, I redeclare the sizes and sometimes I stick importants on them because tables take on the width of the content inside them so having the widths declared again helps this. You will need to play around. I also use a script but you have to change the less files to use it or it won't work responsively.


DEMO: http://jsbin.com/EtUBujI/2

  .row.table-row > [class*="col-"].custom {
    background-color: lightgrey;
    text-align: center;
  }


@media (min-width: 768px) {
  
  img.img-fluid {width:100%;}

  .row.table-row {display:table;width:100%;margin:0 auto;}

  .row.table-row > [class*="col-"] {
    float:none;
    float:none;
    display:table-cell;
    vertical-align:top;
  }

  .row.table-row > .col-sm-11 {
    width: 91.66666666666666%;
  }
  .row.table-row > .col-sm-10 {
    width: 83.33333333333334%;
  }
  .row.table-row > .col-sm-9 {
    width: 75%;
  }
  .row.table-row > .col-sm-8 {
    width: 66.66666666666666%;
  }
  .row.table-row > .col-sm-7 {
    width: 58.333333333333336%;
  }
  .row.table-row > .col-sm-6 {
    width: 50%;
  }
  .col-sm-5 {
    width: 41.66666666666667%;
  }
  .col-sm-4 {
    width: 33.33333333333333%;
  }
  .row.table-row > .col-sm-3 {
    width: 25%;
  }
  .row.table-row > .col-sm-2 {
    width: 16.666666666666664%;
  }
  .row.table-row > .col-sm-1 {
    width: 8.333333333333332%;
  }


}

HTML

<div class="container">
    <div class="row table-row">
        <div class="col-sm-4 custom">
                100% height to make equal to ->
        </div>
        <div class="col-sm-8 image-col">
            <img src="http://placehold.it/600x400/B7AF90/FFFFFF&text=image+1" class="img-fluid">
        </div>
    </div>
</div>

2. Absolute bg div

DEMO: http://jsbin.com/aVEsUmig/2/edit

DEMO with content above and below: http://jsbin.com/aVEsUmig/3


.content {
        text-align: center;
        padding: 10px;
        background: #ccc;

}


@media (min-width:768px) { 
    .my-row {
        position: relative;
        height: 100%;
        border: 1px solid red;
        overflow: hidden;
    }
    .img-fluid {
        width: 100%
    }
    .row.my-row > [class*="col-"] {
        position: relative
    }
    .background {
        position: absolute;
        padding-top: 200%;
        left: 0;
        top: 0;
        width: 100%;
        background: #ccc;
    }
    .content {
        position: relative;
        z-index: 1;
        width: 100%;
        text-align: center;
        padding: 10px;
    }

}

HTML

<div class="container">
  
    <div class="row my-row">
      
        <div class="col-sm-6">
          
        <div class="content">
          This is inside a relative positioned z-index: 1 div
          </div>

         <div class="background"><!--empty bg-div--></div>
        </div>
      
        <div class="col-sm-6 image-col">
            <img src="http://placehold.it/200x400/777777/FFFFFF&text=image+1" class="img-fluid">
        </div>
      
    </div>
   
</div>
  

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

Create A Cors.php File in App/Http/Middleware and paste this in it. ☑

<?php

namespace App\Http\Middleware;

use Closure;


class Cors {    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");
        //ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
        ];
        if ($request->getMethod() == "OPTIONS"){
            //The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response()->json('OK',200,$headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;

    } }

And Add This Line In Your Kernel.php after the "Trust Proxies::Class" Line.

\App\Http\Middleware\Cors::class,

Thats It You have Allowed All Cors Header. ☑

SQL Error with Order By in Subquery

In this example ordering adds no information - the COUNT of a set is the same whatever order it is in!

If you were selecting something that did depend on order, you would need to do one of the things the error message tells you - use TOP or FOR XML

Reminder - \r\n or \n\r?

if you are using C#, why not using Environment.NewLine ? (i assume you use some file writer objects... just pass it the Environment.NewLine and it will handle the right terminators.