Programs & Examples On #Feature selection

In machine learning, this is the process of selecting a subset of most relevant features to construction your data model.

Warning: Cannot modify header information - headers already sent by ERROR

Check the document encoding.

I had this same problem. I develop on Windows XP using Notepad++ and WampServer to run Apache locally and all was fine. After uploading to hosting provider that uses Apache on Unix I got this error. I had no extra PHP tags or white-space from extra lines after the closing tag.

For me this was caused by the encoding of the text documents. I used the "Convert to UTF-8 without BOM" option in Notepad++(under Encoding tab) and reloaded to the web server. Problem fixed, no code/editing changes required.

Getting Java version at runtime

Runtime.version()

Since Java 9, you can use Runtime.version(), which returns a Runtime.Version:

Runtime.Version version = Runtime.version();

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

How to delete last character in a string in C#?

build it with string.Join instead:

var parameters = sl.SelProds.Select(x=>"productID="+x.prodID).ToArray();
paramstr = string.Join("&", parameters);

string.Join takes a seperator ("&") and and array of strings (parameters), and inserts the seperator between each element of the array.

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

*args and **kwargs: allow you to pass a variable number of arguments to a function.

*args: is used to send a non-keyworded variable length argument list to the function:

def args(normal_arg, *argv):
    print("normal argument:", normal_arg)

    for arg in argv:
        print("Argument in list of arguments from *argv:", arg)

args('animals', 'fish', 'duck', 'bird')

Will produce:

normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird

**kwargs*

**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.

def who(**kwargs):
    if kwargs is not None:
        for key, value in kwargs.items():
            print("Your %s is %s." % (key, value))

who(name="Nikola", last_name="Tesla", birthday="7.10.1856", birthplace="Croatia")  

Will produce:

Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.

Is there an "exists" function for jQuery?

this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:

jQuery.fn.exists = function(){return !!this.length};

if ($(selector).exists()) {
    // the element exists, now what?...
}

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

How to use onClick() or onSelect() on option tag in a JSP page?

In my case:

<html>
 <head>
  <script type="text/javascript">

    function changeFunction(val) {

       //Show option value
       console.log(val.value);
    }

  </script>
 </head>
 <body>
   <select id="selectBox" onchange="changeFunction(this)">
     <option value="1">Option #1</option>
     <option value="2">Option #2</option>
   </select>
 </body>
</html>

How to add new DataRow into DataTable?

try table.Rows.add(row); after your for statement.

Compare two files line by line and generate the difference in another file

If you need to solve this with coreutils the accepted answer is good:

comm -23 <(sort file1) <(sort file2) > file3

You can also use sd (stream diff), which doesn't require sorting nor process substitution and supports infinite streams, like so:

cat file1 | sd 'cat file2' > file3

Probably not that much of a benefit on this example, but still consider it; in some cases you won't be able to use comm nor grep -F nor diff.

Here's a blogpost I wrote about diffing streams on the terminal, which introduces sd.

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

force Maven to copy dependencies into target/lib

Try something like this:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
    <archive>
        <manifest>  
            <addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
            <mainClass>MainClass</mainClass>
        </manifest>
    </archive>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <id>copy</id>
            <phase>install</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>
                    ${project.build.directory}/lib
                </outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

UILabel Align Text to center

From iOS 6 and later UITextAlignment is deprecated. use NSTextAlignment

myLabel.textAlignment = NSTextAlignmentCenter;

Swift Version from iOS 6 and later

myLabel.textAlignment = .center

java: How can I do dynamic casting of a variable from one type to another?

Your problem is not the lack of "dynamic casting". Casting Integer to Double isn't possible at all. You seem to want to give Java an object of one type, a field of a possibly incompatible type, and have it somehow automatically figure out how to convert between the types.

This kind of thing is anathema to a strongly typed language like Java, and IMO for very good reasons.

What are you actually trying to do? All that use of reflection looks pretty fishy.

How to use C++ in Go

As of go1.2+, cgo automatically incorporates and compiles C++ code:

http://golang.org/doc/go1.2#cgo_and_cpp

Why can't I reference System.ComponentModel.DataAnnotations?

I found that I cannot reference System.ComponentModel.DataAnnotations from Silverlight 5 with the below version at (1). I found that Silverlight 5 assemblies cannot use .NET assemblies, it gives the error "You can't add a reference to System.ComponentModel.DataAnnotations as it was not built against the Silverlight runtime. ..." I plan to workaround this by hopefully installing the Silverlight 5 package found at (2) below. If this fails I will update this post.

[UPDATE: it failed. I installed everything relating to Silverlight 5 and I don't have the Silverlight version of the .dll assembly System.ComponentModel.DataAnnotations . Too bad. UPDATE II: I found an old .dll having this name from a previous installation of Silverlight developer's kit for Visual Studio 2008 or 2010. I added this file and it seems to 'work', in that IntelliSense is now recognizing attributes on class members, such as [Display(Name = "My Property Name")]. Whether or not this works for everything else in this .dll I don't know.]

(1)

Microsoft Visual Studio Professional 2013
Version 12.0.21005.1 REL
Microsoft .NET Framework
Version 4.5.51641

Installed Version: Professional

(2) http://go.microsoft.com/fwlink/?LinkId=229318

Remove trailing newline from the elements of a string list

my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
print([l.strip() for l in my_list])

Output:

['this', 'is', 'a', 'list', 'of', 'words']

How do I compare two Integers?

Compare integer and print its value in value ascending or descending order. All you have to do is implements Comparator interface and override its compare method and compare its value as below:

@Override
public int compare(Integer o1, Integer o2) {
    if (ascending) {
        return o1.intValue() - o2.intValue();
    } else {
        return o2.intValue() - o1.intValue();
    }

}

How to loop through array in jQuery?

  for(var key in substr)
{
     // do something with substr[key];

} 

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

Make sure the @angular/animations package is installed (e.g. by running npm install @angular/animations). Then, in your app.module.ts

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  ...,
  imports: [
    ...,
    BrowserAnimationsModule
  ],
  ...
})

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Doing the expicit casting to the "int" solves the problem in my case. I had the same issue. So:

int count = (int)[myColors count];

Changing datagridview cell color based on condition

Let's say you have to color certain cell (not all cells of the row) by knowing two things:

  1. Name or index of the column.
  2. Value which is gonna be inside of the cell.

In thas case you have to use event CellFormatting

In my case I use like this

private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
     foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
     {
       if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
       {
          row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
       }
       else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
       {
          // row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row

          row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
       }
     }
}

And result you can see here

enter image description here

So here you can access certain cell of the row in column by its name row.Cells["Decade1Hours"]

How do you know this name? Well in my case i create column of DataGridView like this.

var Decade1Hours = new DataGridViewTextBoxColumn()
{
   Name = "Decade1Hours",
   Width = 50,
   DataPropertyName = "Decade1Hours",
   ReadOnly = true,
   DefaultCellStyle = new DataGridViewCellStyle()
       {
        Alignment = DataGridViewContentAlignment.MiddleCenter,
        ForeColor = System.Drawing.Color.Black,
        Font = new Font(font, FontStyle.Bold),
        Format = "n2"
      },
   HeaderCell = new DataGridViewColumnHeaderCell()
      {
          Style = new DataGridViewCellStyle()
               {
                 Alignment = DataGridViewContentAlignment.MiddleCenter,
                 BackColor = System.Drawing.Color.Blue
               }
       }
};
Decade1Hours.HeaderText = "???.1";
dgvTrucksMaster.Columns.Add(Decade1Hours);

And well... you you need for instance colorize some of the cells in the row like ##1 4 5 and 8 you have to use cell index (it starts from 0).

And code will lok like

 private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
  {
    if (Convert.ToInt32(row.Cells[1].Value) > 0 )
    {
      row.Cells[1].Style.BackColor = Color.LightGreen;
    }
  }
}

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

The only thing you have to do is perform an yum update.

It will automatically download and update a backported version of openssl-1.0.1e-16.el6_5.7 which has been patched by RedHat with heartbeat disabled.

To verify the update simply check the changelog:
# rpm -q --changelog openssl-1.0.1e | grep -B 1 CVE-2014-0160
you should see the following:
* Mon Apr 07 2014 Tomáš Mráz <[email protected]> 1.0.1e-16.7 - fix CVE-2014-0160 - information disclosure in TLS heartbeat extension

Make sure you reboot the server because important services such as Apache and SSH use openSSL.

Generating Fibonacci Sequence

You Could Try This Fibonacci Solution Here

var a = 0;
console.log(a);
var b = 1;
console.log(b);
var c;
for (i = 0; i < 3; i++) {
  c = a + b;
  console.log(c);
  a = b + c;
  console.log(a);
  b = c + a;
  console.log(b);
}

Creating a list of pairs in java

You can use the Entry<U,V> class that HashMap uses but you'll be stuck with its semantics of getKey and getValue:

List<Entry<Float,Short>> pairList = //...

My preference would be to create your own simple Pair class:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

Then of course make a List using this new class, e.g.:

List<Pair<Float,Short>> pairList = new ArrayList<Pair<Float,Short>>();

You can also always make a Lists of Lists, but it becomes difficult to enforce sizing (that you have only pairs) and you would be required, as with arrays, to have consistent typing.

Get names of all files from a folder with Ruby

def get_path_content(dir)
  queue = Queue.new
  result = []
  queue << dir
  until queue.empty?
    current = queue.pop
    Dir.entries(current).each { |file|
      full_name = File.join(current, file)
      if not (File.directory? full_name)
        result << full_name
      elsif file != '.' and file != '..'
          queue << full_name
      end
    }
  end
  result
end

returns file's relative paths from directory and all subdirectories

How to get a string after a specific substring?

s1 = "hello python world , i'm a beginner "
s2 = "world"

print s1[s1.index(s2) + len(s2):]

If you want to deal with the case where s2 is not present in s1, then use s1.find(s2) as opposed to index. If the return value of that call is -1, then s2 is not in s1.

Executing a shell script from a PHP script

I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP.

e.g. /var/www/scripts/testscript

Make sure the user/group for your testscript is the same as your webfiles. For instance if your client.php is owned by apache:apache, change the bash script to the same user/group using chown. You can find out what your client.php and web files are owned by doing ls -al.

Then run

<?php
      $message=shell_exec("/var/www/scripts/testscript 2>&1");
      print_r($message);
    ?>  

EDIT:

If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do.

Execute root commands via PHP

How can I run multiple npm scripts in parallel?

You can use one & for parallel run script

"dev": "npm run start-watch & npm run wp-server"

Reference link

Merge (with squash) all changes from another branch as a single commit

Using git merge --squash <feature branch> as the accepted answer suggests does the trick but it will not show the merged branch as actually merged.

Therefore an even better solution is to:

  • Create a new branch from the latest master, commit in the master branch where the feature branch initiated.
  • Merge <feature branch> into the above using git merge --squash
  • Merge the newly created branch into master. This way, the feature branch will contain only one commit and the merge will be represented in a short and tidy illustration.

This wiki explains the procedure in detail.

In the following example, the left hand screenshot is the result of qgit and the right hand screenshot is the result of:

git log --graph --decorate --pretty=oneline --abbrev-commit

Both screenshots show the same range of commits in the same repository. Nonetheless, the right one is more compact thanks to --squash.

  • Over time, the master branch deviated from db.
  • When the db feature was ready, a new branch called tag was created in the same commit of master that db has its root.
  • From tag a git merge --squash db was performed and then all changes were staged and committed in a single commit.
  • From master, tag got merged: git merge tag.
  • The branch search is irrelevant and not merged in any way.

enter image description here

Mongod complains that there is no /data/db folder

I did

brew install mongodb

on 2018-02-01 and that gave me mongodb version 3.6.2.

Prompted by the answer from orluke above, I tried just

$ brew services restart mongodb

and everything sprang into life. My mongoose.createConnection() call did what I wanted. The GUI MongoDB Compass, the community version, would connect. I used Compass to look at the local.startup_log collection. That had one document in, the log of me just starting the mongoDB service, and that had

cmdLine:Object
    config:"/usr/local/etc/mongod.conf"

and indeed there was such a file:

$ more /usr/local/etc/mongod.conf
systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  bindIp: 127.0.0.1

and there was a /usr/local/var/mongodb directory with lots of obscure files. So that seems to be how the installation works now.

I'm not sure if brew services restart sets the service to run at login. So I did

brew services stop mongodb
brew services start mongodb

and hoped that starts it again after reboot. And, indeed, it did. In fact, now, I think the right thing to do after the initial installation is

brew services start mongodb

and that should start the service and restart it after reboot.

How to loop through Excel files and load them into a database using SSIS package?

I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here

Extract and convert all Excel worksheets into CSV files using PowerShell

is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.

Once the Excel files have been converted to CSV the data import is much less complicated.

HTML Display Current date

var currentDate  = new Date(),
    currentDay   = currentDate.getDate() < 10 
                 ? '0' + currentDate.getDate() 
                 : currentDate.getDate(),
    currentMonth = currentDate.getMonth() < 9 
                 ? '0' + (currentDate.getMonth() + 1) 
                 : (currentDate.getMonth() + 1);

document.getElementById("date").innerHTML = currentDay + '/' + currentMonth + '/' +  currentDate.getFullYear();

You can read more about Date object

How to get param from url in angular 4?

import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap
    .subscribe( params => {
    let id = +params.get('id');
    console.log('id' + id);
    console.log(params);


id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
        }
        )

      }

Vector of Vectors to create matrix

You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:

// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));

This creates a vector of RR size CC vectors, filled with 0.

How to change font size on part of the page in LaTeX?

Example:

\Large\begin{verbatim}
   <how to set font size here to 10 px ? />
\end{verbatim}
\normalsize

\Large can be obviously substituted by one of:

\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge

If you need arbitrary font sizes:

Laravel 5.4 Specific Table Migration

Specific Table Migration

php artisan migrate --path=/database/migrations/fileName.php

Parsing JSON from URL

public static TargetClassJson downloadPaletteJson(String url) throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String genreJson = IOUtils.toString(new URL(url).openStream());
        return new Gson().fromJson(genreJson, TargetClassJson.class);
    }

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

adding 1 day to a DATETIME format value

You can use

$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

select right(rtrim('94342KMR'),3)

This will fetch the last 3 right string.

select substring(rtrim('94342KMR'),1,len('94342KMR')-3)

This will fetch the remaining Characters.

Java - JPA - @Version annotation

But still I am not sure how it works?

Let's say an entity MyEntity has an annotated version property:

@Entity
public class MyEntity implements Serializable {    

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @Version
    private Long version;

    //...
}

On update, the field annotated with @Version will be incremented and added to the WHERE clause, something like this:

UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))

If the WHERE clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an OptimisticLockException.

Does it mean that we should declare our version field as final

No but you could consider making the setter protected as you're not supposed to call it.

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

Only mkdir if it does not exist

Try using this:-

mkdir -p dir;

NOTE:- This will also create any intermediate directories that don't exist; for instance,

Check out mkdir -p

or try this:-

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$Message" 1>&2
fi

Slide div left/right using jQuery

You can easy get that effect without using jQueryUI, for example:

$(document).ready(function(){
    $('#slide').click(function(){
    var hidden = $('.hidden');
    if (hidden.hasClass('visible')){
        hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
    } else {
        hidden.animate({"left":"0px"}, "slow").addClass('visible');
    }
    });
});

Try this working Fiddle:

http://jsfiddle.net/ZQTFq/

Getting Class type from String

Not sure what you are asking, but... Class.forname, maybe?

Setting width of spreadsheet cell using PHPExcel

autoSize for column width set as bellow. It works for me.

$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);

Get a substring of a char*

Assuming you know the position and the length of the substring:

char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

This is a good example of avoiding unnecessary copying by using pointers.

How to check if a scope variable is undefined in AngularJS template?

Corrected:

HTML

  <p ng-show="getFooUndef(foo)">Show this if $scope.foo === undefined</p>

JS

$scope.foo = undefined;

$scope.getFooUndef = function(foo){
    return ( typeof foo === 'undefined' );
}

Fiddle: http://jsfiddle.net/oakley349/vtcff0w5/1/

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

How to add Drop-Down list (<select>) programmatically?

const countryResolver = (data = [{}]) => {
    const countrySelecter = document.createElement('select');
    countrySelecter.className = `custom-select`;
    countrySelecter.id = `countrySelect`;
    countrySelecter.setAttribute("aria-label", "Example select with button addon");

    let opt = document.createElement("option");
    opt.text = "Select language";
    opt.disabled = true;
    countrySelecter.add(opt, null);
    let i = 0;
    for (let item of data) {
        let opt = document.createElement("option");
        opt.value = item.Id;
        opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
        countrySelecter.add(opt, null);
    }
    return countrySelecter;
};

What is java pojo class, java bean, normal class?

  1. Normal Class: A Java class

  2. Java Beans:

    • All properties private (use getters/setters)
    • A public no-argument constructor
    • Implements Serializable.
  3. Pojo: Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

    • Extend prespecified classes
    • Implement prespecified interface
    • Contain prespecified annotations

Can't Autowire @Repository annotated interface in Spring Boot

To extend onto above answers, You can actually add more than one package in your EnableJPARepositories tag, so that you won't run into "Object not mapped" error after only specifying the repository package.

@SpringBootApplication
@EnableJpaRepositories(basePackages = {"com.test.model", "com.test.repository"})
public class SpringBootApplication{

}

Convert Pandas Column to DateTime

You can use the DataFrame method .apply() to operate on the values in Mycol:

>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
                    Mycol
0  05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                    dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
       Mycol
0 2014-09-05

How to solve "The specified service has been marked for deletion" error

Discovered one more thing to check - look in Task manager - if other users are connected to this box, even if they are 'disconnected' you have to actually sign them out to get the service to finally delete.

How do I generate random numbers in Dart?

For me the easiest way is to do:

import 'dart:math';
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//where min and max should be specified.

Thanks to @adam-singer explanation in here.

Find an object in array?

Swift 3

If you need the object use:

array.first{$0.name == "Foo"}

(If you have more than one object named "Foo" then first will return the first object from an unspecified ordering)

Can't draw Histogram, 'x' must be numeric

Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:

 we <- gsub(",", "", we)   # remove comma
 we <- as.numeric(we)      # turn into numbers

and now you can do

 hist(we)

and other numeric operations.

How to make modal dialog in WPF?

Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.

Java - Opposite of .contains (does not contain)

Maybe

if (inventory.contains("bread") && !inventory.contains("water"))

Or

if (inventory.contains("bread")) {
    if (!inventory.contains("water")) {
        // do something here
    } 
}

Is there a reason for C#'s reuse of the variable in a foreach?

Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:

foreach (var s in strings)
    query = query.Where(i => i.Prop == s); // access to modified closure

I do:

foreach (var s in strings)
{
    string search = s;
    query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}        

Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

Displaying a webcam feed using OpenCV and Python

An update to show how to do it in the recent versions of OpenCV:

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break

cv2.destroyWindow("preview")
vc.release()

It works in OpenCV-2.4.2 for me.

No connection could be made because the target machine actively refused it (PHP / WAMP)

In my case i did the following and worked for me

  1. I clicked on the wamp icon.
  2. i went to MySQL > Service administration 'wampmysqld64' > install service
  3. Then click on wamp icon > Restart all service.

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

React js onClick can't pass value to method

I guess you will have to bind the method to the React’s class instance. It’s safer to use a constructor to bind all methods in React. In your case when you pass the parameter to the method, the first parameter is used to bind the ‘this’ context of the method, thus you cannot access the value inside the method.

Twitter Bootstrap carousel different height images cause bouncing arrows

In case someone is feverishly googling to solve the bouncing images carousel thing, this helped me:

.fusion-carousel .fusion-carousel-item img {
    width: auto;
    height: 146px;
    max-height: 146px;
    object-fit: contain;
}

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Calculate mean and standard deviation from a vector of samples in C++ using Boost

2x faster than the versions before mentioned - mostly because transform() and inner_product() loops are joined. Sorry about my shortcut/typedefs/macro: Flo = float. CR const ref. VFlo - vector. Tested in VS2010

#define fe(EL, CONTAINER)   for each (auto EL in CONTAINER)  //VS2010
Flo stdDev(VFlo CR crVec) {
    SZ  n = crVec.size();               if (n < 2) return 0.0f;
    Flo fSqSum = 0.0f, fSum = 0.0f;
    fe(f, crVec) fSqSum += f * f;       // EDIT: was Cit(VFlo, crVec) {
    fe(f, crVec) fSum   += f;
    Flo fSumSq      = fSum * fSum;
    Flo fSumSqDivN  = fSumSq / n;
    Flo fSubSqSum   = fSqSum - fSumSqDivN;
    Flo fPreSqrt    = fSubSqSum / (n - 1);
    return sqrt(fPreSqrt);
}

Are there any disadvantages to always using nvarchar(MAX)?

It's a fair question and he did state apart from the obvious…

Disadvantages could include:

Performance implications Query optimizer uses field size to determine most efficent exectution plan

"1. The space alloction in extends and pages of the database are flexible. Thus when adding information to the field using update, your database would have to create a pointer if the new data is longer than the previous inserted. This the database files would become fragmented = lower performance in almost everything, from index to delete, update and inserts. " http://sqlblogcasts.com/blogs/simons/archive/2006/02/28/Why-use-anything-but-varchar_2800_max_2900_.aspx

Integration implications - hard for other systems to know how to integrate with your database Unpredictable growth of data Possible security issues e.g. you could crash a system by taking up all disk space

There is good article here: http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1098157,00.html

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

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

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

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

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

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

What is the bower (and npm) version syntax?

Based on semver, you can use

  • Hyphen Ranges X.Y.Z - A.B.C 1.2.3-2.3.4 Indicates >=1.2.3 <=2.3.4

  • X-Ranges 1.2.x 1.X 1.2.*

  • Tilde Ranges ~1.2.3 ~1.2 Indicates allowing patch-level changes or minor version changes.

  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

    Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple

    • ^1.2.x (means >=1.2.0 <2.0.0)
    • ^0.0.x (means >=0.0.0 <0.1.0)
    • ^0.0 (means >=0.0.0 <0.1.0)

How can I save a screenshot directly to a file in Windows?

Might I suggest WinSnap http://www.ntwind.com/software/winsnap/download-free-version.html. It provides an autosave option and capture the alt+printscreen and other key combinations to capture screen, windows, dialog, etc.

What can I use for good quality code coverage for C#/.NET?

TestMatrix is a unit test runner and code coverage tool.

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

You won't be able to restore from 2012 to 2008. You will be able to use a tool like red-gate SQL compare to copy the schema etc (provided nothing 2012 specific is used). If you have data to copy across too, you can use their Data Compare tool, and I think you get a 14 day free trial.

Plotting images side by side using matplotlib

As per matplotlib's suggestion for image grids:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, image_data):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()

Generate an integer that is not among four billion given ones

You could speed up finding the missing integers after reading the existing ones by storing ranges of unvisited integers in some tree structure.

You'd start by storing [0..4294967295] and every time you read an integer you splice the range it falls in, deleting a range when it becomes empty. At the end you have the exact set of integers that are missing in the ranges. So if you see 5 as the first integer, you'd have [0..4] and [6..4294967295].

This is a lot slower than marking bits so it would only be a solution for the 10MB case provided you can store the lower levels of the tree in files.

One way to store such a tree would be a B-tree with the start of the range as the key and the end of the range as the value. Worst case usage would be when you get all odd or even integers which would mean storing 2^31 values or tens of GB for the tree... Ouch. Best case is a sorted file where you'd only use a few integers for the whole tree.

So not really the correct answer but I thought I'd mention this way of doing it. I suppose I'd fail the interview ;-)

Free ASP.Net and/or CSS Themes

As always, http://www.csszengarden.com/. Note that the images aren't public domain.

How to select records without duplicate on just one field in SQL?

Try this one

SELECT country_id, country_title 
FROM (SELECT country_id, country_title,
CASE
WHEN country_title=LAG(country_title, 1, 0) OVER(ORDER BY country_title) THEN 1
ELSE 0
END AS "Duplicates"
FROM tbl_countries)
WHERE "Duplicates"=0;

Converting String to Double in Android

try this:

double d= Double.parseDouble(yourString);

Is there any sizeof-like method in Java?

I don't think it is in the java API. but most datatypes which have a number of elements in it, have a size() method. I think you can easily write a function to check for size yourself?

What's the use of "enum" in Java?

1) enum is a keyword in Object oriented method.

2) It is used to write the code in a Single line, That's it not more than that.

     public class NAME
     {
        public static final String THUNNE = "";
        public static final String SHAATA = ""; 
        public static final String THULLU = ""; 
     }

-------This can be replaced by--------

  enum NAME{THUNNE, SHAATA, THULLU}

3) Most of the developers do not use enum keyword, it is just a alternative method..

How to fix 'Microsoft Excel cannot open or save any more documents'

I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.

Way 01:

Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.

Way 02:

This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.

How to render a DateTime object in a Twig template

Dont forget

@ORM\HasLifecycleCallbacks()

Entity :

/**
     * Set gameDate
     *
     * @ORM\PrePersist
     */
    public function setGameDate()
    {
        $this->dateCreated = new \DateTime();

        return $this;
    }

View:

{{ item.gameDate|date('Y-m-d H:i:s') }}

>> Output 2013-09-18 16:14:20

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Nicer code for this:

yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);

Converting string "true" / "false" to boolean value

You could simply have: var result = (str == "true").

AttributeError: 'module' object has no attribute 'urlretrieve'

As you're using Python 3, there is no urllib module anymore. It has been split into several modules.

This would be equivalent to urlretrieve:

import urllib.request
data = urllib.request.urlretrieve("http://...")

urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.

Basically:

  • urlretrieve saves the file to a temporary file and returns a tuple (filename, headers)
  • urlopen returns a Request object whose read method returns a bytestring containing the file contents

How do I trim whitespace from a string?

Just one space or all consecutive spaces? If the second, then strings already have a .strip() method:

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'

If you only need to remove one space however, you could do it with:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'

Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:

>>> "  Hello\n".strip(" ")
'Hello\n'

How to get the server path to the web directory in Symfony2 from inside the controller?

For Symfony3 In your controller try

$request->server->get('DOCUMENT_ROOT').$request->getBasePath()

Converting a double to an int in Javascript without rounding

Similar to C# casting to (int) with just using standard lib:

Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1

What version of Java is running in Eclipse?

try this :

public class vm
{
  public static void main(String[] args)
  {
      System.getProperty("sun.arch.data.model") 
  }
}

compile and run. it will return either 32 or 64 as per your java version . . .

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.

Can anyone explain python's relative imports?

You are importing from package "sub". start.py is not itself in a package even if there is a __init__.py present.

You would need to start your program from one directory over parent.py:

./start.py

./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py

With start.py:

import pkg.sub.relative

Now pkg is the top level package and your relative import should work.


If you want to stick with your current layout you can just use import parent. Because you use start.py to launch your interpreter, the directory where start.py is located is in your python path. parent.py lives there as a separate module.

You can also safely delete the top level __init__.py, if you don't import anything into a script further up the directory tree.

PHP - warning - Undefined property: stdClass - fix?

If think this will work:

if(sizeof($response->records)>0)
$role_arr = getRole($response->records);

newly defined proprties included too.

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

jQuery function to get all unique elements from an array?

If you need to support IE 8 or earlier, you can use jQuery to accomplish this.

var a = [1,2,2,3,4,3,5];
var unique = $.grep(a, function (item, index) {
   return index === $.inArray(item, a);
});

Wrapping text inside input type="text" element HTML/CSS

To create a text input in which the value under the hood is a single line string but is presented to the user in a word-wrapped format you can use the contenteditable attribute on a <div> or other element:

_x000D_
_x000D_
const el = document.querySelector('div[contenteditable]');_x000D_
_x000D_
// Get value from element on input events_x000D_
el.addEventListener('input', () => console.log(el.textContent));_x000D_
_x000D_
// Set some value_x000D_
el.textContent = 'Lorem ipsum curae magna venenatis mattis, purus luctus cubilia quisque in et, leo enim aliquam consequat.'
_x000D_
div[contenteditable] {_x000D_
  border: 1px solid black;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div contenteditable></div>
_x000D_
_x000D_
_x000D_

Check if space is in a string

You can try this, and if it will find any space it will return the position where the first space is.

if mystring.find(' ') != -1:
    print True
else:
    print False

How do I make a simple makefile for gcc on Linux?

Interesting, I didn't know make would default to using the C compiler given rules regarding source files.

Anyway, a simple solution that demonstrates simple Makefile concepts would be:

HEADERS = program.h headers.h

default: program

program.o: program.c $(HEADERS)
    gcc -c program.c -o program.o

program: program.o
    gcc program.o -o program

clean:
    -rm -f program.o
    -rm -f program

(bear in mind that make requires tab instead of space indentation, so be sure to fix that when copying)

However, to support more C files, you'd have to make new rules for each of them. Thus, to improve:

HEADERS = program.h headers.h
OBJECTS = program.o

default: program

%.o: %.c $(HEADERS)
    gcc -c $< -o $@

program: $(OBJECTS)
    gcc $(OBJECTS) -o $@

clean:
    -rm -f $(OBJECTS)
    -rm -f program

I tried to make this as simple as possible by omitting variables like $(CC) and $(CFLAGS) that are usually seen in makefiles. If you're interested in figuring that out, I hope I've given you a good start on that.

Here's the Makefile I like to use for C source. Feel free to use it:

TARGET = prog
LIBS = -lm
CC = gcc
CFLAGS = -g -Wall

.PHONY: default all clean

default: $(TARGET)
all: default

OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)

%.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@

.PRECIOUS: $(TARGET) $(OBJECTS)

$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -Wall $(LIBS) -o $@

clean:
    -rm -f *.o
    -rm -f $(TARGET)

It uses the wildcard and patsubst features of the make utility to automatically include .c and .h files in the current directory, meaning when you add new code files to your directory, you won't have to update the Makefile. However, if you want to change the name of the generated executable, libraries, or compiler flags, you can just modify the variables.

In either case, don't use autoconf, please. I'm begging you! :)

Can the :not() pseudo-class have multiple arguments?

I was having some trouble with this, and the "X:not():not()" method wasn't working for me.

I ended up resorting to this strategy:

INPUT {
    /* styles */
}
INPUT[type="radio"], INPUT[type="checkbox"] {
    /* styles that reset previous styles */
}

It's not nearly as fun, but it worked for me when :not() was being pugnacious. It's not ideal, but it's solid.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

The reason for the error is the same origin policy. It only allows you to do XMLHTTPRequests to your own domain. See if you can use a JSONP callback instead:

$.getJSON( 'http://<url>/api.php?callback=?', function ( data ) { alert ( data ); } );

How to embed YouTube videos in PHP?

This YouTube embed generator solve all my problems with video embedding.

How do I make Java register a string input with spaces?

Instead of

Scanner in = new Scanner(System.in);
String question;
question = in.next();

Type in

Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();

This should be able to take spaces as input.

Django CSRF Cookie Not Set

try to check if your have installed in the settings.py

 MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',)

In the template the data are formatted with the csrf_token:

<form>{% csrf_token %}
</form>

SQL Switch/Case in 'where' clause

Case Statement in SQL Server Example

Syntax

CASE [ expression ]

   WHEN condition_1 THEN result_1
   WHEN condition_2 THEN result_2
   ...
   WHEN condition_n THEN result_n

   ELSE result

END

Example

SELECT contact_id,
CASE website_id
  WHEN 1 THEN 'TechOnTheNet.com'
  WHEN 2 THEN 'CheckYourMath.com'
  ELSE 'BigActivities.com'
END
FROM contacts;

OR

SELECT contact_id,
CASE
  WHEN website_id = 1 THEN 'TechOnTheNet.com'
  WHEN website_id = 2 THEN 'CheckYourMath.com'
  ELSE 'BigActivities.com'
END
FROM contacts;

How to create a jQuery function (a new jQuery method or plugin)?

Create a "colorize" method:

$.fn.colorize = function custom_colorize(some_color) {
    this.css('color', some_color);
    return this;
}

Use it:

$('#my_div').colorize('green');

This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from @Candide, @Michael.

webpack command not working

Installing webpack with -g option installs webpack in a folder in

C:\Users\<.profileusername.>\AppData\Roaming\npm\node_modules

same with webpack-cli and webpack-dev-server

Outside the global node_modules a link is created for webpack to be run from commandline

C:\Users\<.profileusername.>\AppData\Roaming\npm

to make this work locally, I did the following

  1. renamed the webpack folder in global node_modules to _old
  2. installed webpack locally within project
  3. edited the command link webpack.cmd and pointed the webpack.js to look into my local node_modules folder within my application

Problem with this approach is you'd have to maintain links for each project you have. Theres no other way since you are using the command line editor to run webpack command when installing with a -g option.

So if you had proj1, proj2 and proj3 all with their local node_modules and local webpack installed( not using -g when installing), then you'd have to create non-generic link names instead of just webpack.

example here would be to create webpack_proj1.cmd, webpack_proj2.cmd and webpack_proj3.cmd and in each cmd follow point 2 and 3 above

PS: dont forget to update your package.json with these changes or else you'll get errors as it won't find webpack command

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

if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.

class method generates "TypeError: ... got multiple values for keyword argument ..."

just add 'staticmethod' decorator to function and problem is fixed

class foo(object):
    @staticmethod
    def foodo(thing=None, thong='not underwear'):
        print thing if thing else "nothing" 
        print 'a thong is',thong

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

If you keep grabbing bits from your data, you might want to use a bitfield. You'll just have to set up a struct and load it with only ones and zeroes:

struct bitfield{
    unsigned int bit : 1
}
struct bitfield *bitstream;

then later on load it like this (replacing char with int or whatever data you are loading):

long int i;
int j, k;
unsigned char c, d;

bitstream=malloc(sizeof(struct bitfield)*charstreamlength*sizeof(char));
for (i=0; i<charstreamlength; i++){
    c=charstream[i];
    for(j=0; j < sizeof(char)*8; j++){
        d=c;
        d=d>>(sizeof(char)*8-j-1);
        d=d<<(sizeof(char)*8-1);
        k=d;
        if(k==0){
            bitstream[sizeof(char)*8*i + j].bit=0;
        }else{
            bitstream[sizeof(char)*8*i + j].bit=1;
        }
    }
}

Then access elements:

bitstream[bitpointer].bit=...

or

...=bitstream[bitpointer].bit

All of this is assuming are working on i86/64, not arm, since arm can be big or little endian.

How to open a specific port such as 9090 in Google Compute Engine

You'll need to add a firewall rule to open inbound access to tcp:9090 to your instances. If you have more than the two instances, and you only want to open 9090 to those two, you'll want to make sure that there is a tag that those two instances share. You can add or update tags via the console or the command-line; I'd recommend using the GUI for that if needed because it handles the read-modify-write cycle with setinstancetags.

If you want to open port 9090 to all instances, you can create a firewall rule like:

gcutil addfirewall allow-9090 --allowed=tcp:9090

which will apply to all of your instances.

If you only want to open port 9090 to the two instances that are serving your application, make sure that they have a tag like my-app, and then add a firewall like so:

gcutil addfirewall my-app-9090 --allowed=tcp:9090 --target_tags=my-app

You can read more about creating and managing firewalls in GCE here.

Storing Images in PostgreSQL

Re jcoby's answer:

bytea being a "normal" column also means the value being read completely into memory when you fetch it. Blobs, in contrast, you can stream into stdout. That helps in reducing the server memory footprint. Especially, when you store 4-6 MPix images.

No problem with backing up blobs. pg_dump provides "-b" option to include the large objects into the backup.

So, I prefer using pg_lo_*, you may guess.

Re Kris Erickson's answer:

I'd say the opposite :). When images are not the only data you store, don't store them on the file system unless you absolutely have to. It's such a benefit to be always sure about your data consistency, and to have the data "in one piece" (the DB). BTW, PostgreSQL is great in preserving consistency.

However, true, reality is often too performance-demanding ;-), and it pushes you to serve the binary files from the file system. But even then I tend to use the DB as the "master" storage for binaries, with all the other relations consistently linked, while providing some file system-based caching mechanism for performance optimization.

How to check if an element does NOT have a specific class?

Select element (or group of elements) having class "abc", not having class "xyz":

    $('.abc:not(".xyz")')

When selecting regular CSS you can use .abc:not(.xyz).

how to git commit a whole folder?

To Add a little to the above answers:

If you are wanting to commit a folder like the above

git add foldername
git commit -m "commit operation"

To add the folder you will need to be on the same level as, or above, the folder you are trying to add.

For example: App/Storage/Emails/email.php

If you are trying to add the "Storage" file but you have been working inside it on the email.php document you will not be able to add the "Storage" file unless you have 'changed directory' (cd ../) back up to the same level, or higher, as the Storage file itself

How do I properly force a Git push?

I had the same question but figured it out finally. What you most likely need to do is run the following two git commands (replacing hash with the git commit revision number):

git checkout <hash>
git push -f HEAD:master

How to find a value in an array of objects in JavaScript?

If You want to find a specific object via search function just try something like this:

    function findArray(value){

        let countLayer = dataLayer.length;
        for(var x = 0 ; x < countLayer ; x++){

            if(dataLayer[x].user){
                let newArr = dataLayer[x].user;
                let data = newArr[value];
                return data;
            }

        }

        return null;

    }

    findArray("id");

This is an example object:

layerObj = {
    0: { gtm.start :1232542, event: "gtm.js"},
    1: { event: "gtm.dom", gtm.uniqueEventId: 52},
    2: { visitor id: "abcdef2345"},
    3: { user: { id: "29857239", verified: "Null", user_profile: "Personal", billing_subscription: "True", partners_user: "adobe"}
}

Code will iterate and find the "user" array and will search for the object You seek inside.

My problem was when the array index changed every window refresh and it was either in 3rd or second array, but it does not matter.

Worked like a charm for Me!

In Your example it is a bit shorter:

function findArray(value){

    let countLayer = Object.length;
    for(var x = 0 ; x < countLayer ; x++){

        if(Object[x].dinner === value){
            return Object[x];
        }

    }

    return null;

}

findArray('sushi');

How can I pad a String in Java?

You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.

(Hint: For extra credit, make it thread-safe! ;-)

Is it possible to specify a different ssh port when using rsync?

when you need to send files through a specific SSH port:

rsync -azP -e "ssh -p PORT_NUMBER" source destination

example

rsync -azP -e "ssh -p 2121" /path/to/files/source user@remoteip:/path/to/files/destination

Align div with fixed position on the right side

You can use two imbricated div. But you need a fixed width for your content, that's the only limitation.

<div style='float:right; width: 180px;'>
 <div style='position: fixed'>
   <!-- Your content -->
 </div>
</div>

What does "var" mean in C#?

It means the data type is derived (implied) from the context.

From http://msdn.microsoft.com/en-us/library/bb383973.aspx

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

var is useful for eliminating keyboard typing and visual noise, e.g.,

MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();

becomes

var x = new MyReallyReallyLongClassName();

but can be overused to the point where readability is sacrificed.

Extract part of a regex match

re.search('<title>(.*)</title>', s, re.IGNORECASE).group(1)

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

Counting repeated elements in an integer array

with O(n log(n))

int[] arr1; // your given array
int[] arr2 = new int[arr1.length];
Arrays.sort(arr1);

for (int i = 0; i < arr1.length; i++) {
    arr2[i]++;
    if (i+1 < arr1.length) 
    {
        if (arr1[i] == arr1[i + 1]) {
            arr2[i]++;
            i++;
        }
    }
}

for (int i = 0; i < arr1.length; i++) {
    if(arr2[i]>0)
    System.out.println(arr1[i] + ":" + arr2[i]);
}

Installing Python packages from local file system folder to virtualenv with pip

What about::

pip install --help
...
  -e, --editable <path/url>   Install a project in editable mode (i.e. setuptools
                              "develop mode") from a local project path or a VCS url.

eg, pip install -e /srv/pkg

where /srv/pkg is the top-level directory where 'setup.py' can be found.

How should I unit test multithreaded code?

Awaitility can also be useful to help you write deterministic unit tests. It allows you to wait until some state somewhere in your system is updated. For example:

await().untilCall( to(myService).myMethod(), greaterThan(3) );

or

await().atMost(5,SECONDS).until(fieldIn(myObject).ofType(int.class), equalTo(1));

It also has Scala and Groovy support.

await until { something() > 4 } // Scala example

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.

query user /server:$SERVER

Best way to get application folder path

Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:

Application.StartupPath

returns the StartupPath parameter (can be set when run the application)

System.IO.Directory.GetCurrentDirectory()

returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

PYTHONPATH on Linux

PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

Serialize object to query string in JavaScript/jQuery

Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.

For example:

var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

The other answers gave me the right clues, but they didn't completely help.

Here's what worked for me:

$ git checkout email
$ git tag old-email-branch # This is optional
$ git reset --hard staging
$
$ # Using a custom commit message for the merge below
$ git merge -m 'Merge -s our where _ours_ is the branch staging' -s ours origin/email
$ git push origin email

Without the fourth step of merging with the ours strategy, the push is considered a non-fast-forward update and will be rejected (by GitHub).

wget: unable to resolve host address `http'

remove the http or https from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip . this worked fine for me.

Typescript es6 import module "File is not a module error"

In addition to Tim's answer, this issue occurred for me when I was splitting up a refactoring a file, splitting it up into their own files.

VSCode, for some reason, indented parts of my [class] code, which caused this issue. This was hard to notice at first, but after I realised the code was indented, I formatted the code and the issue disappeared.

for example, everything after the first line of the Class definition was auto-indented during the paste.

export class MyClass extends Something<string> {
    public blah: string = null;

    constructor() { ... }
  }

How can I query for null values in entity framework?

var result = from entry in table
             where entry.something.Equals(null)
             select entry;

MSDN Reference: LINQ to SQL: .NET Language-Integrated Query for Relational Data

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

I got the same issue, unable to start the application once it is deployed in tomcat. But, once I copy the Struts set of jars into CATALINA_HOME\lib (Tomcat dir) directory it is resolved. You don't need to have these jars in your WEB_INF\lib but you need to have them in your Build Path.

commons-fileupload-1.2.1.jar

commons-io-1.3.2.jar

freemarker-2.3.16.jar

javassist-3.11.0.GA.jar

struts2-convention-plugin-2.2.1.jar

struts2-core-2.2.1.jar

xwork-core-2.2.1.jar

How to convert color code into media.brush?

For WinRT (Windows Store App)

using Windows.UI;
using Windows.UI.Xaml.Media;

    public static Brush ColorToBrush(string color) // color = "#E7E44D"
    {
        color = color.Replace("#", "");
        if (color.Length == 6)
        {
            return new SolidColorBrush(ColorHelper.FromArgb(255,
                byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
        }
        else
        {
            return null;
        }
    }

npm install private github repositories by dependency in package.json

"dependencies": {
  "some-package": "github:github_username/some-package"
}

or just

"dependencies": {
  "some-package": "github_username/some-package"
}

https://docs.npmjs.com/files/package.json#github-urls

How to loop through all but the last item of a list?

the easiest way to compare the sequence item with the following:

for i, j in zip(a, a[1:]):
     # compare i (the current) to j (the following)

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

This usually occurs when the master.mdf or the mastlog.ldf gets corrupt . In order to solve the issue goto the following path C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL , there you will find a folder ” Template Data ” , copy the master.mdf and mastlog.ldf and replace it in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Data folder . Thats it . Now start the MS SQL service and you are done

How do I edit $PATH (.bash_profile) on OSX?

Determine which shell you're using by typing echo $SHELL in Terminal.

Then open/create correct rc file. For Bash it's $HOME/.bash_profile or $HOME/.bashrc. For Z shell it's $HOME/.zshrc.

Add this line to the file end:

export PATH="$PATH:/your/new/path"

To verify, refresh variables by restarting Terminal or typing source $HOME/.<rc file> and then do echo $PATH

Should I make HTML Anchors with 'name' or 'id'?

ID method will not work on older browsers, anchor name method will be deprecated in newer HTML versions... I'd go with id.

CardView not showing Shadow in Android L

You can try by adding this line

 card_view:cardUseCompatPadding="true"

The Whole code will seems like this

  <android.support.v7.widget.CardView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="5dp"
        android:orientation="horizontal"
        card_view:cardUseCompatPadding="true"
        card_view:cardCornerRadius="5dp">
 </android.support.v7.widget.CardView

Apply function to each column in a data frame observing each columns existing data type

If you want to learn your data summary (df) provides the min, 1st quantile, median and mean, 3rd quantile and max of numerical columns and the frequency of the top levels of the factor columns.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

With JDBC, that error usually occurs because your JDBC driver implements an older version of the JDBC API than the one included in your JRE. These older versions are fine so long as you don't try and use a method that appeared in the newer API.

I'm not sure what version of JDBC setBinaryStream appeared in. It's been around for a while, I think.

Regardless, your JDBC driver version (10.2.0.4.0) is quite old, I recommend upgrading it to the version that was released with 11g (download here), and try again.

what is right way to do API call in react js?

It would be great to use axios for the api request which supports cancellation, interceptors etc. Along with axios, l use react-redux for state management and redux-saga/redux-thunk for the side effects.

Python: No acceptable C compiler found in $PATH when installing python

You would need to install it as non root, since its shared hosting. Here is a tut that points how this step. http://luiarthur.github.io/gccinstall

cd ~/src
wget http://www.netgull.com/gcc/releases/gcc-5.2.0/gcc-5.2.0.tar.gz

or equivalent gcc source, then

tar -xvf gcc-5.2.0.tar.gz
cd gcc-5.2.0
./contrib/download_prerequisites
cd ..
mkdir objdir
cd objdir
$PWD/../gcc-5.2.0/configure --prefix=$HOME/gcc-5.2.0 --enable-languages=c,c++,fortran,go
make
make install

then add to .bashrc, or equivalent

export PATH=~/gcc-5.2.0/bin:$PATH
export LD_LIBRARY_PATH=~/gcc-5.2.0/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=~/gcc-5.2.0/lib64:$LD_LIBRARY_PATH

Changing the text on a label

Use the config method to change the value of the label:

top = Tk()

l = Label(top)
l.pack()

l.config(text = "Hello World", width = "50")

Not able to pip install pickle in python 3.6

$ pip install pickle5
import pickle5 as pickle

pb = pickle.PickleBuffer(b"foo")
data = pickle.dumps(pb, protocol=5)
assert pickle.loads(data) == b"foo"

This package backports all features and APIs added in the pickle module in Python 3.8.3, including the PEP 574 additions. It should work with Python 3.5, 3.6 and 3.7.

Basic usage is similar to the pickle module, except that the module to be imported is pickle5:

https://pypi.org/project/pickle5/

Java Delegates?

Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.

Instead of a line like this declaring a named method signature:

// C#
public delegate void SomeFunction();

declare an interface:

// Java
public interface ISomeBehaviour {
   void SomeFunction();
}

For concrete implementations of the method, define a class that implements the behaviour:

// Java
public class TypeABehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeA behaviour
   }
}

public class TypeBBehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeB behaviour
   }
}

Then wherever you would have had a SomeFunction delegate in C#, use an ISomeBehaviour reference instead:

// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();

// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();

With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.

// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
   ...
}

...

SomeMethod(new ISomeBehaviour() { 
   @Override
   public void SomeFunction() {
      // your implementation
   }
});

This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.

And then of course in Java 8, these do become basically lambda expressions:

// Java 8
SomeMethod(() -> { /* your implementation */ });

Origin http://localhost is not allowed by Access-Control-Allow-Origin

This approach resolved my issue to allow multiple domain

app.use(function(req, res, next) {
      var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });

How do I update a Mongo document after inserting it?

This is an old question, but I stumbled onto this when looking for the answer so I wanted to give the update to the answer for reference.

The methods save and update are deprecated.

save(to_save, manipulate=True, check_keys=True, **kwargs)¶ Save a document in this collection.

DEPRECATED - Use insert_one() or replace_one() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

update(spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs) Update a document(s) in this collection.

DEPRECATED - Use replace_one(), update_one(), or update_many() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

in the OPs particular case, it's better to use replace_one.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

How to filter multiple values (OR operation) in angularJS

you can use searchField filter of angular.filter

JS:

$scope.users = [
 { first_name: 'Sharon', last_name: 'Melendez' },
 { first_name: 'Edmundo', last_name: 'Hepler' },
 { first_name: 'Marsha', last_name: 'Letourneau' }
];

HTML:

<input ng-model="search" placeholder="search by full name"/> 
<th ng-repeat="user in users | searchField: 'first_name': 'last_name' | filter: search">
  {{ user.first_name }} {{ user.last_name }}
</th>
<!-- so now you can search by full name -->

How to secure the ASP.NET_SessionId cookie?

To add the ; secure suffix to the Set-Cookie http header I simply used the <httpCookies> element in the web.config:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>

IMHO much more handy than writing code as in the article of Anubhav Goyal.

See: http://msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx

Check if element at position [x] exists in the list

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

How to read data from a file in Lua

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);

Animation CSS3: display + opacity

I changed a bit but the result is beautiful.

.child {
    width: 0px;
    height: 0px;
    opacity: 0;
}

.parent:hover child {
    width: 150px;
    height: 300px;
    opacity: .9;
}

Thank you to everyone.

How to find/identify large commits in git history?

Step 1 Write all file SHA1s to a text file:

git rev-list --objects --all | sort -k 2 > allfileshas.txt

Step 2 Sort the blobs from biggest to smallest and write results to text file:

git gc && git verify-pack -v .git/objects/pack/pack-*.idx | egrep "^\w+ blob\W+[0-9]+ [0-9]+ [0-9]+$" | sort -k 3 -n -r > bigobjects.txt

Step 3a Combine both text files to get file name/sha1/size information:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | awk '{print $1,$3,$7}' >> bigtosmall.txt
done;

Step 3b If you have file names or path names containing spaces try this variation of Step 3a. It uses cut instead of awk to get the desired columns incl. spaces from column 7 to end of line:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | cut -d ' ' -f'1,3,7-' >> bigtosmall.txt
done;

Now you can look at the file bigtosmall.txt in order to decide which files you want to remove from your Git history.

Step 4 To perform the removal (note this part is slow since it's going to examine every commit in your history for data about the file you identified):

git filter-branch --tree-filter 'rm -f myLargeFile.log' HEAD

Source

Steps 1-3a were copied from Finding and Purging Big Files From Git History

EDIT

The article was deleted sometime in the second half of 2017, but an archived copy of it can still be accessed using the Wayback Machine.

How is length implemented in Java Arrays?

According to the Java Language Specification (specifically §10.7 Array Members) it is a field:

  • The public final field length, which contains the number of components of the array (length may be positive or zero).

Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.

The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:

[...] arrays have a third header field, for the array size.

How do I display a text file content in CMD?

To do this, you can use Microsoft's more advanced command-line shell called "Windows PowerShell." It should come standard on the latest versions of Windows, but you can download it from Microsoft if you don't already have it installed.

To get the last five lines in the text file simply read the file using Get-Content, then have Select-Object pick out the last five items/lines for you:

Get-Content c:\scripts\test.txt | Select-Object -last 5

Source: Using the Get-Content Cmdlet

Received fatal alert: handshake_failure through SSLHandshakeException

In my case, the website just can use TLSv1.2. and i use apache httpclient 4.5.6, i use this code and install jce to solve this (JDK1.7):

jce

jdk7 http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

jdk 8 http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

code:

SSLContext sslContext = SSLContext.getDefault();

  SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
      sslContext,
      new String[]{"TLSv1.2"}, // important
      null,
      NoopHostnameVerifier.INSTANCE);

  Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("https", sslConnectionFactory)
      .register("http", PlainConnectionSocketFactory.INSTANCE)
      .build();

  HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
  httpclient = HttpClientBuilder.create().
      .setSSLSocketFactory(sslConnectionFactory)
      .setConnectionManager(ccm)
      .build();

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

You have to change the mamp Mysql Database port into 8889.

Virtual Serial Port for Linux

Using the links posted in the previous answers, I coded a little example in C++ using a Virtual Serial Port. I pushed the code into GitHub: https://github.com/cymait/virtual-serial-port-example .

The code is pretty self explanatory. First, you create the master process by running ./main master and it will print to stderr the device is using. After that, you invoke ./main slave device, where device is the device printed in the first command.

And that's it. You have a bidirectional link between the two process.

Using this example you can test you the application by sending all kind of data, and see if it works correctly.

Also, you can always symlink the device, so you don't need to re-compile the application you are testing.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

I've added the <%% literal tag delimiter as an answer to this because of its obscurity. This will tell erb not to interpret the <% part of the tag which is necessary for js apps like displaying chart.js tooltips etc.

Update (Fixed broken link)

Everything about ERB can now be found here: https://puppet.com/docs/puppet/5.3/lang_template_erb.html#tags

Copy every nth line from one sheet to another

In my opinion the answers given to this question are too specific. Here's an attempt at a more general answer with two different approaches and a complete example.

The OFFSET approach

OFFSET takes 3 mandatory arguments. The first is a given cell that we want to offset from. The next two are the number of rows and columns we want to offset (downwards and rightwards). OFFNET returns the content of the cell this results in. For instance, OFFSET(A1, 1, 2) returns the contents of cell C2 because A1 is cell (1,1) and if we add (1,2) to that we get (2,3) which corresponds to cell C2.

To get this to return every nth row from another column, we can make use of the ROW function. When this function is given no argument, it returns the row number of the current cell. We can thus combine OFFSET and ROW to make a function that returns every nth cell by adding a multiplier to the value returned by ROW. For instance OFFSET(A$1,ROW()*3,0). Note the use of $1 in the target cell. If this is not used, the offsetting will offset from different cells, thus in effect adding 1 to the multiplier.

The ADDRESS + INDIRECT approach

ADDRESS takes two integer inputs and returns the address/name of the cell as a string. For instance, ADDRESS(1,1) return "$A$1". INDIRECT takes the address of a cell and returns the contents. For instance, INDIRECT("A1") returns the contents of cell A1 (it also accepts input with $'s in it). If we use ROW inside ADDRESS with a multiplier, we can get the address of every nth cell. For instance, ADDRESS(ROW(), 1) in row 1 will return "$A$1", in row 2 will return "$A$2" and so on. So, if we put this inside INDIRECT, we can get the content of every nth cells. For instance, INDIRECT(ADDRESS(1*ROW()*3,1)) returns the contents of every 3rd cell in the first column when dragged downwards.

Example

Consider the following screenshot of a spreadsheet. The headers (first row) contains the call used in the rows below. enter image description here Column A contains our example data. In this case, it's just the positive integers (the counting continues outside the shown area). These are the values that we want to get every 3rd of, that is, we want to get 1, 4, 7, 10, and so on.

Column B contains an incorrect attempt at using the OFFSET approach but where we forgot to use $. As can be seen, while we multiply by 3, we actually get every 4th row.

Column C contains an incorrect attempt at using the OFFSET approach where we remembered to use $, but forgot to subtract. So while we do get every 3rd value, we skipped some values (1 and 4).

Column D contains a correct function using the OFFSET approach.

Column E contains an incorrect attempt at using the ADDRESS + INDRECT approach, but where we forgot to subtract. Thus we skipped some rows initially. The same problem as with column C.

Column F contains a correct function using the ADDRESS + INDRECT approach.

How can I merge two commits into one if I already started rebase?

Since I use git cherry-pick for just about everything, to me it comes natural to do so even here.

Given that I have branchX checked out and there are two commits at the tip of it, of which I want to create one commit combining their content, I do this:

git checkout HEAD^ // Checkout the privious commit
git cherry-pick --no-commit branchX // Cherry pick the content of the second commit
git commit --amend // Create a new commit with their combined content

If i want to update branchX as well (and I suppose this is the down side of this method) I also have to:

git checkout branchX
git reset --hard <the_new_commit>

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Javascript - Track mouse position

Here is the simplest way to track your mouse position

Html

<body id="mouse-position" ></body>

js

document.querySelector('#mouse-position').addEventListener('mousemove', (e) => {
        console.log("mouse move X: ", e.clientX);
        console.log("mouse move X: ", e.screenX);


    }, );

know more

split string only on first instance - java

This works:

public class Split
{
    public static void main(String...args)
    {
        String a = "%abcdef&Ghijk%xyz";
        String b[] = a.split("%", 2);
        
        System.out.println("Value = "+b[1]);
    }
}

Each GROUP BY expression must contain at least one column that is not an outer reference

Well, as it was said before, you can't GROUP by literals, I think that you are confused cause you can ORDER by 1, 2, 3. When you use functions as your columns, you need to GROUP by the same expression. Besides, the HAVING clause is wrong, you can only use what is in the agreggations. In this case, your query should be like this:

SELECT 
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound,
MAX(qvalues.rid) MaxRid
FROM batchinfo join qvalues 
ON batchinfo.rowid=qvalues.rowid
WHERE LEN(datapath)>4
GROUP BY 
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound

Update rows in one table with data from another table based on one column in each being equal

If you want to update matching rows in t1 with data from t2 then:

update t1
set (c1, c2, c3) = 
(select c1, c2, c3 from t2
 where t2.user_id = t1.user_id)
where exists
(select * from t2
 where t2.user_id = t1.user_id)

The "where exists" part it to prevent updating the t1 columns to null where no match exists.

How can I make space between two buttons in same div?

I actual ran into the same requirement. I simply used CSS override like this

.navbar .btn-toolbar { margin-top: 0; margin-bottom: 0 }

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

Referencing another schema in Mongoose

Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing

http://mongoosejs.com/docs/populate.html

Why can't I display a pound (£) symbol in HTML?

You need to save your PHP script file in UTF-8 encoding, and leave the <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> in the HTML.

For text editor, I recommend Notepad++, because it can detect and display the actual encoding of the file (in the lower right corner of the editor), and you can convert it as well.

Android – Listen For Incoming SMS Messages

Thank to @Vineet Shukla (the accepted answer) and @Ruchir Baronia (found the issue in the accepted answer), below is the Kotlin version:

Add permission:

<uses-permission android:name="android.permission.RECEIVE_SMS" />

Register BroadcastReceiver in AndroidManifest:

<receiver
    android:name=".receiver.SmsReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter android:priority="2332412">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Add implementation for BroadcastReceiver:

class SmsReceiver : BroadcastReceiver() {
    private var mLastTimeReceived = System.currentTimeMillis()

    override fun onReceive(p0: Context?, intent: Intent?) {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - mLastTimeReceived > 200) {
            mLastTimeReceived = currentTimeMillis

            val pdus: Array<*>
            val msgs: Array<SmsMessage?>
            var msgFrom: String?
            var msgText: String?
            val strBuilder = StringBuilder()
            intent?.extras?.let {
                try {
                    pdus = it.get("pdus") as Array<*>
                    msgs = arrayOfNulls(pdus.size)
                    for (i in msgs.indices) {
                        msgs[i] = SmsMessage.createFromPdu(pdus[i] as ByteArray)
                        strBuilder.append(msgs[i]?.messageBody)
                    }

                    msgText = strBuilder.toString()
                    msgFrom = msgs[0]?.originatingAddress

                    if (!msgFrom.isNullOrBlank() && !msgText.isNullOrBlank()) {
                        //
                        // Do some thing here
                        //
                    }
                } catch (e: Exception) {
                }
            }
        }
    }
}

Sometime event fires twice so I add mLastTimeReceived = System.currentTimeMillis()

In Chart.js set chart title, name of x axis and y axis?

          <Scatter
            data={data}
            // style={{ width: "50%", height: "50%" }}
            options={{
              scales: {
                yAxes: [
                  {
                    scaleLabel: {
                      display: true,
                      labelString: "Probability",
                    },
                  },
                ],
                xAxes: [
                  {
                    scaleLabel: {
                      display: true,
                      labelString: "Hours",
                    },
                  },
                ],
              },
            }}
          />

How to list running screen sessions?

 For windows system

 Open putty 
 then login in server

If you want to see screen in Console then you have to write command

 Screen -ls

if you have to access the screen then you have to use below command

 screen -x screen id

Write PWD in command line to check at which folder you are currently

SCRIPT5: Access is denied in IE9 on xmlhttprequest

  $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This code will work https sites too

Rails 4: how to use $(document).ready() with turbo-links

None of the above works for me, I solved this by not using jQuery's $(document).ready, but use addEventListener instead.

document.addEventListener("turbolinks:load", function() {
  // do something
});

Running a cron job at 2:30 AM everyday

As an addition to the all above mentioned great answers, check the https://crontab.guru/ - a useful online resource for checking your crontab syntax.

What you get is human readable representation of what you have specified.

See the examples below:

Branch from a previous commit using Git

git checkout -b <branch-name> <sha1-of-commit>

Configure nginx with multiple locations with different root folders on subdomain

You need to use the alias directive for location /static:

server {

  index index.html;
  server_name test.example.com;

  root /web/test.example.com/www;

  location /static/ {
    alias /web/test.example.com/static/;
  }

}

The nginx wiki explains the difference between root and alias better than I can:

Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.

Note that root and alias handle trailing slashes differently.

Most efficient way to remove special characters from string

I agree with this code sample. The only different it I make it into Extension Method of string type. So that you can use it in a very simple line or code:

string test = "abc@#$123";
test.RemoveSpecialCharacters();

Thank to Guffa for your experiment.

public static class MethodExtensionHelper
    {
    public static string RemoveSpecialCharacters(this string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }
}

Disable cache for some images

If you have a hardcoded image URL, for example: http://example.com/image.jpg you can use php to add headers to your image.

First you will have to make apache process your jpg as php. See here: Is it possible to execute PHP with extension file.php.jpg?

Load the image (imagecreatefromjpeg) from file then add the headers from previous answers. Use php function header to add the headers.

Then output the image with the imagejpeg function.

Please notice that it's very insecure to let php process jpg images. Also please be aware I haven't tested this solution so it is up to you to make it work.

C++ - how to find the length of an integer

Code for finding Length of int and decimal number:

#include<iostream>
    #include<cmath>
    using namespace std;
    int main()
    {
        int len,num;
        cin >> num;
        len = log10(num) + 1;
        cout << len << endl;
        return 0;
    }
    //sample input output
    /*45566
    5

    Process returned 0 (0x0)   execution time : 3.292 s
    Press any key to continue.
    */

Is it possible to have a default parameter for a mysql stored procedure?

No, this is not supported in MySQL stored routine syntax.

Feel free to submit a feature request at bugs.mysql.com.

What is the difference between typeof and instanceof and when should one be used vs. the other?

When checking for a function, one must always use typeof.

Here's the difference:

var f = Object.create(Function);

console.log(f instanceof Function); //=> true
console.log(typeof f === 'function'); //=> false

f(); // throws TypeError: f is not a function

This is why one must never use instanceof to check for a function.

Using LINQ to concatenate strings

This answer shows usage of LINQ (Aggregate) as requested in the question and is not intended for everyday use. Because this does not use a StringBuilder it will have horrible performance for very long sequences. For regular code use String.Join as shown in the other answer

Use aggregate queries like this:

string[] words = { "one", "two", "three" };
var res = words.Aggregate(
   "", // start with empty string to handle empty list case.
   (current, next) => current + ", " + next);
Console.WriteLine(res);

This outputs:

, one, two, three

An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an IEnumerable object.

Remember that aggregate queries are executed immediately.

More information - MSDN: Aggregate Queries


If you really want to use Aggregate use variant using StringBuilder proposed in comment by CodeMonkeyKing which would be about the same code as regular String.Join including good performance for large number of objects:

 var res = words.Aggregate(
     new StringBuilder(), 
     (current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
     .ToString();

Case in Select Statement

The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.

http://msdn.microsoft.com/en-us/library/ms181765.aspx

USE AdventureWorks2012;
GO
SELECT   ProductNumber, Name, "Price Range" = 
  CASE 
     WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
     WHEN ListPrice < 50 THEN 'Under $50'
     WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
     WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
     ELSE 'Over $1000'
  END
FROM Production.Product
ORDER BY ProductNumber ;
GO

Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.