Programs & Examples On #Transactional

Spring @Transactional - isolation, propagation

You almost never want to use Read Uncommited since it's not really ACID compliant. Read Commmited is a good default starting place. Repeatable Read is probably only needed in reporting, rollup or aggregation scenarios. Note that many DBs, postgres included don't actually support Repeatable Read, you have to use Serializable instead. Serializable is useful for things that you know have to happen completely independently of anything else; think of it like synchronized in Java. Serializable goes hand in hand with REQUIRES_NEW propagation.

I use REQUIRES for all functions that run UPDATE or DELETE queries as well as "service" level functions. For DAO level functions that only run SELECTs, I use SUPPORTS which will participate in a TX if one is already started (i.e. being called from a service function).

Spring - @Transactional - What happens in background?

All existing answers are correct, but I feel cannot give just this complex topic.

For a comprehensive, practical explanation you might want to have a look at this Spring @Transactional In-Depth guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.

How can I read input from the console using the Scanner class in Java?

You can make a simple program to ask for the user's name and print whatever the reply use inputs.

Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.

So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:

Scanner input = new Scanner(System.in);

input is a variable name.

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value

System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer

System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double

See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.

counting the number of lines in a text file

Your hack of decrementing the count at the end is exactly that -- a hack.

Far better to write your loop correctly in the first place, so it doesn't count the last line twice.

int main() { 
    int number_of_lines = 0;
    std::string line;
    std::ifstream myfile("textexample.txt");

    while (std::getline(myfile, line))
        ++number_of_lines;
    std::cout << "Number of lines in text file: " << number_of_lines;
    return 0;
}

Personally, I think in this case, C-style code is perfectly acceptable:

int main() {
    unsigned int number_of_lines = 0;
    FILE *infile = fopen("textexample.txt", "r");
    int ch;

    while (EOF != (ch=getc(infile)))
        if ('\n' == ch)
            ++number_of_lines;
    printf("%u\n", number_of_lines);
    return 0;
}

Edit: Of course, C++ will also let you do something a bit similar:

int main() {
    std::ifstream myfile("textexample.txt");

    // new lines will be skipped unless we stop it from happening:    
    myfile.unsetf(std::ios_base::skipws);

    // count the newlines with an algorithm specialized for counting:
    unsigned line_count = std::count(
        std::istream_iterator<char>(myfile),
        std::istream_iterator<char>(), 
        '\n');

    std::cout << "Lines: " << line_count << "\n";
    return 0;
}

Set a default font for whole iOS app?

There is also another solution which will be to override systemFont.

Just create a category

UIFont+SystemFontOverride.h

#import <UIKit/UIKit.h>

@interface UIFont (SystemFontOverride)
@end

UIFont+SystemFontOverride.m

@implementation UIFont (SystemFontOverride)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"fontName" size:fontSize];
}

+ (UIFont *)systemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"fontName" size:fontSize];
}

#pragma clang diagnostic pop

@end

This will replace the default implementation and most UIControls use systemFont.

How to display the current time and date in C#

The System.DateTime class has a property called Now, which:

Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

You can set the Text property of your label to the current time like this (where myLabel is the name of your label):

myLabel.Text = DateTime.Now.ToString();

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])
    }


    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])
    }
}

Tests:

func testArraySubscriptRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1..<arr.count] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

func testArraySubscriptClosedRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1...arr.count - 1] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

AngularJS/javascript converting a date String to date object

This is what I did on the controller

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

I ended up formatting the date to my desired pattern on the directive as follows.

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

Getting "cannot find Symbol" in Java project in Intellij

I know this is old, but for anyone else, make sure that the class that's missing is in the same package as the class where you get the error/where your calling it from.

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

It sounds like your error comes from an attempt to run something like this (which works in Linux)

NODE_ENV=development node foo.js

the equivalent in Windows would be

SET NODE_ENV=development
node foo.js

running in the same command shell. You mentioned set NODE_ENV did not work, but wasn't clear how/when you executed it.

Difference between "while" loop and "do while" loop

While : your condition is at the begin of the loop block, and makes possible to never enter the loop.

Do While : your condition is at the end of the loop block, and makes obligatory to enter the loop at least one time.

What are pipe and tap methods in Angular tutorial?

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

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

In brief:

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

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

How to output MySQL query results in CSV format?

To expand on previous answers, the following one-liner exports a single table as a tab-separated file. It's suitable for automation, exporting the database every day or so.

mysql -B -D mydatabase -e 'select * from mytable'

Conveniently, we can use the same technique to list out MySQL's tables, and to describe the fields on a single table:

mysql -B -D mydatabase -e 'show tables'

mysql -B -D mydatabase -e 'desc users'

Field   Type    Null    Key Default Extra
id  int(11) NO  PRI NULL    auto_increment
email   varchar(128)    NO  UNI NULL    
lastName    varchar(100)    YES     NULL    
title   varchar(128)    YES UNI NULL    
userName    varchar(128)    YES UNI NULL    
firstName   varchar(100)    YES     NULL    

Random date in C#

This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.

Func<DateTime> RandomDayFunc()
{
    DateTime start = new DateTime(1995, 1, 1); 
    Random gen = new Random(); 
    int range = ((TimeSpan)(DateTime.Today - start)).Days; 
    return () => start.AddDays(gen.Next(range));
}

How to switch back to 'master' with git?

Will take you to the master branch.

git checkout master

To switch to other branches do (ignore the square brackets, it's just for emphasis purposes)

git checkout [the name of the branch you want to switch to]

To create a new branch use the -b like this (ignore the square brackets, it's just for emphasis purposes)

git checkout -b [the name of the branch you want to create]

Print in one line dynamically

In Python 3 you can do it this way:

for item in range(1,10):
    print(item, end =" ")

Outputs:

1 2 3 4 5 6 7 8 9 

Tuple: You can do the same thing with a tuple:

tup = (1,2,3,4,5)

for n in tup:
    print(n, end = " - ")

Outputs:

1 - 2 - 3 - 4 - 5 - 

Another example:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
    print(item)

Outputs:

(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')

You can even unpack your tuple like this:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]

# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
    print(item1, item2)   

Outputs:

1 2
A B
3 4
Cat Dog

another variation:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
    print(item1)
    print(item2)
    print('\n')

Outputs:

1
2


A
B


3
4


Cat
Dog

How to iterate over rows in a DataFrame in Pandas

Some libraries (e.g. a Java interop library that I use) require values to be passed in a row at a time, for example, if streaming data. To replicate the streaming nature, I 'stream' my dataframe values one by one, I wrote the below, which comes in handy from time to time.

class DataFrameReader:
  def __init__(self, df):
    self._df = df
    self._row = None
    self._columns = df.columns.tolist()
    self.reset()
    self.row_index = 0

  def __getattr__(self, key):
    return self.__getitem__(key)

  def read(self) -> bool:
    self._row = next(self._iterator, None)
    self.row_index += 1
    return self._row is not None

  def columns(self):
    return self._columns

  def reset(self) -> None:
    self._iterator = self._df.itertuples()

  def get_index(self):
    return self._row[0]

  def index(self):
    return self._row[0]

  def to_dict(self, columns: List[str] = None):
    return self.row(columns=columns)

  def tolist(self, cols) -> List[object]:
    return [self.__getitem__(c) for c in cols]

  def row(self, columns: List[str] = None) -> Dict[str, object]:
    cols = set(self._columns if columns is None else columns)
    return {c : self.__getitem__(c) for c in self._columns if c in cols}

  def __getitem__(self, key) -> object:
    # the df index of the row is at index 0
    try:
        if type(key) is list:
            ix = [self._columns.index(key) + 1 for k in key]
        else:
            ix = self._columns.index(key) + 1
        return self._row[ix]
    except BaseException as e:
        return None

  def __next__(self) -> 'DataFrameReader':
    if self.read():
        return self
    else:
        raise StopIteration

  def __iter__(self) -> 'DataFrameReader':
    return self

Which can be used:

for row in DataFrameReader(df):
  print(row.my_column_name)
  print(row.to_dict())
  print(row['my_column_name'])
  print(row.tolist())

And preserves the values/ name mapping for the rows being iterated. Obviously, is a lot slower than using apply and Cython as indicated above, but is necessary in some circumstances.

Is a GUID unique 100% of the time?

If your system clock is set properly and hasn't wrapped around, and if your NIC has its own MAC (i.e. you haven't set a custom MAC) and your NIC vendor has not been recycling MACs (which they are not supposed to do but which has been known to occur), and if your system's GUID generation function is properly implemented, then your system will never generate duplicate GUIDs.

If everyone on earth who is generating GUIDs follows those rules then your GUIDs will be globally unique.

In practice, the number of people who break the rules is low, and their GUIDs are unlikely to "escape". Conflicts are statistically improbable.

Setting action for back button in navigation controller

Here's my Swift solution. In your subclass of UIViewController, override the navigationShouldPopOnBackButton method.

extension UIViewController {
    func navigationShouldPopOnBackButton() -> Bool {
        return true
    }
}

extension UINavigationController {

    func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
        if let vc = self.topViewController {
            if vc.navigationShouldPopOnBackButton() {
                self.popViewControllerAnimated(true)
            } else {
                for it in navigationBar.subviews {
                    let view = it as! UIView
                    if view.alpha < 1.0 {
                        [UIView .animateWithDuration(0.25, animations: { () -> Void in
                            view.alpha = 1.0
                        })]
                    }
                }
                return false
            }
        }
        return true
    }

}

cannot download, $GOPATH not set

You can use the "export" solution just like what other guys have suggested. I'd like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.

Firstly, you need to download a small tool named gost : https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).

Then you need to run the commands below to unpack it :

$ cd /path/to/your/download/directory 
$ tar -xvf gost_linux_amd64.tar.gz

You would get an executable gost. You can move it to /usr/local/bin for convenient use:

$ sudo mv gost /usr/local/bin

Run the command below to add the path you want to use as GOPATH into the pathspace gost maintains. It is required to give the path a name which you would use later.

$ gost add foo /home/foobar/bar     # 'foo' is the name and '/home/foobar/bar' is the path

Run any Go command you want in the format:

gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]

For example, you want to run go get github.com/go-sql-driver/mysql with /home/foobar/bar as the GOPATH, just do it as below:

$ gost get -p foo -- github.com/go-sql-driver/mysql  # 'foo' is the name you give to the path above.

It would help you to set the GOPATH and run the command. But remember that you have added the path into gost's pathspace. If you are under any level of subdirectories of /home/foobar/bar, you can even just run the command below which would do the same thing for short :

$ gost get -- github.com/go-sql-driver/mysql

gost is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName. For example you want to know more about install, just type words below in:

$ gost help install

You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md

How can I pass a list as a command-line argument with argparse?

You can parse the list as a string and use of the eval builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.

# declare the list arg as a string
parser.add_argument('-l', '--list', type=str)

# parse
args = parser.parse()

# turn the 'list' string argument into a list object
args.list = eval(args.list)
print(list)
print(type(list))

Testing:

python list_arg.py --list "[1, 2, 3]"

[1, 2, 3]
<class 'list'>

How to use code to open a modal in Angular 2?

This is one way I found. You can add a hidden button:

<button id="openModalButton" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>

Then use the code to "click" the button to open the modal:

document.getElementById("openModalButton").click();

This way can keep the bootstrap style of the modal and the fade in animation.

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.

Using PIVOT

In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

How to create own dynamic type or dynamic object in C#?

dynamic MyDynamic = new ExpandoObject();

How to convert C# nullable int to int

I am working on C# 9 and .NET 5, example

foo is nullable int, I need get int value of foo

var foo = (context as AccountTransfer).TransferSide;
int value2 = 0;
if (foo != null)
{
    value2 = foo.Value;
}

See more at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#examination-of-an-instance-of-a-nullable-value-type

How may I sort a list alphabetically using jQuery?

$(".list li").sort(asc_sort).appendTo('.list');
//$("#debug").text("Output:");
// accending sort
function asc_sort(a, b){
    return ($(b).text()) < ($(a).text()) ? 1 : -1;    
}

// decending sort
function dec_sort(a, b){
    return ($(b).text()) > ($(a).text()) ? 1 : -1;    
}

live demo : http://jsbin.com/eculis/876/edit

jQuery ajax request with json response, how to?

Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.

$.ajax({
    url : base_url+"Login/submit",
    type: "POST",
    dataType: "json",
    data : {
        'username': username,
        'password': password
    },
    success: function(data)
    {
        alert(data.status);
    }
});

jquery change div text

I think this will do:

$('#'+div_id+' .widget-head > span').text("new dialog title");

Submit form without reloading page

You can't do this using forms the normal way. Instead, you want to use AJAX.

A sample function that will submit the data and alert the page response.

function submitForm() {
    var http = new XMLHttpRequest();
    http.open("POST", "<<whereverTheFormIsGoing>>", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    }
}

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

How to Add Date Picker To VBA UserForm

OFFICE 2013 INSTRUCTIONS:

(For Windows 7 (x64) | MS Office 32-Bit)

Option 1 | Check if ability already exists | 2 minutes

  1. Open VB Editor
  2. Tools -> Additional Controls
  3. Select "Microsoft Monthview Control 6.0 (SP6)" (if applicable)
  4. Use 'DatePicker' control for VBA Userform

Option 2 | The "Monthview" Control doesn't currently exist | 5 minutes

  1. Close Excel
  2. Download MSCOMCT2.cab (it's a cabinet file which extracts into two useful files)
  3. Extract Both Files | the .inf file and the .ocx file
  4. Install | right-click the .inf file | hit "Install"
  5. Move .ocx file | Move from "C:\Windows\system32" to "C:\Windows\sysWOW64"
  6. Run CMD | Start Menu -> Search -> "CMD.exe" | right-click the icon | Select "Run as administrator"
  7. Register Active-X File | Type "regsvr32 c:\windows\sysWOW64\MSCOMCT2.ocx"
  8. Open Excel | Open VB Editor
  9. Activate Control | Tools->References | Select "Microsoft Windows Common Controls 2-6.0 (SP6)"
  10. Userform Controls | Select any userform in VB project | Tools->Additional Controls
  11. Select "Microsoft Monthview Control 6.0 (SP6)"
  12. Use 'DatePicker' control for VBA UserForm

Okay, either of these two steps should work for you if you have Office 2013 (32-Bit) on Windows 7 (x64). Some of the steps may be different if you have a different combo of Windows 7 & Office 2013.

The "Monthview" control will be your fully fleshed out 'DatePicker'. It comes equipped with its own properties and image. It works very well. Good luck.

Site: "bonCodigo" from above (this is an updated extension of his work)
Site: "AMM" from above (this is just an exension of his addition)
Site: Various Microsoft Support webpages

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).

you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below

javac -target 1.7 *.java

if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.

Custom domain for GitHub project pages

I'd like to share my steps which is a bit different to what offered by rynop and superluminary.

  • for A Record is exactly the same but
  • instead of creating CNAME for www I would prefer to redirect it to my blank domain (non-www)

This configuration is referring to guidance of preferred domain. The domain setting of www to non www or vise versa can be different on each of the domain providers. Since my domain is under GoDaddy, so under the Domain Setting I set it using the Subdomain Forwarding (301).

As the result of pointing the domain to Github repository, it will then give all the URLs for both of master and gh-pages branch similar like the ones I listed below goes to the preferred domain:

master

By creating CNAME file on master branch (check it on my user repository).

http://hyipworld.github.io/
http://www.hyip.world/
http://hyip.world/

gh-pages

By creating the same CNAME file on gh-pages branch (check it on my project repository).

http://hyipworld.github.io/maps/
http://www.hyip.world/maps/
http://hyip.world/maps/

As addition to the CNAME file above, you may need to completely bypass Jekyll processing on GitHub Pages by creating a file named .nojekyll in the root of your pages repo.

Volatile vs Static in Java

I think static and volatile have no relation at all. I suggest you read java tutorial to understand Atomic Access, and why use atomic access, understand what is interleaved, you will find answer.

Encrypt Password in Configuration Files?

Try using ESAPIs Encryption methods. Its easy to configure and you can also easily change your keys.

http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/Encryptor.html

You

1)encrypt 2)decrypt 3)sign 4)unsign 5)hashing 6)time based signatures and much more with just one library.

How do I delete everything in Redis?

Answers so far are absolutely correct; they delete all keys.

However, if you also want to delete all Lua scripts from the Redis instance, you should follow it by:

SCRIPT FLUSH

The OP asks two questions; this completes the second question (everything wiped).

Get checkbox values using checkbox name using jquery

Like it has been said few times, you need to change your selector to

$("input[name='bla[]']")

But I want to add, you have to use single or double quotes when using [] in selector.

How do you remove columns from a data.frame?

Just addressing the edit.

@nzcoops, you do not need the column names in a comma delimited character vector. You are thinking about this the wrong way round. When you do

vec <- c("col1", "col2", "col3")

you are creating a character vector. The , just separates arguments taken by the c() function when you define that vector. names() and similar functions return a character vector of names.

> dat <- data.frame(col1 = 1:3, col2 = 1:3, col3 = 1:3)
> dat
  col1 col2 col3
1    1    1    1
2    2    2    2
3    3    3    3
> names(dat)
[1] "col1" "col2" "col3"

It is far easier and less error prone to select from the elements of names(dat) than to process its output to a comma separated string you can cut and paste from.

Say we want columns col1 and col2, subset names(dat), retaining only the ones we want:

> names(dat)[c(1,3)]
[1] "col1" "col3"
> dat[, names(dat)[c(1,3)]]
  col1 col3
1    1    1
2    2    2
3    3    3

You can kind of do what you want, but R will always print the vector the screen in quotes ":

> paste('"', names(dat), '"', sep = "", collapse = ", ")
[1] "\"col1\", \"col2\", \"col3\""
> paste("'", names(dat), "'", sep = "", collapse = ", ")
[1] "'col1', 'col2', 'col3'"

so the latter may be more useful. However, now you have to cut and past from that string. Far better to work with objects that return what you want and use standard subsetting routines to keep what you need.

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

Recommended Fonts for Programming?

I use Bitstream Vera http://www.gnome.org/fonts/ for Visual Studio 2008 paired with the Darkness Theme because my eyes can't deal with white backgrounds.

Where do I put image files, css, js, etc. in Codeigniter?

add one folder any name e.g public and add .htaccess file and write allow from all it means, in this folder your all files and all folder will not give error Access forbidden! use it like this

<link href="<?php echo base_url(); ?>application/public/css/style.css" rel="stylesheet" type="text/css"  />
<script type="text/javascript" src="<?php echo base_url(); ?>application/public/js/javascript.js"></script>

Converting a date string to a DateTime object using Joda Time library

There are two ways this could be achieved.

DateTimeFormat

DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");

SimpleDateFormat

        String dateValue = "04/02/2011 20:27:05";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //  04/02/2011 20:27:05

        Date date = sdf.parse(dateValue); // returns date object
        System.out.println(date); // outputs: Fri Feb 04 20:27:05 IST 2011

R memory management / cannot allocate vector of size n Mb

Here is a presentation on this topic that you might find interesting:

http://www.bytemining.com/2010/08/taking-r-to-the-limit-part-ii-large-datasets-in-r/

I haven't tried the discussed things myself, but the bigmemory package seems very useful

How to detect string which contains only spaces?

To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0, then you can be sure the original only contained whitespace. Try this:

_x000D_
_x000D_
var str = "    ";_x000D_
if (!str.replace(/\s/g, '').length) {_x000D_
  console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');_x000D_
}
_x000D_
_x000D_
_x000D_

Using "Object.create" instead of "new"

The advantage is that Object.create is typically slower than new on most browsers

In this jsperf example, in a Chromium, browser new is 30 times as fast as Object.create(obj) although both are pretty fast. This is all pretty strange because new does more things (like invoking a constructor) where Object.create should be just creating a new Object with the passed in object as a prototype (secret link in Crockford-speak)

Perhaps the browsers have not caught up in making Object.create more efficient (perhaps they are basing it on new under the covers ... even in native code)

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

How do I set GIT_SSL_NO_VERIFY for specific repos only?

Like what Thirumalai said, but inside of the cloned repository and without --global. I.e.,

  1. GIT_SSL_NO_VERIFY=true git clone https://url
  2. cd <directory-of-the-clone>
  3. git config http.sslVerify false

JSON: why are forward slashes escaped?

I asked the same question some time ago and had to answer it myself. Here's what I came up with:

It seems, my first thought [that it comes from its JavaScript roots] was correct.

'\/' === '/' in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like \z) not allowed in JSON?

The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.

ImportError: No module named matplotlib.pyplot

Comment in the normal feed are blocked. Let me write why this happens, just like when you executed your app.

If you ran scripts, python or ipython in another environment than the one you installed it, you will get these issues.

Don't confuse reinstalling it. Matplotlib is normally installed in your user environment, not in sudo. You are changing the environment.

So don't reinstall pip, just make sure you are running it as sudo if you installed it in the sudo environment.

Adding a column to an existing table in a Rails migration

When I've done this, rather than fiddling the original migration, I create a new one with just the add column in the up section and a drop column in the down section.

You can change the original and rerun it if you migrate down between, but in this case I think that's made a migration that won't work properly.

As currently posted, you're adding the column and then creating the table.

If you change the order it might work. Or, as you're modifying an existing migration, just add it to the create table instead of doing a separate add column.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How can I pad a value with leading zeros?

function zeroFill(number, width) {
    width -= (number.toString().length - /\./.test(number));
    if (width > 0) {
        return new Array(width + 1).join('0') + number;
    }
    return number + ""; // always return a string
}

Slight changes made to Peter's code. With his code if the input is (1.2, 3) the value returned should be 01.2 but it is returning 1.2. The changes here should correct that.

Check substring exists in a string in C

My own humble (case sensitive) solution:

uint8_t strContains(char* string, char* toFind)
{
    uint8_t slen = strlen(string);
    uint8_t tFlen = strlen(toFind);
    uint8_t found = 0;

    if( slen >= tFlen )
    {
        for(uint8_t s=0, t=0; s<slen; s++)
        {
            do{

                if( string[s] == toFind[t] )
                {
                    if( ++found == tFlen ) return 1;
                    s++;
                    t++;
                }
                else { s -= found; found=0; t=0; }

              }while(found);
        }
        return 0;
    }
    else return -1;
}

Results

strContains("this is my sample example", "th") // 1
strContains("this is my sample example", "sample") // 1
strContains("this is my sample example", "xam") // 1
strContains("this is my sample example", "ple") // 1
strContains("this is my sample example", "ssample") // 0
strContains("this is my sample example", "samplee") // 0
strContains("this is my sample example", "") // 0
strContains("str", "longer sentence") // -1
strContains("ssssssample", "sample") // 1
strContains("sample", "sample") // 1

Tested on ATmega328P (avr8-gnu-toolchain-3.5.4.1709) ;)

jQuery: If this HREF contains

use this

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

How to declare an array of strings in C++?

You can use the begin and end functions from the Boost range library to easily find the ends of a primitive array, and unlike the macro solution, this will give a compile error instead of broken behaviour if you accidentally apply it to a pointer.

const char* array[] = { "cat", "dog", "horse" };
vector<string> vec(begin(array), end(array));

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

Installing Pandas on Mac OSX

You need to install newest version of xCode from appStore. It contains the compiler for C(gcc) and C++(g++) for mac. Then you can install pandas without any problem. Use the following commands in terminal:

  1. xcode-select --install

  2. pip3 install pandas

It might take some time as it installs other packages too. Please be patient.

Printing to the console in Google Apps Script?

Make sure you select the function that needs to be executed. See screenshot:
Apps script logging

How can I reuse a navigation bar on multiple pages?

A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml extension. For instance this would be your index.shtml file:

<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>

Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

How do you create a Distinct query in HQL

I have got a answer for Hibernate Query Language to use Distinct fields. You can use *SELECT DISTINCT(TO_CITY) FROM FLIGHT_ROUTE*. If you use SQL query, it return String List. You can't use it return value by Entity Class. So the Answer to solve that type of Problem is use HQL with SQL.

FROM FLIGHT_ROUTE F WHERE F.ROUTE_ID IN (SELECT SF.ROUTE_ID FROM FLIGHT_ROUTE SF GROUP BY SF.TO_CITY);

From SQL query statement it got DISTINCT ROUTE_ID and input as a List. And IN query filter the distinct TO_CITY from IN (List).

Return type is Entity Bean type. So you can it in AJAX such as AutoComplement.

May all be OK

Function overloading in Python: Missing

Oftentimes you see the suggestion use use keyword arguments, with default values, instead. Look into that.

How to make a Div appear on top of everything else on the screen?

dropdowns always show up on top, only solution for this problem is to hide dropdowns when image is displayed (display:block or visibility:visibile) and show them when image hidden (display:none or visibility:hidden)

Check if a string is palindrome

// The below C++ function checks for a palindrome and 
// returns true if it is a palindrome and returns false otherwise

bool checkPalindrome ( string s )
{
    // This calculates the length of the string

    int n = s.length();

    // the for loop iterates until the first half of the string
    // and checks first element with the last element,
    // second element with second last element and so on.
    // if those two characters are not same, hence we return false because
    // this string is not a palindrome 

    for ( int i = 0; i <= n/2; i++ ) 
    {
        if ( s[i] != s[n-1-i] )
            return false;
    }
    
    // if the above for loop executes completely , 
    // this implies that the string is palindrome, 
    // hence we return true and exit

    return true;
}

Bash Templating: How to build configuration files from templates with Bash?

Here is another solution: generate a bash script with all the variables and the contents of the template file, that script would look like this:

word=dog           
i=1                
cat << EOF         
the number is ${i} 
the word is ${word}

EOF                

If we feed this script into bash it would produce the desired output:

the number is 1
the word is dog

Here is how to generate that script and feed that script into bash:

(
    # Variables
    echo word=dog
    echo i=1

    # add the template
    echo "cat << EOF"
    cat template.txt
    echo EOF
) | bash

Discussion

  • The parentheses opens a sub shell, its purpose is to group together all the output generated
  • Within the sub shell, we generate all the variable declarations
  • Also in the sub shell, we generate the cat command with HEREDOC
  • Finally, we feed the sub shell output to bash and produce the desired output
  • If you want to redirect this output into a file, replace the last line with:

    ) | bash > output.txt
    

Delete all records in a table of MYSQL in phpMyAdmin

  • Visit phpmyadmin
  • Select your database and click on structure
  • In front of your table, you can see Empty, click on it to clear all the entries from the selected table.

demo-database-structure

Or you can do the same using sql query:

Click on SQL present along side Structure

TRUNCATE tablename; //offers better performance, but used only when all entries need to be cleared
or
DELETE FROM tablename; //returns the number of rows deleted

Refer to DELETE and TRUNCATE for detailed documentaion

How to sort by two fields in Java?

Use Comparator and then put objects into Collection, then Collections.sort();

class Person {

    String fname;
    String lname;
    int age;

    public Person() {
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public Person(String fname, String lname, int age) {
        this.fname = fname;
        this.lname = lname;
        this.age = age;
    }

    @Override
    public String toString() {
        return fname + "," + lname + "," + age;
    }
}

public class Main{

    public static void main(String[] args) {
        List<Person> persons = new java.util.ArrayList<Person>();
        persons.add(new Person("abc3", "def3", 10));
        persons.add(new Person("abc2", "def2", 32));
        persons.add(new Person("abc1", "def1", 65));
        persons.add(new Person("abc4", "def4", 10));
        System.out.println(persons);
        Collections.sort(persons, new Comparator<Person>() {

            @Override
            public int compare(Person t, Person t1) {
                return t.getAge() - t1.getAge();
            }
        });
        System.out.println(persons);

    }
}

What languages are Windows, Mac OS X and Linux written in?

  • Windows: C++, kernel is in C
  • Mac: Objective C, kernel is in C (IO PnP subsystem is Embedded C++)
  • Linux: Most things are in C, many userland apps are in Python, KDE is all C++

All kernels will use some assembly code as well.

Cleanest way to toggle a boolean variable in Java?

This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)

Boolean.valueOf(aBool).equals(false)

or alternatively:

Boolean.FALSE.equals(aBool)

or

Boolean.FALSE::equals

DateTime vs DateTimeOffset

TLDR if you don't want to read all these great answers :-)

Explicit:

Using DateTimeOffset because the timezone is forced to UTC+0.

Implicit:

Using DateTime where you hope everyone sticks to the unwritten rule of the timezone always being UTC+0.


(Side note for devs: explicit is always better than implicit!)

(Side side note for Java devs, C# DateTimeOffset == Java OffsetDateTime, read this: https://www.baeldung.com/java-zoneddatetime-offsetdatetime)

How to make a custom LinkedIn share button

Official LinkedIn API for sharing:

https://developer.linkedin.com/docs/share-on-linkedin

Read Terms of Use!

Example link using "Customized URL" method: http://www.linkedin.com/shareArticle?mini=true&url=https://stackoverflow.com/questions/10713542/how-to-make-custom-linkedin-share-button/10737122&title=How%20to%20make%20custom%20linkedin%20share%20button&summary=some%20summary%20if%20you%20want&source=stackoverflow.com

You just need to open it in popup using JavaScript or load it to iframe. Simple and works - that's what I was looking for!

EDIT: Video attached to a post:

I checked that you can't really embed any video to LinkedIn post, the only option is to add the link to the page with video itself.

You can achieve it by putting YT link into url param:

https://www.linkedin.com/shareArticle?mini=true&url=https://www.youtube.com/watch?v=SBi92AOSW2E

If you specify summary and title then LinkedIn will stop pulling it from the video, e.g.:

https://www.linkedin.com/shareArticle?mini=true&summary=youtube&title=f1&url=https://www.youtube.com/watch?v=SBi92AOSW2E

It does work exactly the same with Vimeo, and probably will work for any website. Hope it will help.

EDIT 2: Pulling images to the post:

When you open above links you will see that LinkedIn loads some images along with the passed URL (and optionally title and summary).

LinkedIn does it automatically, and you can read about it here: https://developer.linkedin.com/docs/share-on-linkedin#opengraph

It's interesting though as it says:

If Open Graph tags are present, LinkedIn's crawler will not have to rely on it's own analysis to determine what content will be shared, which improves the likelihood that the information that is shared is exactly what you intended.

It tells me that even if Open Graph information is not attached, LinkedIn can pull this data based on its own analysis. And in case of YouTube it seems to be the case, as I couldn't find any Open Graph tags added to YouTube pages.

Changing Java Date one hour back

Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!

    int minutes = 60;
    long currentDateTime = System.currentTimeMillis();
    Date currentDate = new Date(currentDateTime - minutes*60*1000);
    System.out.println(currentDate);

Form Submit jQuery does not work

You can use jQuery like this:

$(function() {
    $("#form").submit(function(event) {
        // do some validation, for example:
        username = $("#username").val();
        if (username.length >= 8)
            return; // valid
        event.preventDefault(); // invalidates the form
    });
});

In your HTML:

<form id="form" method="post">
    <input type="text" name="username" required id="username">
    <button type="submit">Submit</button>
</form>

References:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event https://api.jquery.com/submit/

How do I prevent Conda from activating the base environment by default?

There're 3 ways to achieve this after conda 4.6. (The last method has the highest priority.)

  1. Use sub-command conda config to change the setting.

    conda config --set auto_activate_base false
    
  2. In fact, the former conda config sub-command is changing configuration file .condarc. We can modify .condarc directly. Add following content into .condarc under your home directory,

    # auto_activate_base (bool)
    #   Automatically activate the base environment during shell
    #   initialization. for `conda init`
    auto_activate_base: false
    
  3. Set environment variable CONDA_AUTO_ACTIVATE_BASE in the shell's init file. (.bashrc for bash, .zshrc for zsh)

    CONDA_AUTO_ACTIVATE_BASE=false
    

    To convert from the condarc file-based configuration parameter name to the environment variable parameter name, make the name all uppercase and prepend CONDA_. For example, conda’s always_yes configuration parameter can be specified using a CONDA_ALWAYS_YES environment variable.

    The environment settings take precedence over corresponding settings in .condarc file.

References

Javascript get Object property Name

Like the other answers you can do theTypeIs = Object.keys(myVar)[0]; to get the first key. If you are expecting more keys, you can use

Object.keys(myVar).forEach(function(k) {
    if(k === "typeA") {
        // do stuff
    }
    else if (k === "typeB") {
        // do more stuff
    }
    else {
        // do something
    }
});

Xcode Product -> Archive disabled

Change the active scheme Device from Simulator to Generic iOS Device

How to use refs in React with Typescript

To use the callback style (https://facebook.github.io/react/docs/refs-and-the-dom.html) as recommended on React's documentation you can add a definition for a property on the class:

export class Foo extends React.Component<{}, {}> {
// You don't need to use 'references' as the name
references: {
    // If you are using other components be more specific than HTMLInputElement
    myRef: HTMLInputElement;
} = {
    myRef: null
}
...
 myFunction() {
    // Use like this
    this.references.myRef.focus();
}
...
render() {
    return(<input ref={(i: any) => { this.references.myRef = i; }}/>)
}

How to redirect verbose garbage collection output to a file?

From the output of java -X:

    -Xloggc:<file>    log GC status to a file with time stamps

Documented here:

-Xloggc:filename

Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of -verbose:gc with the time elapsed since the first GC event preceding each logged event. The -Xloggc option overrides -verbose:gc if both are given with the same java command.

Example:

    -Xloggc:garbage-collection.log

So the output looks something like this:

0.590: [GC 896K->278K(5056K), 0.0096650 secs]
0.906: [GC 1174K->774K(5056K), 0.0106856 secs]
1.320: [GC 1670K->1009K(5056K), 0.0101132 secs]
1.459: [GC 1902K->1055K(5056K), 0.0030196 secs]
1.600: [GC 1951K->1161K(5056K), 0.0032375 secs]
1.686: [GC 1805K->1238K(5056K), 0.0034732 secs]
1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs]
1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

Reset Entity-Framework Migrations

Considering this still shows up when we search for EF in .NET Core, I'll post my answer here (Since it has haunted me a lot). Note that there are some subtleties with the EF 6 .NET version (No initial command, and you will need to delete "Snapshot" files)

(Tested in .NET Core 2.1)

Here are the steps:

  1. Delete the _efmigrationhistory table.
  2. Search for your entire solution for files that contain Snapshot in their name, such as ApplicationDbContextSnapshot.cs, and delete them.
  3. Rebuild your solution
  4. Run Add-Migration InitialMigration

Please note: You must delete ALL the Snapshot files. I spent countless hours just deleting the database... This will generate an empty migration if you don't do it.

Also, in #3 you can just name your migration however you want.

Here are some additional resources: asp.net CORE Migrations generated empty

Reset Entity Framework 7 migrations

What's the difference between an id and a class?

When applying CSS, apply it to a class and try to avoid as much as you can to an id. The ID should only be used in JavaScript to fetch the element or for any event binding.

Classes should be used to apply CSS.

Sometimes you do have to use classes for event binding. In such cases, try to avoid classes which are being used for applying CSS and rather add new classes which doesn't have corresponding CSS. This will come to help when you need to change the CSS for any class or change the CSS class name all together for any element.

Using group by on two fields and count in SQL

You must group both columns, group and sub-group, then use the aggregate function COUNT().

SELECT
  group, subgroup, COUNT(*)
FROM
  groups
GROUP BY
  group, subgroup

Finding the average of a list

In terms of efficiency and speed, these are the results that I got testing the other answers:

# test mean caculation

import timeit
import statistics
import numpy as np
from functools import reduce
import pandas as pd

LIST_RANGE = 10000000000
NUMBERS_OF_TIMES_TO_TEST = 10000

l = list(range(10))

def mean1():
    return statistics.mean(l)


def mean2():
    return sum(l) / len(l)


def mean3():
    return np.mean(l)


def mean4():
    return np.array(l).mean()


def mean5():
    return reduce(lambda x, y: x + y / float(len(l)), l, 0)

def mean6():
    return pd.Series(l).mean()



for func in [mean1, mean2, mean3, mean4, mean5, mean6]:
    print(f"{func.__name__} took: ",  timeit.timeit(stmt=func, number=NUMBERS_OF_TIMES_TO_TEST))

and the results:

mean1 took:  0.17030245899968577
mean2 took:  0.002183011999932205
mean3 took:  0.09744236000005913
mean4 took:  0.07070840100004716
mean5 took:  0.022754742999950395
mean6 took:  1.6689282460001778

so clearly the winner is: sum(l) / len(l)

How to check internet access on Android? InetAddress never times out

This method gives you the option for a really fast method (for real time feedback) or a slower method (for one off checks that require reliability)

public boolean isNetworkAvailable(bool SlowButMoreReliable) {
    bool Result = false; 
    try {
        if(SlowButMoreReliable){
            ConnectivityManager MyConnectivityManager = null;
            MyConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo MyNetworkInfo = null;
            MyNetworkInfo = MyConnectivityManager.getActiveNetworkInfo();

            Result = MyNetworkInfo != null && MyNetworkInfo.isConnected();

        } else
        {
            Runtime runtime = Runtime.getRuntime();
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");

            int i = ipProcess.waitFor();

            Result = i== 0;

        }

    } catch(Exception ex)
    {
        //Common.Exception(ex); //This method is one you should have that displays exceptions in your log
    }
    return Result;
}

Cancel a UIView animation?

When I work with UIStackView animation, besides removeAllAnimations() I need to set some values to initial one because removeAllAnimations() can set them to unpredictable state. I have stackView with view1 and view2 inside, and one view should be visible and one hidden:

public func configureStackView(hideView1: Bool, hideView2: Bool) {
    let oldHideView1 = view1.isHidden
    let oldHideView2 = view2.isHidden
    view1.layer.removeAllAnimations()
    view2.layer.removeAllAnimations()
    view.layer.removeAllAnimations()
    stackView.layer.removeAllAnimations()
    // after stopping animation the values are unpredictable, so set values to old
    view1.isHidden = oldHideView1 //    <- Solution is here
    view2.isHidden = oldHideView2 //    <- Solution is here

    UIView.animate(withDuration: 0.3,
                   delay: 0.0,
                   usingSpringWithDamping: 0.9,
                   initialSpringVelocity: 1,
                   options: [],
                   animations: {
                    view1.isHidden = hideView1
                    view2.isHidden = hideView2
                    stackView.layoutIfNeeded()
    },
                   completion: nil)
}

Highest Salary in each department

Assuming SQL Server 2005+

WITH cteRowNum AS (
    SELECT DeptID, EmpName, Salary,
           DENSE_RANK() OVER(PARTITION BY DeptID ORDER BY Salary DESC) AS RowNum
        FROM EmpDetails
)
SELECT DeptID, EmpName, Salary
    FROM cteRowNum
    WHERE RowNum = 1;

What do I do when my program crashes with exception 0xc0000005 at address 0?

I was getting the same issue with a different application,

Faulting application name: javaw.exe, version: 8.0.51.16, time stamp: 0x55763d32
Faulting module name: mscorwks.dll, version: 2.0.50727.5485, time stamp: 0x53a11d6c
Exception code: 0xc0000005
Fault offset: 0x0000000000501090
Faulting process id: 0x2960
Faulting application start time: 0x01d0c39a93c695f2
Faulting application path: C:\Program Files\Java\jre1.8.0_51\bin\javaw.exe
Faulting module path:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll

I was using the The Enhanced Mitigation Experience Toolkit (EMET) from Microsoft and I found by disabling the EMET features on javaw.exe in my case as this was the faulting application, it enabled my application to run successfully. Make sure you don't have any similar software with security protections on memory.

How do I break out of a loop in Scala?

import scala.util.control._

object demo_brk_963 
{
   def main(args: Array[String]) 
   {
      var a = 0;
      var b = 0;
      val numList1 = List(1,2,3,4,5,6,7,8,9,10);
      val numList2 = List(11,12,13);

      val outer = new Breaks; //object for break
      val inner = new Breaks; //object for break

      outer.breakable // Outer Block
      {
         for( a <- numList1)
         {
            println( "Value of a: " + a);

            inner.breakable // Inner Block
            {
               for( b <- numList2)
               {
                  println( "Value of b: " + b);

                  if( b == 12 )
                  {
                      println( "break-INNER;");
                       inner.break;
                  }
               }
            } // inner breakable
            if( a == 6 )
            {
                println( "break-OUTER;");
                outer.break;
            }
         }
      } // outer breakable.
   }
}

Basic method to break the loop, using Breaks class. By declaring the loop as breakable.

How can I retrieve the remote git address of a repo?

The long boring solution, which is not involved with CLI, you can manually navigate to:

your local repo folder ? .git folder (hidden) ? config file

then choose your text editor to open it and look for url located under the [remote "origin"] section.

Forcing label to flow inline with input that they label

Why don't You just use:

label {
    display: block;
    width: 50px;
    height: 24px;
    float: left;
}

How to execute a shell script from C in Linux?

If you need more fine-grade control, you can also go the fork pipe exec route. This will allow your application to retrieve the data outputted from the shell script.

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

Facebook Javascript SDK Problem: "FB is not defined"

To test Mattys suggestions about FB not finishing, I put an alert in the script. This cause a delay that I could control. Sure enough... it was a timing issue.

    $("document").ready(function () {
        // Wait...
        alert('Click ok to init');
        try {
            FB.init({
                appId: '###', // App ID
                status: true, // check login status
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true  // parse XFBML
            });
        }
        catch (err) {
            txt = "There was an error on this page.\n\n";
            txt += "Error description: " + err.message + "\n\n";
            txt += "Click OK to continue.\n\n";
            alert(txt);
        }
        FB.Event.subscribe('auth.statusChange', OnLogin);
    });

Where is android studio building my .apk file?

Mine application's apk was at this location

C:\Users\haseeb_mir\AndroidStudioProjects\MyTestApp\app\build\outputs\apk\debug

*ngIf else if in template

You can use multiple way based on sitaution:

  1. If you Variable is limited to specific Number or String, best way is using ngSwitch or ngIf:

    <!-- foo = 3 -->
    <div [ngSwitch]="foo">
        <div *ngSwitchCase="1">First Number</div>
        <div *ngSwitchCase="2">Second Number</div>
        <div *ngSwitchCase="3">Third Number</div>
        <div *ngSwitchDefault>Other Number</div>
    </div>
    
    <!-- foo = 3 -->
    <ng-template [ngIf]="foo === 1">First Number</ng-template>
    <ng-template [ngIf]="foo === 2">Second Number</ng-template>
    <ng-template [ngIf]="foo === 3">Third Number</ng-template>
    
    
    <!-- foo = 'David' -->
    <div [ngSwitch]="foo">
        <div *ngSwitchCase="'Daniel'">Daniel String</div>
        <div *ngSwitchCase="'David'">David String</div>
        <div *ngSwitchCase="'Alex'">Alex String</div>
        <div *ngSwitchDefault>Other String</div>
    </div>
    
    <!-- foo = 'David' -->
    <ng-template [ngIf]="foo === 'Alex'">Alex String</ng-template>
    <ng-template [ngIf]="foo === 'David'">David String</ng-template>
    <ng-template [ngIf]="foo === 'Daniel'">Daniel String</ng-template>
    
  2. Above not suitable for if elseif else codes and dynamic codes, you can use below code:

    <!-- foo = 5 -->
    <ng-container *ngIf="foo >= 1 && foo <= 3; then t13"></ng-container>
    <ng-container *ngIf="foo >= 4 && foo <= 6; then t46"></ng-container>
    <ng-container *ngIf="foo >= 7; then t7"></ng-container>
    
    <!-- If Statement -->
    <ng-template #t13>
        Template for foo between 1 and 3
    </ng-template>
    <!-- If Else Statement -->
    <ng-template #t46>
        Template for foo between 4 and 6
    </ng-template>
    <!-- Else Statement -->
    <ng-template #t7>
        Template for foo greater than 7
    </ng-template>
    

Note: You can choose any format, but notice every code has own problems

How do I retrieve the number of columns in a Pandas data frame?

In order to include the number of row index "columns" in your total shape I would personally add together the number of columns df.columns.size with the attribute pd.Index.nlevels/pd.MultiIndex.nlevels:

Set up dummy data

import pandas as pd

flat_index = pd.Index([0, 1, 2])
multi_index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), names=["letter", "id"])

columns = ["cat", "dog", "fish"]

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_df = pd.DataFrame(data, index=flat_index, columns=columns)
multi_df = pd.DataFrame(data, index=multi_index, columns=columns)

# Show data
# -----------------
# 3 columns, 4 including the index
print(flat_df)
    cat  dog  fish
id                
0     1    2     3
1     4    5     6
2     7    8     9

# -----------------
# 3 columns, 5 including the index
print(multi_df)
           cat  dog  fish
letter id                
a      1     1    2     3
       2     4    5     6
b      1     7    8     9

Writing our process as a function:

def total_ncols(df, include_index=False):
    ncols = df.columns.size
    if include_index is True:
        ncols += df.index.nlevels
    return ncols

print("Ignore the index:")
print(total_ncols(flat_df), total_ncols(multi_df))

print("Include the index:")
print(total_ncols(flat_df, include_index=True), total_ncols(multi_df, include_index=True))

This prints:

Ignore the index:
3 3

Include the index:
4 5

If you want to only include the number of indices if the index is a pd.MultiIndex, then you can throw in an isinstance check in the defined function.

As an alternative, you could use df.reset_index().columns.size to achieve the same result, but this won't be as performant since we're temporarily inserting new columns into the index and making a new index before getting the number of columns.

How to use Lambda in LINQ select statement

using LINQ query expression

 IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID };

 ViewBag.storeSelector = stores;

or using LINQ extension methods with lambda expressions

 IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(store => new SelectListItem { Value = store.Name, Text = store.ID });

 ViewBag.storeSelector = stores;

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

gradient descent using python and numpy

I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations:

  1. Calculate the hypothesis h = X * theta
  2. Calculate the loss = h - y and maybe the squared cost (loss^2)/2m
  3. Calculate the gradient = X' * loss / m
  4. Update the parameters theta = theta - alpha * gradient

In your case, I guess you have confused m with n. Here m denotes the number of examples in your training set, not the number of features.

Let's have a look at my variation of your code:

import numpy as np
import random

# m denotes the number of examples here, not the number of features
def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.transpose()
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        # avg cost per example (the 2 in 2*m doesn't really matter here.
        # But to be consistent with the gradient, I include it)
        cost = np.sum(loss ** 2) / (2 * m)
        print("Iteration %d | Cost: %f" % (i, cost))
        # avg gradient per example
        gradient = np.dot(xTrans, loss) / m
        # update
        theta = theta - alpha * gradient
    return theta


def genData(numPoints, bias, variance):
    x = np.zeros(shape=(numPoints, 2))
    y = np.zeros(shape=numPoints)
    # basically a straight line
    for i in range(0, numPoints):
        # bias feature
        x[i][0] = 1
        x[i][1] = i
        # our target variable
        y[i] = (i + bias) + random.uniform(0, 1) * variance
    return x, y

# gen 100 points with a bias of 25 and 10 variance as a bit of noise
x, y = genData(100, 25, 10)
m, n = np.shape(x)
numIterations= 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)

At first I create a small random dataset which should look like this:

Linear Regression

As you can see I also added the generated regression line and formula that was calculated by excel.

You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by m.

The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it.

If you run my example, the theta returned will look like this:

Iteration 99997 | Cost: 47883.706462
Iteration 99998 | Cost: 47883.706462
Iteration 99999 | Cost: 47883.706462
[ 29.25567368   1.01108458]

Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.

How can a add a row to a data frame in R?

There's now add_row() from the tibble or tidyverse packages.

library(tidyverse)
df %>% add_row(hello = "hola", goodbye = "ciao")

Unspecified columns get an NA.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

There are two solutions to this:

a) Set your PATH variable to include "/usr/local/bin"

export PATH="$PATH:/usr/local/bin"

b) Create a symlink to "/usr/bin" which is already in your PATH

ln -s /usr/bin/nodejs /usr/bin/node

I hope it helps.

Set Background cell color in PHPExcel

This always running!

$sheet->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setRGB('FF0000');

git is not installed or not in the PATH

In my case the issue was not resolved because i did not restart my system. Please make sure you do restart your system.

The executable gets signed with invalid entitlements in Xcode

I came across exactly the same issue quite recently. After reading many different advices which none of them worked for me, I finally went under the hood and found the root cause of the issue.

Mobile provisioning file actually DOESN'T match with the Entitlements file generated by Xcode.

Although all files are anaged automatically by Apple tool, they are not correct.

If you download provisioning file from Apple portal and open it (you can open it because it's just plist file signed by your certificate, so it's readable by text editor) and compare it with your Entitlements file (automatically generated by Xcode and residing in project files (so it's again plist XML file readable by text editor). Then you can see the difference.

In my case it was Game Center entitlement. It was displayed on the portal as checked (checked by default) but actually this entitlement was not included in mobile provisioning file. So it was matter of deleting it from Entitlements file.

So the result is - content of mobile provisioning profile sometimes doesn't match with what is displayed on the APP ID configuration page.

Join two data frames, select all columns from one and some columns from the other

function to drop duplicate columns after joining.

check it

def dropDupeDfCols(df): newcols = [] dupcols = []

for i in range(len(df.columns)):
    if df.columns[i] not in newcols:
        newcols.append(df.columns[i])
    else:
        dupcols.append(i)

df = df.toDF(*[str(i) for i in range(len(df.columns))])
for dupcol in dupcols:
    df = df.drop(str(dupcol))

return df.toDF(*newcols)

Fastest JavaScript summation

While searching for the best method to sum an array, I wrote a performance test.

In Chrome, "reduce" seems to be vastly superior

I hope this helps

// Performance test, sum of an array
  var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var result = 0;
// Eval
  console.time("eval");
  for(var i = 0; i < 10000; i++) eval("result = (" + array.join("+") + ")");
  console.timeEnd("eval");
// Loop
  console.time("loop");
  for(var i = 0; i < 10000; i++){
    result = 0;
    for(var j = 0; j < array.length; j++){
      result += parseInt(array[j]);
    }
  }
  console.timeEnd("loop");
// Reduce
  console.time("reduce");
  for(var i = 0; i < 10000; i++) result = array.reduce(function(pv, cv) { return pv + parseInt(cv); }, 0);
  console.timeEnd("reduce");
// While
  console.time("while");
  for(var i = 0; i < 10000; i++){
    j = array.length;
    result = 0;
    while(j--) result += array[i];
  }
  console.timeEnd("while");

eval: 5233.000ms

loop: 255.000ms

reduce: 70.000ms

while: 214.000ms

TERM environment variable not set

You've answered the question with this statement:

Cron calls this .sh every 2 minutes

Cron does not run in a terminal, so why would you expect one to be set?

The most common reason for getting this error message is because the script attempts to source the user's .profile which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:

#!/bin/bash -p

Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.

If this is the entirety of the script, then the TERM error is coming from something other than the plain content of the script.

WCF Service Returning "Method Not Allowed"

It sounds like you're using an incorrect address:

To access the Service I enter http://localhost/project/myService.svc/FileUpload

Assuming you mean this is the address you give your client code then I suspect it should actually be:

http://localhost/project/myService.svc

Swift - Remove " character from string

To remove the optional you only should do this

println("\(text2!)")

cause if you dont use "!" it takes the optional value of text2

And to remove "" from 5 you have to convert it to NSInteger or NSNumber easy peasy. It has "" cause its an string.

How to do an update + join in PostgreSQL?

For those wanting to do a JOIN that updates ONLY the rows your join returns use:

UPDATE a
SET price = b_alias.unit_price
FROM      a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value' 
AND a.id = a_alias.id
--the below line is critical for updating ONLY joined rows
AND a.pk_id = a_alias.pk_id;

This was mentioned above but only through a comment..Since it's critical to getting the correct result posting NEW answer that Works

How to ignore files/directories in TFS for avoiding them to go to central source repository?

I'm going to assume you are using Web Site Projects. These automatically crawl their project directory and throw everything into source control. There's no way to stop them.

However, don't despair. Web Application Projects don't exhibit this strange and rather unexpected (imho: moronic) behavior. WAP is an addon on for VS2005 and comes direct with VS2008.

As an alternative to changing your projects to WAP, you might consider moving the Assets folder out of Source control and into a TFS Document Library. Only do this IF the project itself doesn't directly use the assets files.

Data truncated for column?

In my case it was a table with an ENUM that accepts the days of the week as integers (0 to 6). When inserting the value 0 as an integer I got the error message "Data truncated for column ..." so to fix it I had to cast the integer to a string. So instead of:

$item->day = 0;

I had to do;

$item->day = (string) 0;

It looks silly to cast the zero like that but in my case it was in a Laravel factory, and I had to write it like this:

$factory->define(App\Schedule::class, function (Faker $faker) {
    return [
        'day' => (string) $faker->numberBetween(0, 6),
        //
    ];
});

Push eclipse project to GitHub with EGit

Simple Steps:

-Open Eclipse.

  • Select Project which you want to push on github->rightclick.
  • select Team->share Project->Git->Create repository->finish.(it will ask to login in Git account(popup).
  • Right click again to Project->Team->commit. you are done

Freeze screen in chrome debugger / DevTools panel for popover inspection?

To be able to inspect any element do the following. This should work even if it's hard to duplicate the hover state:

  • Run the following javascript in the console. This will break into the debugger in 5 seconds.

    setTimeout(function(){debugger;}, 5000)

  • Go show your element (by hovering or however) and wait until Chrome breaks into the Debugger.

  • Now click on the Elements tab in the Chrome Inspector, and you can look for your element there.
  • You may also be able to click on the Find Element icon (looks like a magnifying glass) and Chrome will let you go and inspect and find your element on the page by right clicking on it, then choosing Inspect Element

Note that this approach is a slight variation to this other great answer on this page.

Create a simple HTTP server with Java?

Java 6 has a default embedded http server.

Check the thread here

By the way, if you plan to have a rest web service, here is a simple example using jersey.

Dynamic Height Issue for UITableView Cells (Swift)

Set proper constraint and update delegate methods as:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

This will resolve dynamic cell height issue. IF not you need to check constraints.

How to ping multiple servers and return IP address and Hostnames using batch script?

Try this

$servers = Get-Content test.txt

$reg=""

foreach ($server in $servers) 

{

$reg=$reg+$server+"`t"+([System.Net.Dns]::GetHostAddresses($server) | foreach {echo $_.IPAddressToString})+"`n"

 }
$reg >reg.csv

Best way to change the background color for an NSView

In swift you can subclass NSView and do this

class MyView:NSView {
    required init?(coder: NSCoder) {
        super.init(coder: coder);

        self.wantsLayer = true;
        self.layer?.backgroundColor = NSColor.redColor().CGColor;
    }
}

How to get the focused element with jQuery?

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

Which one should you use? quoting the jQuery docs:

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':focus') is equivalent to $('*:focus'). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

The answer is:

document.activeElement

And if you want a jQuery object wrapping the element:

$(document.activeElement)

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Example

//In Model

public class MyModel
{  
   [Required]
    public string Name{ get; set; }
}

//In PartailView //PartailView.cshtml

@model MyModel

<div>
    <div>
      @Html.LabelFor(model=>model.Name)
    </div>
    <div>
        @Html.EditorFor(model=>model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
</div>

In Index.cshtml view

@model MyModel
<div id="targetId">
    @{Html.RenderPartial("PartialView",Model)}
</div>

@using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" }))
{
     <div>
        <input type="submit" value="Add Unit" />
    </div>
}

In Controller

public ActionResult Index()
{
  return View(new MyModel());
}


public string AddName(MyModel model)
{
   string HtmlString = RenderPartialViewToString("PartailView",model);
   return HtmlString;
}


protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model and append the content in "targetId" div in Index.cshtml. I this way by catching RenderHtml of partial view you can apply validation.

jQuery ajax request being block because Cross-Origin

There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.

The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.

How to highlight text using javascript

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

Error: Local workspace file ('angular.json') could not be found

~/Desktop $ ng serve

Local workspace file ('angular.json') could not be found.

Error: Local workspace file ('angular.json') could not be found.

at WorkspaceLoader._getProjectWorkspaceFilePath (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:37:19)
at WorkspaceLoader.loadWorkspace (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:24:21)
at ServeCommand._loadWorkspaceAndArchitect (/usr/lib/node_modules/@angular/cli/models/architect-command.js:180:32)
at ServeCommand.<anonymous> (/usr/lib/node_modules/@angular/cli/models/architect-command.js:47:25)
at Generator.next (<anonymous>)
at /usr/lib/node_modules/@angular/cli/models/architect-command.js:7:71
at new Promise (<anonymous>)
at __awaiter (/usr/lib/node_modules/@angular/cli/models/architect-command.js:3:12)
at ServeCommand.initialize (/usr/lib/node_modules/@angular/cli/models/architect-command.js:46:16)
at Object.<anonymous> (/usr/lib/node_modules/@angular/cli/models/command-runner.js:87:23)

This is because I haven't choose the Angular project directory.

It should be like:

~/Desktop/angularproject $ ng serve

What is considered a good response time for a dynamic, personalized web application?

There's a great deal of research on this. Here's a quick summary.

Response Times: The 3 Important Limits

by Jakob Nielsen on January 1, 1993

Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance.

Excerpt from Chapter 5 in my book Usability Engineering, from 1993:

The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:

  • 0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.
  • 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
  • 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

How to open generated pdf using jspdf in new window

This is how I handle it.

window.open(doc.output('bloburl'), '_blank');

How to fix "unable to open stdio.h in Turbo C" error?

Since you did not mention which version of Turbo C this method below will cover both v2 and v3.

  • Click on 'Options', 'Directories', enter the proper location for the Include and Lib directories.

How to print a debug log?

error_log(print_r($variable, TRUE)); 

might be useful

How can I determine if a .NET assembly was built for x86 or x64?

An alternative to already mentioned tools is Telerik JustDecompile (free tool) which will display the information next to the assembly name:

Any or x86 or x64 information in Telerik

What is the best way to give a C# auto-property an initial value?

little complete sample:

using System.ComponentModel;

private bool bShowGroup ;
[Description("Show the group table"), Category("Sea"),DefaultValue(true)]
public bool ShowGroup
{
    get { return bShowGroup; }
    set { bShowGroup = value; }
}

Heap vs Binary Search Tree (BST)

When to use a heap and when to use a BST

Heap is better at findMin/findMax (O(1)), while BST is good at all finds (O(logN)). Insert is O(logN) for both structures. If you only care about findMin/findMax (e.g. priority-related), go with heap. If you want everything sorted, go with BST.

First few slides from here explain things very clearly.

How to remove last n characters from a string in Bash?

In this case you could use basename assuming you have the same suffix on the files you want to remove.

Example:

basename -s .rtf "some string.rtf"

This will return "some string"

If you don't know the suffix, and want it to remove everything after and including the last dot:

f=file.whateverthisis
basename "${f%.*}"

outputs "file"

% means chop, . is what you are chopping, * is wildcard

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

If you want to filter rows by a certain number of columns with null values, you may use this:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

So, here is the example:

Your dataframe:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

If you want to select the rows that have two or more columns with null value, you run the following:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

Capture keyboardinterrupt in Python without try-except

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal
import sys
import time
import threading

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()

ActiveRecord OR query

Just add an OR in the conditions

Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])

Does Spring @Transactional attribute work on a private method?

Spring Docs explain that

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

Another way is user BeanSelfAware

React Checkbox not sending onChange

In the scenario you would NOT like to use the onChange handler on the input DOM, you can use the onClick property as an alternative. The defaultChecked, the condition may leave a fixed state for v16 IINM.

 class CrossOutCheckbox extends Component {
      constructor(init){
          super(init);
          this.handleChange = this.handleChange.bind(this);
      }
      handleChange({target}){
          if (target.checked){
             target.removeAttribute('checked');
             target.parentNode.style.textDecoration = "";
          } else {
             target.setAttribute('checked', true);
             target.parentNode.style.textDecoration = "line-through";
          }
      }
      render(){
         return (
            <span>
              <label style={{textDecoration: this.props.complete?"line-through":""}}>
                 <input type="checkbox"
                        onClick={this.handleChange}
                        defaultChecked={this.props.complete}
                  />
              </label>
                {this.props.text}
            </span>
        )
    }
 }

I hope this helps someone in the future.

How do you determine a processing time in Python?

You can implement two tic() and tac() functions, where tic() captures the time which it is called, and tac() prints the time difference since tic() was called. Here is a short implementation:

import time

_start_time = time.time()

def tic():
    global _start_time 
    _start_time = time.time()

def tac():
    t_sec = round(time.time() - _start_time)
    (t_min, t_sec) = divmod(t_sec,60)
    (t_hour,t_min) = divmod(t_min,60) 
    print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec))

Now in your code you can use it as:

tic()
do_some_stuff()
tac()

and it will, for example, output:

Time passed: 0hour:7min:26sec

See also:

How to get first object out from List<Object> using Linq

I would to it like this:

//Dictionary object with Key as string and Value as List of Component type object
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();

//from each element of the dictionary select first component if any
IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep"));

but only if it is sure that list contains only objects of Component class or children

Uncaught TypeError: Cannot read property 'top' of undefined

If this error appears whenever you click on the <a> tag. Try the code below.

CORRECT :

<a href="javascript:void(0)">

This malfunction occurs because your href is set to # inside of your <a> tag. Basically, your app is trying to find href which does not exist. The right way to set empty href is shown above.

WRONG :

<a href="#">

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

What is the best project structure for a Python application?

Try starting the project using the python_boilerplate template. It largely follows the best practices (e.g. those here), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library).

  • Where do you put the source?

    • For decently large projects it makes sense to split the source into several eggs. Each egg would go as a separate setuptools-layout under PROJECT_ROOT/src/<egg_name>.
  • Where do you put application startup scripts?

    • The ideal option is to have application startup script registered as an entry_point in one of the eggs.
  • Where do you put the IDE project cruft?

    • Depends on the IDE. Many of them keep their stuff in PROJECT_ROOT/.<something> in the root of the project, and this is fine.
  • Where do you put the unit/acceptance tests?

    • Each egg has a separate set of tests, kept in its PROJECT_ROOT/src/<egg_name>/tests directory. I personally prefer to use py.test to run them.
  • Where do you put non-Python data such as config files?

    • It depends. There can be different types of non-Python data.
      • "Resources", i.e. data that must be packaged within an egg. This data goes into the corresponding egg directory, somewhere within package namespace. It can be used via the pkg_resources package from setuptools, or since Python 3.7 via the importlib.resources module from the standard library.
      • "Config-files", i.e. non-Python files that are to be regarded as external to the project source files, but have to be initialized with some values when application starts running. During development I prefer to keep such files in PROJECT_ROOT/config. For deployment there can be various options. On Windows one can use %APP_DATA%/<app-name>/config, on Linux, /etc/<app-name> or /opt/<app-name>/config.
      • Generated files, i.e. files that may be created or modified by the application during execution. I would prefer to keep them in PROJECT_ROOT/var during development, and under /var during Linux deployment.
  • Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
    • Into PROJECT_ROOT/src/<egg_name>/native

Documentation would typically go into PROJECT_ROOT/doc or PROJECT_ROOT/src/<egg_name>/doc (this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like PROJECT_ROOT/buildout.cfg and PROJECT_ROOT/setup.cfg.

How to use ScrollView in Android?

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

android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:stretchColumns="1" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <RadioGroup
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >

                <RadioButton
                    android:id="@+id/butonSecim1"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight=".50"
                    android:text="@string/buton1Text" />

                <RadioButton
                    android:id="@+id/butonSecim2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight=".50"
                    android:text="@string/buton2Text" />
            </RadioGroup>
        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TableLayout
                android:id="@+id/bilgiAlani"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:visibility="invisible" >

                <TableRow
                    android:id="@+id/BilgiAlanitableRow2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >

                    <TextView
                        android:id="@+id/bilgiMesaji"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_weight=".100"
                        android:ems="10"
                        android:gravity="left|top"
                        android:inputType="textMultiLine" />
                </TableRow>
            </TableLayout>
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/metin4"
                android:layout_height="match_parent"
                android:layout_weight=".100"
                android:text="deneme" />
        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/metin5"
                android:layout_height="match_parent"
                android:layout_weight=".100"
                android:text="deneme" />
        </TableRow>
    </TableLayout>

</ScrollView>

What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

Java - Check if JTextField is empty or not

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Submit Button        

    String Fname = jTextField1.getText();
    String Lname = jTextField2.getText();
    String Desig = jTextField3.getText();
    String Nic = jTextField4.getText();
    String Phone = jTextField5.getText();
    String Add = jTextArea1.getText();
    String Dob = jTextField6.getText();
    // String Gender;
    // Image

    if (Fname.hashCode() == 0 || Lname.hashCode() == 0 || Desig.hashCode() == 0 || Nic.hashCode() == 0 || Phone.hashCode() == 0 || Add.hashCode() == 0)
    {
        JOptionPane.showMessageDialog(null, "Some fields are empty!");
    }
    else
    {
        JOptionPane.showMessageDialog(null, "OK");
    }
}

Iterate over the lines of a string

You can iterate over "a file", which produces lines, including the trailing newline character. To make a "virtual file" out of a string, you can use StringIO:

import io  # for Py2.7 that would be import cStringIO as io

for line in io.StringIO(foo):
    print(repr(line))

Generate fixed length Strings filled with whitespaces

Utilize String.format's padding with spaces and replace them with the desired char.

String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);

Prints 000Apple.


Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).

int width = 10;
char fill = '0';

String toPad = "New York";
String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
System.out.println(padded);

Prints 00New York.

But a check needs to be added to prevent the attempt of creating a char array with negative length.

Sort divs in jQuery based on attribute 'data-sort'?

I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.

_x000D_
_x000D_
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
    elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
   $('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
   <div class="imgs" data-image-id='1'>1</div>_x000D_
   <div class="imgs" data-image-id='2'>2</div>_x000D_
   <div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/ruys9ksg/

(13: Permission denied) while connecting to upstream:[nginx]

13-permission-denied-while-connecting-to-upstreamnginx on centos server -

setsebool -P httpd_can_network_connect 1

How do you reinstall an app's dependencies using npm?

Most of the time I use the following command to achieve a complete reinstall of all the node modules (be sure you are in the project folder).

rm -rf node_modules && npm install

You can also run npm cache clean after removing the node_modules folder to be sure there aren't any cached dependencies.

How do I bind a WPF DataGrid to a variable number of columns?

I have found a blog article by Deborah Kurata with a nice trick how to show variable number of columns in a DataGrid:

Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM

Basically, she creates a DataGridTemplateColumn and puts ItemsControl inside that displays multiple columns.

How to properly create an SVN tag from trunk?

@victor hugo and @unwind are correct, and victor's solution is by far the simplest. However BEWARE of externals in your SVN project. If you reference external libraries, the external's revision reference (whether a tag, or HEAD, or number) will remain unchanged when you tag directories that have external references.

It is possible to create a script to handle this aspect of tagging, for a discussion on that topic, see this SO article: Tagging an SVN checkout with externals

How do I import other TypeScript files?

I would avoid now using /// <reference path='moo.ts'/>but for external libraries where the definition file is not included into the package.

The reference path solves errors in the editor, but it does not really means the file needs to be imported. Therefore if you are using a gulp workflow or JSPM, those might try to compile separately each file instead of tsc -out to one file.

From Typescript 1.5

Just prefix what you want to export at the file level (root scope)

aLib.ts

{
export class AClass(){} // exported i.e. will be available for import
export valueZero = 0; // will be available for import
}

You can also add later in the end of the file what you want to export

{
class AClass(){} // not exported yet
valueZero = 0; // not exported yet
valueOne = 1; // not exported (and will not in this example)

export {AClass, valueZero} // pick the one you want to export
}

Or even mix both together

{
class AClass(){} // not exported yet
export valueZero = 0; // will be available for import
export {AClass} // add AClass to the export list
}

For the import you have 2 options, first you pick again what you want (one by one)

anotherFile.ts

{
import {AClass} from "./aLib.ts"; // you import only AClass
var test = new AClass();
}

Or the whole exports

{
import * as lib from "./aLib.ts"; // you import all the exported values within a "lib" object
var test = new lib.AClass();
}

Note regarding the exports: exporting twice the same value will raise an error { export valueZero = 0; export {valueZero}; // valueZero is already exported… }

Replace CRLF using powershell

You have not specified the version, I'm assuming you are using Powershell v3.

Try this:

$path = "C:\Users\abc\Desktop\File\abc.txt"
(Get-Content $path -Raw).Replace("`r`n","`n") | Set-Content $path -Force

Editor's note: As mike z points out in the comments, Set-Content appends a trailing CRLF, which is undesired. Verify with: 'hi' > t.txt; (Get-Content -Raw t.txt).Replace("`r`n","`n") | Set-Content t.txt; (Get-Content -Raw t.txt).EndsWith("`r`n"), which yields $True.

Note this loads the whole file in memory, so you might want a different solution if you want to process huge files.

UPDATE

This might work for v2 (sorry nowhere to test):

$in = "C:\Users\abc\Desktop\File\abc.txt"
$out = "C:\Users\abc\Desktop\File\abc-out.txt"
(Get-Content $in) -join "`n" > $out

Editor's note: Note that this solution (now) writes to a different file and is therefore not equivalent to the (still flawed) v3 solution. (A different file is targeted to avoid the pitfall Ansgar Wiechers points out in the comments: using > truncates the target file before execution begins). More importantly, though: this solution too appends a trailing CRLF, which may be undesired. Verify with 'hi' > t.txt; (Get-Content t.txt) -join "`n" > t.NEW.txt; [io.file]::ReadAllText((Convert-Path t.NEW.txt)).endswith("`r`n"), which yields $True.

Same reservation about being loaded to memory though.

How to query as GROUP BY in django?

An easy solution, but not the proper way is to use raw SQL:

results = Members.objects.raw('SELECT * FROM myapp_members GROUP BY designation')

Another solution is to use the group_by property:

query = Members.objects.all().query
query.group_by = ['designation']
results = QuerySet(query=query, model=Members)

You can now iterate over the results variable to retrieve your results. Note that group_by is not documented and may be changed in future version of Django.

And... why do you want to use group_by? If you don't use aggregation, you can use order_by to achieve an alike result.

MS Access DB Engine (32-bit) with Office 64-bit

A similar approach to @Peter Coppins answer. This, I think, is a bit easier and doesn't require the use of the Orca utility:

  1. Check the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" registry key and make sure the value "mso.dll" is NOT present. If it is present, then Office 64-bit seems to be installed and you should not need this workaround.

  2. Download the Microsoft Access Database Engine 2010 Redistributable.

  3. From the command line, run: AccessDatabaseEngine_x64.exe /passive

(Note: this installer silently crashed or failed for me, so I unzipped the components and ran: AceRedist.msi /passive and that installed fine. Maybe a Windows 10 thing.)

  1. Delete or rename the "mso.dll" value in the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" key.

Source: How to install 64-bit Microsoft Database Drivers alongside 32-bit Microsoft Office

Split comma-separated input box values into array in jquery, and loop through it

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

Invalid default value for 'dateAdded'

CURRENT_TIMESTAMP is only acceptable on TIMESTAMP fields. DATETIME fields must be left either with a null default value, or no default value at all - default values must be a constant value, not the result of an expression.

relevant docs: http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html

You can work around this by setting a post-insert trigger on the table to fill in a "now" value on any new records.

Fixing Segmentation faults in C++

Yes, there is a problem with pointers. Very likely you're using one that's not initialized properly, but it's also possible that you're messing up your memory management with double frees or some such.

To avoid uninitialized pointers as local variables, try declaring them as late as possible, preferably (and this isn't always possible) when they can be initialized with a meaningful value. Convince yourself that they will have a value before they're being used, by examining the code. If you have difficulty with that, initialize them to a null pointer constant (usually written as NULL or 0) and check them.

To avoid uninitialized pointers as member values, make sure they're initialized properly in the constructor, and handled properly in copy constructors and assignment operators. Don't rely on an init function for memory management, although you can for other initialization.

If your class doesn't need copy constructors or assignment operators, you can declare them as private member functions and never define them. That will cause a compiler error if they're explicitly or implicitly used.

Use smart pointers when applicable. The big advantage here is that, if you stick to them and use them consistently, you can completely avoid writing delete and nothing will be double-deleted.

Use C++ strings and container classes whenever possible, instead of C-style strings and arrays. Consider using .at(i) rather than [i], because that will force bounds checking. See if your compiler or library can be set to check bounds on [i], at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers.

Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems. They will doubtless fail to fix everything, and that's why you should use valgrind now and then when you don't have problems, and valgrind and gdb when you do.

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

You should run:

composer dump-autoload

and if does not work you should:

re-install composer

Count multiple columns with group by in one query

You didn't say which database server you are using, but if temp tables are available they may be the best approach.

// table is a temp table
select ... into #table ....
SELECT COUNT(column1),column1 FROM #table GROUP BY column1  
SELECT COUNT(column2),column2 FROM #table GROUP BY column2  
SELECT COUNT(column3),column3 FROM #table GROUP BY column3  
// drop may not be required
drop table #table

Initialize a string variable in Python: "" or None?

None is used to indicate "not set", whereas any other value is used to indicate a "default" value.

Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.

Notice that it doesn't matter if your variable is a string initially. You can change it to any other type/value at any other moment.

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

Sprint == Iteration.

The lengths can vary, but it's a bad planning precedent to let them vary too much.

Keep them consistent in duration and you will get better at planning and delivering. Everything will be measured by how many 10-day sprints it takes to finish a series of use cases.

Keep them consistent in length and you can plan your deliveries, end-user testing, etc., with more accuracy.

The point is to release on time at a consistent pace. A regular schedule makes management slightly simpler and more predictable.

Py_Initialize fails - unable to load the file system codec

Ran into the same thing trying to install brew's python3 under Mac OS! The issue here is that in Mac OS, homebrew puts the "real" python a whole layer deeper than you think. You would think from the homebrew output that

$ echo $PYTHONHOME
/usr/local/Cellar/python3/3.6.2/
$ echo $PYTHONPATH
/usr/local/Cellar/python3/3.6.2/bin

would be correct, but invoking $PYTHONPATH/python3 immediately crashes with the abort 6 "can't find encodings." This is because although that $PYTHONHOME looks like a complete installation, having a bin, lib etc, it is NOT the actual Python, which is in a Mac OS "Framework". Do this:

PYTHONHOME=/usr/local/Cellar/python3/3.x.y/Frameworks/Python.framework/Versions/3.x
PYTHONPATH=$PYTHONHOME/bin

(substituting version numbers as appropriate) and it will work fine.

Use String.split() with multiple delimiters

pdfName.split("[.-]+");

  • [.-] -> any one of the . or - can be used as delimiter

  • + sign signifies that if the aforementioned delimiters occur consecutively we should treat it as one.

How to prevent a click on a '#' link from jumping to top of page?

Links with href="#" should almost always be replaced with a button element:

<button class="someclass">Text</button>

Using links with href="#" is also an accessibility concern as these links will be visible to screen readers, which will read out "Link - Text" but if the user clicks it won't go anywhere.

Sort a list alphabetically

You should be able to use OrderBy in LINQ...

var sortedItems = myList.OrderBy(s => s);

Getting full JS autocompletion under Sublime Text

As already mentioned, tern.js is a new and promising project with plugins for Sublime Text, Vim and Emacs. I´ve been using TernJS for Sublime for a while and the suggestions I get are way better than the standard ones:

enter image description here

Tern scans all .js files in your project. You can get support for DOM, nodejs, jQuery, and more by adding "libs" in your .sublime-project file:

"ternjs": {
    "exclude": ["wordpress/**", "node_modules/**"],
    "libs": ["browser", "jquery"],
    "plugins": {
        "requirejs": {
            "baseURL": "./js"
        }
    }
}

enter image description here

Adding null values to arraylist

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

How to do an array of hashmaps?

Java doesn't want you to make an array of HashMaps, but it will let you make an array of Objects. So, just write up a class declaration as a shell around your HashMap, and make an array of that class. This lets you store some extra data about the HashMaps if you so choose--which can be a benefit, given that you already have a somewhat complex data structure.

What this looks like:

private static someClass[] arr = new someClass[someNum];

and

public class someClass {

private static int dataFoo;
private static int dataBar;
private static HashMap<String, String> yourArray;

...

}

How can I INSERT data into two tables simultaneously in SQL Server?

Another option is to run the two inserts separately, leaving the FK column null, then running an update to poulate it correctly.

If there is nothing natural stored within the two tables that match from one record to another (likely) then create a temporary GUID column and populate this in your data and insert to both fields. Then you can update with the proper FK and null out the GUIDs.

E.g.:

CREATE TABLE [dbo].[table1] ( 
    [id] [int] IDENTITY(1,1) NOT NULL, 
    [data] [varchar](255) NOT NULL, 
    CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED ([id] ASC),
    JoinGuid UniqueIdentifier NULL
) 

CREATE TABLE [dbo].[table2] ( 
    [id] [int] IDENTITY(1,1) NOT NULL, 
    [table1_id] [int] NULL, 
    [data] [varchar](255) NOT NULL, 
    CONSTRAINT [PK_table2] PRIMARY KEY CLUSTERED ([id] ASC),
    JoinGuid UniqueIdentifier NULL
) 


INSERT INTO Table1....

INSERT INTO Table2....

UPDATE b
SET table1_id = a.id
FROM Table1 a
JOIN Table2 b on a.JoinGuid = b.JoinGuid
WHERE b.table1_id IS NULL

UPDATE Table1 SET JoinGuid = NULL
UPDATE Table2 SET JoinGuid = NULL

Location of the mongodb database on mac

Thanks @Mark, I keep forgetting this again and again. After installing MongoDB with Homebrew:

  • The databases are stored in the /usr/local/var/mongodb/ directory
  • The mongod.conf file is here: /usr/local/etc/mongod.conf
  • The mongo logs can be found at /usr/local/var/log/mongodb/
  • The mongo binaries are here: /usr/local/Cellar/mongodb/[version]/bin

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Toggle Class in React

Toggle function in react

At first you should create constructor like this

constructor(props) {
        super(props);
        this.state = {
            close: true,
        };
    }

Then create a function like this

yourFunction = () => {
        this.setState({
            close: !this.state.close,
        });
    };

then use this like

render() {
        const {close} = this.state;
        return (

            <Fragment>

                 <div onClick={() => this.yourFunction()}></div>

                 <div className={close ? "isYourDefaultClass" : "isYourOnChangeClass"}></div>

            </Fragment>
        )
    }
}

Please give better solutions

IP to Location using Javascript

Just in case you were not able to accomplish the above code, here is a simple way of using it with jquery:

$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",
    function (data) {
        for (var i in data) {
            document.write('data["i"] = ' + i + '<br/>');
        }
    }
);

VC++ fatal error LNK1168: cannot open filename.exe for writing

well, I actually just saved and closed the project and restarted VS Express 2013 in windows 8 and that sorted my problem.

Set font-weight using Bootstrap classes

In Bootstrap 4:

class="font-weight-bold"

Or:

<strong>text</strong>

What is AndroidX?

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Changes in gradle:

implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'

When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library

Refer to: https://developer.android.com/jetpack/androidx/migrate

How to define an optional field in protobuf 3

One way is to optional like described in the accepted answer: https://stackoverflow.com/a/62566052/1803821

Another one is to use wrapper objects. You don't need to write them yourself as google already provides them:

At the top of your .proto file add this import:

import "google/protobuf/wrappers.proto";

Now you can use special wrappers for every simple type:

DoubleValue
FloatValue
Int64Value
UInt64Value
Int32Value
UInt32Value
BoolValue
StringValue
BytesValue

So to answer the original question a usage of such a wrapper could be like this:

message Foo {
    int32 bar = 1;
    google.protobuf.Int32Value baz = 2;
}

Now for example in Java I can do stuff like:

if(foo.hasBaz()) { ... }

Bootstrap dropdown not working

FYI: If you have bootstrap.js, you should not add bootstrap-dropdown.js.

I'm unsure of the result with bootstrap.min.js.

What is the difference between 'typedef' and 'using' in C++11?

They are equivalent, from the standard (emphasis mine) (7.1.3.2):

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

python: iterate a specific range in a list

You want to use slicing.

for item in listOfStuff[1:3]:
    print item

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

How to convert Observable<any> to array[]

Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.

Using your CountryData class, you would define a service method like this:

getCountries()  {
  return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}

Then when you need it, define an array like this:

countries:CountryData[] = [];

and subscribe to it like this:

this.countryService.getCountries().subscribe(countries => this.countries = countries);

A complete setup answer is posted here also.

Simple http post example in Objective-C?

ASIHTTPRequest makes network communication really easy

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];
[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];

Main differences between SOAP and RESTful web services in Java

SOAP

Simple Object Access Protocol (SOAP) is a standard, an XML language, defining a message architecture and message formats. It is used by Web services. It contains a description of the operations.

WSDL is an XML-based language for describing Web services and how to access them. It will run on SMTP, HTTP, FTP, etc. It requires middleware support and well-defined mechanism to define services like WSDL+XSD and WS-Policy. SOAP will return XML based data

REST

Representational State Transfer (RESTful) web services. They are second-generation Web services.

RESTful web services communicate via HTTP rather than SOAP-based services and do not require XML messages or WSDL service-API definitions. For REST middleware is not required, only HTTP support is needed. It is a WADL standard, REST can return XML, plain text, JSON, HTML, etc.

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

How to install plugins to Sublime Text 2 editor?

According to John Day's answer

You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.

In case if you are searching for Data/Packages folder you can find it here

Windows: %APPDATA%\Sublime Text 2

OS X: ~/Library/Application Support/Sublime Text 2

Linux: ~/.Sublime Text 2

Portable Installation: Sublime Text 2/Data

Can you use CSS to mirror/flip text?

You can user either

.your-class{ 
      position:absolute; 
      -moz-transform: scaleX(-1); 
      -o-transform: scaleX(-1); 
      -webkit-transform: scaleX(-1); 
      transform: scaleX(-1); 
      filter: FlipH;  
}

or

 .your-class{ 
  position:absolute;
  transform: rotate(360deg) scaleX(-1);
}

Notice that setting position to absolute is very important! If you won't set it, you will need to set display: inline-block;

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

How do I get data from a table?

in this code data is a two dimensional array of table data

let oTable = document.getElementById('datatable-id');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

Could not open ServletContext resource

Put the things like /src/main/resources/foo/bar.properties and then reference them as classpath:/foo/bar.properties.

How to copy data from one table to another new table in MySQL?

CREATE TABLE newTable LIKE oldTable;

Then, to copy the data over

INSERT INTO newTable SELECT * FROM oldTable;

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Simply :

$(".leaderMultiSelctdropdown").val()

How to reload page every 5 seconds?

setTimeout(function () { location.reload(1); }, 5000);

But as development tools go, you are probably better off with https://addons.mozilla.org/en-US/firefox/addon/115

What is the facade design pattern?

As explained in the previous answer it provides a simple interface to the consuming client. For example: "watch ESPN" is the intended function. But it involves several steps like:

  1. Switch on TV if required;
  2. Check for satellite/cable functioning;
  3. Switch to ESPN if required.

But the facade will simplify this and just provide "watch ESPN" function to the client.

How to find day of week in php in a specific timezone

"Day of Week" is actually something you can get directly from the php date() function with the format "l" or "N" respectively. Have a look at the manual

edit: Sorry I didn't read the posts of Kalium properly, he already explained that. My bad.

How to correct indentation in IntelliJ

Code ? Reformat Code... (default Ctrl + Alt + L) for the whole file or Code ? Auto-Indent Lines (default Ctrl + Alt + I) for the current line or selection.

You can customise the settings for how code is auto-formatted under File ? Settings ? Editor ? Code Style.


To ensure comments are also indented to the same level as the code, you can simply do as follows:

UI screenshot (example for JavaScript)

Removing body margin in CSS

This should help you get rid of body margins and default top margin of <h1> tag

body{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }