Programs & Examples On #Webcron

Create code first, many to many, with additional fields in association table

It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberID { get; set; }
    [Key, Column(Order = 1)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

... or ...

var commentsOfMembers = context.MemberComments
    .Where(mc => mc.Member.LastName == "Smith")
    .Select(mc => mc.Comment)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

If you want to find all comments of a member with MemberId = 1:

var commentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1)
    .Select(mc => mc.Comment)
    .ToList();

Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something:

var filteredCommentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1 && mc.Something == 99)
    .Select(mc => mc.Comment)
    .ToList();

Because of lazy loading things might become easier. If you have a loaded Member you should be able to get the comments without an explicit query:

var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);

I guess that lazy loading will fetch the comments automatically behind the scenes.

Edit

Just for fun a few examples more how to add entities and relationships and how to delete them in this model:

1) Create one member and two comments of this member:

var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
                                         Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
                                         Something = 102 };

context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2

context.SaveChanges();

2) Add a third comment of member1:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    var comment3 = new Comment { Message = "Good night!" };
    var memberComment3 = new MemberComment { Member = member1,
                                             Comment = comment3,
                                             Something = 103 };

    context.MemberComments.Add(memberComment3); // will also add comment3
    context.SaveChanges();
}

3) Create new member and relate it to the existing comment2:

var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
    .SingleOrDefault();
if (comment2 != null)
{
    var member2 = new Member { FirstName = "Paul" };
    var memberComment4 = new MemberComment { Member = member2,
                                             Comment = comment2,
                                             Something = 201 };

    context.MemberComments.Add(memberComment4);
    context.SaveChanges();
}

4) Create relationship between existing member2 and comment3:

var member2 = context.Members.Where(m => m.FirstName == "Paul")
    .SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
    .SingleOrDefault();
if (member2 != null && comment3 != null)
{
    var memberComment5 = new MemberComment { Member = member2,
                                             Comment = comment3,
                                             Something = 202 };

    context.MemberComments.Add(memberComment5);
    context.SaveChanges();
}

5) Delete this relationship again:

var memberComment5 = context.MemberComments
    .Where(mc => mc.Member.FirstName == "Paul"
        && mc.Comment.Message == "Good night!")
    .SingleOrDefault();
if (memberComment5 != null)
{
    context.MemberComments.Remove(memberComment5);
    context.SaveChanges();
}

6) Delete member1 and all its relationships to the comments:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    context.Members.Remove(member1);
    context.SaveChanges();
}

This deletes the relationships in MemberComments too because the one-to-many relationships between Member and MemberComments and between Comment and MemberComments are setup with cascading delete by convention. And this is the case because MemberId and CommentId in MemberComment are detected as foreign key properties for the Member and Comment navigation properties and since the FK properties are of type non-nullable int the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.

How to run an application as "run as administrator" from the command prompt?

Try this:

runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1" 

It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.

How to delete multiple pandas (python) dataframes from memory to save RAM?

This will delete the dataframe and will release the RAM/memory

del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()

the data-frame will be explicitly set to null

in the above statements

Firstly, the self reference of the dataframe is deleted meaning the dataframe is no longer available to python there after all the references of the dataframe is collected by garbage collector (gc.collect()) and then explicitly set all the references to empty dataframe.

more on the working of garbage collector is well explained in https://stackify.com/python-garbage-collection/

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

import android packages cannot be resolved

This import android packages cannot be resolved is also occurs when your using some library and that library is not in the same path where your application is there, or if you are importing the library and not coping library to the workspace

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

Use that code it definitely works and I modified it.

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
//import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.*;

public class TestApp {

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

        try {

            Class forName = Class.forName("com.mysql.jdbc.Driver");
            Connection con = null;
            con = DriverManager.getConnection("jdbc:mysql://localhost/tables", "root", "root");
            con.setAutoCommit(false);
            PreparedStatement pstm = null;
            FileInputStream input = new FileInputStream("C:\\Users\\Desktop\\a1.xls");
            POIFSFileSystem fs = new POIFSFileSystem(input);
            Workbook workbook;
            workbook = WorkbookFactory.create(fs);
            Sheet sheet = workbook.getSheetAt(0);
            Row row;
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                row = (Row) sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String add = row.getCell(1).getStringCellValue();

                int  contact = (int) row.getCell(2).getNumericCellValue();

                String email = row.getCell(3).getStringCellValue();

                String sql = "INSERT INTO employee (name, address, contactNo, email) VALUES('" + name + "','" + add + "'," + contact + ",'" + email + "')";
                pstm = (PreparedStatement) con.prepareStatement(sql);
                pstm.execute();
                System.out.println("Import rows " + i);
            }
            con.commit();
            pstm.close();
            con.close();
            input.close();
            System.out.println("Success import excel to mysql table");
        } catch (IOException e) {
        }
    }

}

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

When to use the !important property in CSS

This is a real-world example.

While working with GWT-Bootstrap V2, it will inject some CSS file, which will override my CSS styles. In order to make my properties to be not overridden, I used !important.

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

How to set array length in c# dynamically

Or in C# 3.0 using System.Linq you can skip the intermediate list:

private Update BuildMetaData(MetaData[] nvPairs)
{
        Update update = new Update();
        var ip = from nv in nvPairs
                 select new InputProperty()
                 {
                     Name = "udf:" + nv.Name,
                     Val = nv.Value
                 };
        update.Items = ip.ToArray();
        return update;
}

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine

React.js create loop through Array

You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

Converting String To Float in C#

Use Convert.ToDouble("41.00027357629127");

Convert.ToDouble documentation

How to format a DateTime in PowerShell

Do this if you absolutely need to use the -Format option:

$dateStr = Get-Date $date -Format "yyyMMdd"

However

$dateStr = $date.toString('yyyMMdd')

is probably more efficient.. :)

How can JavaScript save to a local file?

If you are using FireFox you can use the File HandleAPI

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

I had just tested it out and it works!

How do I cast a JSON Object to a TypeScript class?

I had the same issue and I have found a library that does the job : https://github.com/pleerock/class-transformer.

It works like this :

let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;

It supports nested childs but you have to decorate your class's member.

ASP.NET MVC Razor pass model to layout

A common solution is to make a base view model which contains the properties used in the layout file and then inherit from the base model to the models used on respective pages.

The problem with this approach is that you now have locked yourself into the problem of a model can only inherit from one other class, and maybe your solution is such that you cannot use inheritance on the model you intended anyways.

My solution also starts of with a base view model:

public class LayoutModel
{
    public LayoutModel(string title)
    {
        Title = title;
    }

    public string Title { get;}
}

What I then use is a generic version of the LayoutModel which inherits from the LayoutModel, like this:

public class LayoutModel<T> : LayoutModel
{
    public LayoutModel(T pageModel, string title) : base(title)
    {
        PageModel = pageModel;
    }

    public T PageModel { get; }
}

With this solution I have disconnected the need of having inheritance between the layout model and the model.

So now I can go ahead and use the LayoutModel in Layout.cshtml like this:

@model LayoutModel
<!doctype html>
<html>
<head>
<title>@Model.Title</title>
</head>
<body>
@RenderBody()
</body>
</html>

And on a page you can use the generic LayoutModel like this:

@model LayoutModel<Customer>
@{
    var customer = Model.PageModel;
}

<p>Customer name: @customer.Name</p>

From your controller you simply return a model of type LayoutModel:

public ActionResult Page()
{
    return View(new LayoutModel<Customer>(new Customer() { Name = "Test" }, "Title");
}

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

Spring MVC 4: "application/json" Content Type is not being set correctly

Not exactly for this OP, but for those who encountered 404 and cannot set response content-type to "application/json" (any content-type). One possibility is a server actually responds 406 but explorer (e.g., chrome) prints it as 404.

If you do not customize message converter, spring would use AbstractMessageConverterMethodProcessor.java. It would run:

List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);

and if they do not have any overlapping (the same item), it would throw HttpMediaTypeNotAcceptableException and this finally causes 406. No matter if it is an ajax, or GET/POST, or form action, if the request uri ends with a .html or any suffix, the requestedMediaTypes would be "text/[that suffix]", and this conflicts with producibleMediaTypes, which is usually:

"application/json"  
"application/xml"   
"text/xml"          
"application/*+xml" 
"application/json"  
"application/*+json"
"application/json"  
"application/*+json"
"application/xml"   
"text/xml"          
"application/*+xml"
"application/xml"  
"text/xml"         
"application/*+xml"

Detect when a window is resized using JavaScript ?

If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:

Super Super compact

var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }

All 3 possible combinations together (ES6)

var t
window.onresize = () => {
    resizing(this, this.innerWidth, this.innerHeight) //1
    if (typeof t == 'undefined') resStarted() //2
    clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}

function resizing(target, w, h) {
    console.log(`Youre resizing: width ${w} height ${h}`)
}    
function resStarted() { 
    console.log('Resize Started') 
}
function resEnded() { 
    console.log('Resize Ended') 
}

Use Font Awesome Icon in Placeholder

I do this by adding fa-placeholder class to input text:

<input type="text" name="search" class="form-control" placeholder="&#xF002;" />

so, in css just add this:

.fa-placholder { font-family: "FontAwesome"; }

It works well for me.

Update:

To change font while user type in your text input, just add your font after font awesome

.fa-placholder { font-family: "FontAwesome", "Source Sans Pro"; }

Skip certain tables with mysqldump

You can use the mysqlpump command with the

--exclude-tables=name

command. It specifies a comma-separated list of tables to exclude.

Syntax of mysqlpump is very similar to mysqldump, buts its way more performant. More information of how to use the exclude option you can read here: https://dev.mysql.com/doc/refman/5.7/en/mysqlpump.html#mysqlpump-filtering

How to compare two JSON objects with the same elements in a different order equal?

Decode them and compare them as mgilson comment.

Order does not matter for dictionary as long as the keys, and values matches. (Dictionary has no order in Python)

>>> {'a': 1, 'b': 2} == {'b': 2, 'a': 1}
True

But order is important in list; sorting will solve the problem for the lists.

>>> [1, 2] == [2, 1]
False
>>> [1, 2] == sorted([2, 1])
True

>>> a = '{"errors": [{"error": "invalid", "field": "email"}, {"error": "required", "field": "name"}], "success": false}'
>>> b = '{"errors": [{"error": "required", "field": "name"}, {"error": "invalid", "field": "email"}], "success": false}'
>>> a, b = json.loads(a), json.loads(b)
>>> a['errors'].sort()
>>> b['errors'].sort()
>>> a == b
True

Above example will work for the JSON in the question. For general solution, see Zero Piraeus's answer.

How to redirect siteA to siteB with A or CNAME records

You can do this a number of non-DNS ways. The landing page at subdomain.hostone.com can have an HTTP redirect. The webserver at hostone.com can be configured to redirect (easy in Apache, not sure about IIS), etc.

Python - TypeError: 'int' object is not iterable

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

MySQL Sum() multiple columns

SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table

Android read text raw resource file

Here goes mix of weekens's and Vovodroid's solutions.

It is more correct than Vovodroid's solution and more complete than weekens's solution.

    try {
        InputStream inputStream = res.openRawResource(resId);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            } finally {
                reader.close();
            }
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        // process exception
    }

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I had this issue with Mvc identity when registering new user instead of:

var result = await UserManager.CreateAsync(user);

I was doing:

var result = await UserManager.UpdateAsync(user);

How can I add a help method to a shell script?

The first argument to a shell script is available as the variable $1, so the simplest implementation would be

if [ "$1" == "-h" ]; then
  echo "Usage: `basename $0` [somestuff]"
  exit 0
fi

But what anubhava said.

Pure CSS to make font-size responsive based on dynamic amount of characters

I used smth like this:

1.style.fontSize = 15.6/(document.getElementById("2").innerHTML.length)+ 'vw'

Where: 1 - parent div Id and 2 - Id of div with my text

Check if key exists in JSON object using jQuery

No need of JQuery simply you can do

if(yourObject['email']){
 // what if this property exists.
}

as with any value for email will return you true, if there is no such property or that property value is null or undefined will result to false

How to only get file name with Linux 'find'?

In GNU find you can use -printf parameter for that, e.g.:

find /dir1 -type f -printf "%f\n"

What version of Java is running in Eclipse?

There are various options are available to test which java version is using your eclipse. The best way is to find first java installed in your machine.

run java -version command on terminal

then to check whether your eclipse pointing to the right version or not.

For that go to

Eclipse >> Preferences >>Java >>Installed JREs

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

Importing CommonCrypto in a Swift framework

WARNING: iTunesConnect may reject apps that are using this method.


New member on my team accidentally broke the solution given by one of the top answers, so I decided to consolidate it in a small wrapper project called CommonCryptoModule. You can install it manually or via Cocoapods:

pod 'CommonCryptoModule', '~> 1.0.2'

Then, all you have to do is to import the module where you need CommonCrypto, like so:

import CommonCryptoModule

Hope someone else finds this useful.

What is the difference between SAX and DOM?

You're comparing apples and pears. SAX is a parser that parses serialized DOM structures. There are many different parsers, and "event-based" refers to the parsing method.

Maybe a small recap is in order:

  • The document object model (DOM) is an abstract data model that describes a hierarchical, tree-based document structure; a document tree consists of nodes, namely element, attribute and text nodes (and some others). Nodes have parents, siblings and children and can be traversed, etc., all the stuff you're used to from doing JavaScript (which incidentally has nothing to do with the DOM).

  • A DOM structure may be serialized, i.e. written to a file, using a markup language like HTML or XML. An HTML or XML file thus contains a "written out" or "flattened out" version of an abstract document tree.

  • For a computer to manipulate, or even display, a DOM tree from a file, it has to deserialize, or parse, the file and reconstruct the abstract tree in memory. This is where parsing comes in.

Now we come to the nature of parsers. One way to parse would be to read in the entire document and recursively build up a tree structure in memory, and finally expose the entire result to the user. (I suppose you could call these parsers "DOM parsers".) That would be very handy for the user (I think that's what PHP's XML parser does), but it suffers from scalability problems and becomes very expensive for large documents.

On the other hand, event-based parsing, as done by SAX, looks at the file linearly and simply makes call-backs to the user whenever it encounters a structural piece of data, like "this element started", "that element ended", "some text here", etc. This has the benefit that it can go on forever without concern for the input file size, but it's a lot more low-level because it requires the user to do all the actual processing work (by providing call-backs). To return to your original question, the term "event-based" refers to those parsing events that the parser raises as it traverses the XML file.

The Wikipedia article has many details on the stages of SAX parsing.

Determine what attributes were changed in Rails after_save callback?

you can add a condition to the after_update like so:

class SomeModel < ActiveRecord::Base
  after_update :send_notification, if: :published_changed?

  ...
end

there's no need to add a condition within the send_notification method itself.

oracle - what statements need to be committed?

DML (Data Manipulation Language) commands need to be commited/rolled back. Here is a list of those commands.

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency

Use multiple custom fonts using @font-face?

Check out fontsquirrel. They have a web font generator, which will also spit out a suitable stylesheet for your font (look for "@font-face kit"). This stylesheet can be included in your own, or you can use it as a template.

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

I was also wondering how to store it cleanly in a variable. As using

char c = '•';

is not very good practice (I guess). I found out the following way of storing it in a variable

char c = (char)0x2022;// or 0x25cf depending on the one you choose

or even cleaner

char c = '\u2022';// or "\u25cf"

https://msdn.microsoft.com/en-us/library/aa664669%28v=vs.71%29.aspx

same for strings

string s = "\u2022";

https://msdn.microsoft.com/en-us/library/362314fe.aspx

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

I think it really depends on why this error is given. It may be the bitness issue, but it may also be because of a deinstaller bug that leaves registry entries behind.

I just had this case because I need two versions of Python on my system. When I tried to install SCons (using Python2), the .msi installer failed, saying it only found Python3 in the registry. So I uninstalled it, with the result that no Python was found at all. Frustrating! (workaround: install SCons with pip install --egg --upgrade scons)

Anyway, I'm sure there are threads on that phenomenon. I just thought it would fit here because this was one of my top search results.

SQL Server Profiler - How to filter trace to only display events from one database?

Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

Here's a cross browser solution that triggers an event when your selected images are loaded: http://desandro.github.io/imagesloaded/ you can look up the height and width within the imagesLoaded() function.

CHECK constraint in MySQL is not working

try with set sql_mode = 'STRICT_TRANS_TABLES' OR SET sql_mode='STRICT_ALL_TABLES'

What is the difference between functional and non-functional requirements?

I think functional requirement is from client to developer side that is regarding functionality to the user by the software and non-functional requirement is from developer to client i.e. the requirement is not given by client but it is provided by developer to run the system smoothly e.g. safety, security, flexibility, scalability, availability, etc.

illegal character in path

I usualy would enter the path like this ....

FileInfo fi = new FileInfo(@"C:\Program Files (x86)\test software\myapp\demo.exe"); 

Did you register the @ at the beginning of the string? ;-)

Swapping pointers in C (char, int)

If you have the luxury of working in C++, use this:

template<typename T>
void swapPrimitives(T& a, T& b)
{
    T c = a;
    a = b;
    b = c;
}

Granted, in the case of char*, it would only swap the pointers themselves, not the data they point to, but in most cases, that is OK, right?

javascript: detect scroll end

I could not get either of the above answers to work so here is a third option that works for me! (This is used with jQuery)

if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) {
    //do stuff
}

Hope this helps anyone!

how do I query sql for a latest record date for each user

SELECT * FROM TABEL1 WHERE DATE= (SELECT MAX(CREATED_DATE) FROM TABEL1)

Open URL in Java to get the content

public class UrlContent{
    public static void main(String[] args) {

        URL url;

        try {
            // get URL content

            String a="http://localhost:8080/TestWeb/index.jsp";
            url = new URL(a);
            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                               new InputStreamReader(conn.getInputStream()));

            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                    System.out.println(inputLine);
            }
            br.close();

            System.out.println("Done");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Capture HTML Canvas as gif/jpg/png/pdf?

HTML5 provides Canvas.toDataURL(mimetype) which is implemented in Opera, Firefox, and Safari 4 beta. There are a number of security restrictions, however (mostly to do with drawing content from another origin onto the canvas).

So you don't need an additional library.

e.g.

 <canvas id=canvas width=200 height=200></canvas>
 <script>
      window.onload = function() {
          var canvas = document.getElementById("canvas");
          var context = canvas.getContext("2d");
          context.fillStyle = "green";
          context.fillRect(50, 50, 100, 100);
          // no argument defaults to image/png; image/jpeg, etc also work on some
          // implementations -- image/png is the only one that must be supported per spec.
          window.location = canvas.toDataURL("image/png");
      }
 </script>

Theoretically this should create and then navigate to an image with a green square in the middle of it, but I haven't tested.

Convert seconds to HH-MM-SS with JavaScript?

After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.

function secsToTime(secs){
  var time = new Date(); 
  // create Date object and set to today's date and time
  time.setHours(parseInt(secs/3600) % 24);
  time.setMinutes(parseInt(secs/60) % 60);
  time.setSeconds(parseInt(secs%60));
  time = time.toTimeString().split(" ")[0];
  // time.toString() = "HH:mm:ss GMT-0800 (PST)"
  // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
  // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
  return time;
}

I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.

I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.

You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

How can I hide a TD tag using inline JavaScript or CSS?

Everything is possible (or almost) with css, just use:

display: none; //to hide

display: table-cell //to show

How to include file in a bash shell script

Simply put inside your script :

source FILE

Or

. FILE # POSIX compliant

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

Is your MySQL server version 5.5.3 or greater?

The utf8mb4, utf16, and utf32 character sets were added in MySQL 5.5.3.

http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-sets.html

How to unmount a busy device

Check out umount2:

Linux 2.1.116 added the umount2() system call, which, like umount(), unmounts a target, but allows additional flags controlling the behaviour of the operation:

MNT_FORCE (since Linux 2.1.116) Force unmount even if busy. (Only for NFS mounts.) MNT_DETACH (since Linux 2.4.11) Perform a lazy unmount: make the mount point unavailable for new accesses, and actually perform the unmount when the mount point ceases to be busy. MNT_EXPIRE (since Linux 2.6.8) Mark the mount point as expired. If a mount point is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount point as expired. The mount point remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount point. This flag cannot be specified with either MNT_FORCE or MNT_DETACH. Return Value

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

Create a new TextView programmatically then display it below another TextView

public View recentView;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Create a relative layout and add a button
        relativeLayout = new RelativeLayout(this);
        btn = new Button(this);
        btn.setId((int)System.currentTimeMillis());
        recentView = btn;
        btn.setText("Click me");
        relativeLayout.addView(btn);


        setContentView(relativeLayout);

        btn.setOnClickListener(new View.OnClickListener() {

            @Overr ide
            public void onClick(View view) {

                //Create a textView, set a random ID and position it below the most recently added view
                textView = new TextView(ActivityName.this);
                textView.setId((int)System.currentTimeMillis());
                layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
                textView.setText("Time: "+System.currentTimeMillis());
                relativeLayout.addView(textView, layoutParams);
                recentView = textView;
            }
        });
    }

This can be modified to display each element of a String array in different TextViews.

Convert command line argument to string

#include <iostream>

std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));

jQuery: Get selected element tag name

This is yet another way:

$('selector')[0].tagName

How to define a connection string to a SQL Server 2008 database?

You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:

Integrated Security = True;

If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:

User ID = "username"; Password = "password";

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

In my weird scenario, I had a different column that didn't always return a value in the 'render' function. return null solved my issue.

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

Remove portion of a string after a certain character

Hey I thought this may be useful for someone who wants to replace the characters comes after the "By", for example in the text he given has by at the 20th position of his string so if you want to ignore the by you should add + 2 to the position then which will ignore the 20th position and it will replace all after coming the by it will work if you give the exact character length of the text you're gonna replace.

$variable = substr($variable, 0, strpos($variable, "By") + 2 );

Set NA to 0 in R

To add to James's example, it seems you always have to create an intermediate when performing calculations on NA-containing data frames.

For instance, adding two columns (A and B) together from a data frame dfr:

temp.df <- data.frame(dfr) # copy the original
temp.df[is.na(temp.df)] <- 0
dfr$C <- temp.df$A + temp.df$B # or any other calculation
remove('temp.df')

When I do this I throw away the intermediate afterwards with remove/rm.

Extract values in Pandas value_counts()

Code

train["label_Name"].value_counts().to_frame()

where : label_Name Mean column_name

result (my case) :-

0    29720 
1     2242 
Name: label, dtype: int64

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

Whichever of those you choose, your record will look like the following:

Record: ALIAS or ANAME

Name: empty or @

Target: example.com.herokudns.com.

That's all you need.


However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

To handle the redirects at the application level, you'll need to:

  • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
  • Set up your SSL certificates
  • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
  • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
  • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
  • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

Check out this post from DNSimple for more.

MySQL root access from all hosts

if you have many networks attached to you OS, yo must especify one of this network in the bind-addres from my.conf file. an example:

[mysqld]
bind-address = 127.100.10.234

this ip is from a ethX configuration.

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

need to add a class to an element

You can use result.className = 'red';, but you can also use result.classList.add('red');. The .classList.add(str) way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.

How to print matched regex pattern using awk?

gawk can get the matching part of every line using this as action:

{ if (match($0,/your regexp/,m)) print m[0] }

match(string, regexp [, array]) If array is present, it is cleared, and then the zeroth element of array is set to the entire portion of string matched by regexp. If regexp contains parentheses, the integer-indexed elements of array are set to contain the portion of string matching the corresponding parenthesized subexpression. http://www.gnu.org/software/gawk/manual/gawk.html#String-Functions

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

How to print a dictionary line by line in Python?

Modifying MrWonderful code

import sys

def print_dictionary(obj, ident):
    if type(obj) == dict:
        for k, v in obj.items():
            sys.stdout.write(ident)
            if hasattr(v, '__iter__'):
                print k
                print_dictionary(v, ident + '  ')
            else:
                print '%s : %s' % (k, v)
    elif type(obj) == list:
        for v in obj:
            sys.stdout.write(ident)
            if hasattr(v, '__iter__'):
                print_dictionary(v, ident + '  ')
            else:
                print v
    else:
        print obj

How can I create an object based on an interface file definition in TypeScript?

If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:

declare const modal: IModal;

If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.

const modal: IModal = {
    content: '',
    form: '',
    href: '',
    $form: null,
    $message: null,
    $modal: null,
    $submits: null
};

Or lie, with a type assertion, but you'll lost type safety as you will now get undefined in unexpected places, and possibly runtime errors, when accessing modal.content and so on (properties that the contract says will be there).

const modal = {} as IModal;

Example Class

class Modal implements IModal {
    content: string;
    form: string;
    href: string;
    $form: JQuery;
    $message: JQuery;
    $modal: JQuery;
    $submits: JQuery;
}

const modal = new Modal();

You may think "hey that's really a duplication of the interface" - and you are correct. If the Modal class is the only implementation of the IModal interface you may want to delete the interface altogether and use...

const modal: Modal = new Modal();

Rather than

const modal: IModal = new Modal();

Capitalize first letter. MySQL

CREATE A FUNCTION:

CREATE DEFINER=`root`@`localhost` FUNCTION `UC_FIRST`(`oldWord` VARCHAR(255)) 

RETURNS varchar(255) CHARSET utf8

RETURN CONCAT( UCASE( LEFT(oldWord, 1)), LCASE(SUBSTRING(oldWord, 2)))

USE THE FUNCTION

UPDATE tbl_name SET col_name = UC_FIRST(col_name);

Getting "cannot find Symbol" in Java project in Intellij

This happened to me when I deleted a folder and then copy-pasted it back to the project.

Right-click project folder -> Rebuild worked for me.

How can I solve a connection pool problem between ASP.NET and SQL Server?

Unless your usage went up a lot, it seems unlikely that there is just a backlog of work. IMO, the most likely option is that something is using connections and not releasing them promptly. Are you sure you are using using in all cases? Or (through whatever mechanism) releasing the connections?

Exception thrown in catch and finally clause

The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.

Exception currentException = null;

As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.

Also, the finally blocks always run before the method exits. You could then requite the code snippet to:

public class C1 {

    public static void main(String [] argv) throws Exception {
        try {
            System.out.print(1);
            q();

        }
        catch ( Exception i ) {
            // <-- currentException = Exception, as thrown by q()'s finally block
            throw( new MyExc2() ); // <-- currentException = MyExc2
        }
        finally {
             // <-- currentException = MyExc2, thrown from main()'s catch block
            System.out.print(2);
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }

    }  // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.

    static void q() throws Exception {
        try {
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }
        catch( Exception y ) {
           // <-- currentException = null, because the exception is caught and not rethrown
        }
        finally {
            System.out.print(3);
            throw( new Exception() ); // <-- currentException = Exception
        }
    }
}

The order in which the application executes is:

main()
{
  try
    q()
    {
      try
      catch
      finally
    }
  catch
  finally
}

Convert js Array() to JSon object for use with JQuery .ajax

When using the data on the server, your characters can reach with the addition of slashes eg if string = {"hello"} comes as string = {\ "hello \"} to solve the following function can be used later to use json decode.

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

$array = $_POST['jObject'];
$array = stripslashes_deep($array);

$data = json_decode($array, true);
print_r($data);
?>

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

TRY

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings

EnableAutoProxyResultCache = dword: 0

Wget output document and headers to STDOUT

It works here:

    $ wget -S -O - http://google.com
HTTP request sent, awaiting response... 
  HTTP/1.1 301 Moved Permanently
  Location: http://www.google.com/
  Content-Type: text/html; charset=UTF-8
  Date: Sat, 25 Aug 2012 10:15:38 GMT
  Expires: Mon, 24 Sep 2012 10:15:38 GMT
  Cache-Control: public, max-age=2592000
  Server: gws
  Content-Length: 219
  X-XSS-Protection: 1; mode=block
  X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29--  http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...

  ...skipped a few more redirections ...

    [<=>                                                                                                                                     ] 0           --.-K/s              
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti 

... skipped ...

perhaps you need to update your wget (~$ wget --version GNU Wget 1.14 built on linux-gnu.)

appending list but error 'NoneType' object has no attribute 'append'

You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-

last_list.append(p.last)

if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

Taken from @J-Rou's comment

How do I create an array of strings in C?

I was missing somehow more dynamic array of strings, where amount of strings could be varied depending on run-time selection, but otherwise strings should be fixed.

I've ended up of coding code snippet like this:

#define INIT_STRING_ARRAY(...)          \
    {                                   \
        char* args[] = __VA_ARGS__;     \
        ev = args;                      \
        count = _countof(args);         \
    }

void InitEnumIfAny(String& key, CMFCPropertyGridProperty* item)
{
    USES_CONVERSION;
    char** ev = nullptr;
    int count = 0;

    if( key.Compare("horizontal_alignment") )
        INIT_STRING_ARRAY( { "top", "bottom" } )

    if (key.Compare("boolean"))
        INIT_STRING_ARRAY( { "yes", "no" } )

    if( ev == nullptr )
        return;

    for( int i = 0; i < count; i++)
        item->AddOption(A2T(ev[i]));

    item->AllowEdit(FALSE);
}

char** ev picks up pointer to array strings, and count picks up amount of strings using _countof function. (Similar to sizeof(arr) / sizeof(arr[0])).

And there is extra Ansi to unicode conversion using A2T macro, but that might be optional for your case.

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

What is the maximum size of a web browser's cookie's key?

A cookie key(used to identify a session) and a cookie are the same thing being used in different ways. So the limit would be the same. According to Microsoft its 4096 bytes.

MSDN

cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Well you could solve this with a temp table..

DECLARE @RoleToAdds TABLE
([RoleID] int, [PageID] int)

INSERT INTO @RoleToAdds ([RoleID], [PageID])
    VALUES
    (1, 2),
    (1, 3),
    (1, 4),
    (2, 5)

INSERT INTO [dbo].[RolePages] ([RoleID], [PageID])
    SELECT rta.[RoleID], rta.[PageID] FROM @RoleToAdds rta WHERE NOT EXISTS 
        (SELECT * FROM [RolePages] rp WHERE rp.PageID = rta.PageID AND rp.RoleID = rta.RoleID)

This might not work for big amounts of data but for a few rows it should work!

Confirm Password with jQuery Validate

It works if id value and name value are different:

<input type="password" class="form-control"name="password" id="mainpassword">
password: {     required: true,     } , 
cpassword: {required: true, equalTo: '#mainpassword' },

Hibernate table not mapped error in HQL query

I had same problem , instead @Entity I used following code for getting records

    List<Map<String, Object>> list = null;
            list = incidentHibernateTemplate.execute(new HibernateCallback<List<Map<String, Object>>>() {

            @Override
            public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery("SELECT * from table where appcode = :app");
                    query.setParameter("app", apptype);
                query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                return query.list();

                }
            });

I used following code for update

private @Autowired HibernateTemplate incidentHibernateTemplate;
Integer updateCount = 0;

    updateCount = incidentHibernateTemplate.execute((Session session) -> {
        Query<?> query = session
                    .createSQLQuery("UPDATE  tablename SET key = :apiurl, data_mode = :mode WHERE apiname= :api ");
          query.setParameter("apiurl", url);
          query.setParameter("api", api);
          query.setParameter("mode", mode);
            return query.executeUpdate();
        }
    );

Set default time in bootstrap-datetimepicker

This Works for me. I have to use specially date format like this 'YY-MM-dd hh:mm' or 'YYYY-MM-dd hh:mm'

$('#datetimepicker1').datetimepicker({
            format: 'YYYY-MM-dd hh:mm',
            defaultDate: new Date()
        });

IntelliJ: Working on multiple projects

Prequisite

Having all the related projects in the same root directory.

Steps

1) First you create a new Empty project

New empty project


2) Then you select the root directory of all you projects.

This will create a empty project, with a .idea directory that will simply remember the module organisation we are about to do in the next step

Select root directory


3) Then, in the next window, you import the different projects as modules

Import projects as modules


4) In the next window, to import each project, simply double click on the build.gradle, or pom.xml

The project will be imported as a new module. Select build file


5) Done, you now have all your projects as modules, opened on the same IntelliJ project

Result

How do I convert between big-endian and little-endian values in C++?

Seriously... I don't understand why all solutions are that complicated! How about the simplest, most general template function that swaps any type of any size under any circumstances in any operating system????

template <typename T>
void SwapEnd(T& var)
{
    static_assert(std::is_pod<T>::value, "Type must be POD type for safety");
    std::array<char, sizeof(T)> varArray;
    std::memcpy(varArray.data(), &var, sizeof(T));
    for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)
        std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);
    std::memcpy(&var, varArray.data(), sizeof(T));
}

It's the magic power of C and C++ together! Simply swap the original variable character by character.

Point 1: No operators: Remember that I didn't use the simple assignment operator "=" because some objects will be messed up when the endianness is flipped and the copy constructor (or assignment operator) won't work. Therefore, it's more reliable to copy them char by char.

Point 2: Be aware of alignment issues: Notice that we're copying to and from an array, which is the right thing to do because the C++ compiler doesn't guarantee that we can access unaligned memory (this answer was updated from its original form for this). For example, if you allocate uint64_t, your compiler cannot guarantee that you can access the 3rd byte of that as a uint8_t. Therefore, the right thing to do is to copy this to a char array, swap it, then copy it back (so no reinterpret_cast). Notice that compilers are mostly smart enough to convert what you did back to a reinterpret_cast if they're capable of accessing individual bytes regardless of alignment.

To use this function:

double x = 5;
SwapEnd(x);

and now x is different in endianness.

What is the difference between a "line feed" and a "carriage return"?

Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

I have the same problem, in build.gradle (Module:app) add the following line of code inside dependencies:

dependencies 
{
   ...
   compile 'com.android.support:support-annotations:27.1.1'
}

It worked for me perfectly

How do I run Selenium in Xvfb?

open a terminal and run this command xhost +. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands

Also make sure in your /etc/environment file there is a line

export DISPLAY=:0.0 

And then, run your tests to see if your issue is resolved.

All please note the comment from sardathrion below before using this.

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:

ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;

How to handle windows file upload using Selenium WebDriver?

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");

Hey, that's mine from somewhere :).


In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:

driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");

In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).

So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.

If not, you could try to jump to it by pressing Alt + N, at least on Windows...

If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:

driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C);        // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON);    // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH);    // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path

r.keyPress(KeyEvent.VK_ENTER);    // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).


For Flash, the only alternative I know (from this discussion) is to use the dark technique:

First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.

Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.

This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.

Force overwrite of local file with what's in origin repo?

If you want to overwrite only one file:

git fetch
git checkout origin/master <filepath>

If you want to overwrite all changed files:

git fetch
git reset --hard origin/master

(This assumes that you're working on master locally and you want the changes on the origin's master - if you're on a branch, substitute that in instead.)

How to make this Header/Content/Footer layout using CSS?

Here is how to to that:

The header and footer are 30px height.

The footer is stuck to the bottom of the page.

HTML:

<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>

CSS:

#header {
    height: 30px;
}
#footer {
    height: 30px;
    position: absolute;
    bottom: 0;
}
body {
    height: 100%;
    margin-bottom: 30px;
}

Try it on jsfiddle: http://jsfiddle.net/Usbuw/

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

How do I convert NSInteger to NSString datatype?

Obj-C way =):

NSString *inStr = [@(month) stringValue];

Python POST binary data

You can use unirest, It provides easy method to post request. `

import unirest
 
def callback(response):
 print "code:"+ str(response.code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "body:"+ str(response.body)
 print "******************"
 print "raw_body:"+ str(response.raw_body)
 
# consume async post request
def consumePOSTRequestASync():
 params = {'test1':'param1','test2':'param2'}
 
 # we need to pass a dummy variable which is open method
 # actually unirest does not provide variable to shift between
 # application-x-www-form-urlencoded and
 # multipart/form-data
  
 params['dummy'] = open('dummy.txt', 'r')
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 unirest.post(url, headers = headers,params = params, callback = callback)
 
 
# post async request multipart/form-data
consumePOSTRequestASync()

How to find elements with 'value=x'?

Value exactly equal to 123:

jQuery("#attached_docs[value='123']")

Full reference: http://api.jquery.com/category/selectors/

Execute php file from another php

exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g

exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;

or use the punct at the top of your php script

#!/usr/local/bin/php
<?php ... ?>

How to present a simple alert message in java?

I'll be the first to admit Java can be very verbose, but I don't think this is unreasonable:

JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");

If you statically import javax.swing.JOptionPane.showMessageDialog using:

import static javax.swing.JOptionPane.showMessageDialog;

This further reduces to

showMessageDialog(null, "This is even shorter");

Ansible: filter a list by its attributes

I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:

- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"

would return:

ok: [localhost] => {
    "msg": [
        "172.16.1.100"
    ]
}

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

You can use the .ToList() method to convert the IQueryable result returned to an IList, as shown below, after the linq query.

   public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname)
{
    DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities();
    DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection();
    if (firstname == null && lastname != null)
    {
        IList<DzieckoAndOpiekun> resultV = from p in db.Dziecko
                      where lastname == p.Nazwisko
                      **select** new DzieckoAndOpiekun(
                     p.Imie,
                     p.Nazwisko,
                     p.Opiekun.Imie,
                     p.Opiekun.Nazwisko).ToList()
                  ;
        result.AddRange(resultV);
    }
    return result;
}

Validate Dynamically Added Input fields

The one mahesh posted is not working because the attribute name is missing:

So instead of

<input id="list" class="required"  />

You can use:

<input id="list" name="list" class="required"  />

Modified version

Can you hide the controls of a YouTube embed without enabling autoplay?

To continue using the iframe YouTube, you should only have to change ?autoplay=1 to ?autoplay=0.

Another way to accomplish this would be by using the YouTube JavaScript Player API. (https://developers.google.com/youtube/js_api_reference)

Edit: the YouTube JavaScript Player API is no longer supported.

<div id="howToVideo"></div>

<script type="application/javascript">

    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = false;
    ga.src = 'http://www.youtube.com/player_api';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);

    var done = false;
    var player;

    function onYouTubePlayerAPIReady() {
        player = new YT.Player('howToVideo', {
            height: '390',
            width: '640',
            videoId: 'qUJYqhKZrwA',
        playerVars: {
            controls: 0,
            disablekb: 1
        },
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
    }
    function onPlayerReady(evt) {
        console.log('onPlayerReady', evt);
    }
    function onPlayerStateChange(evt) {
        console.log('onPlayerStateChange', evt);
        if (evt.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }

    function stopVideo() {
        console.log('stopVideo');
        player.stopVideo();
    }

</script>

Here is a jsfiddle for the example: http://jsfiddle.net/fgkrj/

Note that player controls are disabled in the "playerVars" part of the player. The one sacrifice you make is that users are still able to pause the video by clicking on it. I would suggest writing a simple javascript function that subscribes to a stop event and calls player.playVideo().

How to copy a collection from one database to another in MongoDB

for huge size collections, you can use Bulk.insert()

var bulk = db.getSiblingDB(dbName)[targetCollectionName].initializeUnorderedBulkOp();
db.getCollection(sourceCollectionName).find().forEach(function (d) {
    bulk.insert(d);
});
bulk.execute();

This will save a lot of time. In my case, I'm copying collection with 1219 documents: iter vs Bulk (67 secs vs 3 secs)

INNER JOIN ON vs WHERE clause

I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

How to concatenate two strings in C++?

C++14

std::string great = "Hello"s + " World"; // concatenation easy!

Answer on the question:

auto fname = ""s + name + ".txt";

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

Spring mvc @PathVariable

@PathVariable used to fetch the value from URL

for example: To get some question

www.stackoverflow.com/questions/19803731

Here some question id is passed as a parameter in URL

Now to fetch this value in controller all you have to do is just to pass @PathVariable in the method parameter

@RequestMapping(value = " /questions/{questionId}", method=RequestMethod.GET)
    public String getQuestion(@PathVariable String questionId){
    //return question details
}

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

Using $_POST to get select option value from HTML

<select name="taskOption">
      <option value="first">First</option>
      <option value="second">Second</option>
      <option value="third">Third</option>
</select>

$var = $_POST['taskOption'];

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

Generating a UUID in Postgres for Insert statement?

Without extensions (cheat)

SELECT uuid_in(md5(random()::text || clock_timestamp()::text)::cstring);

output>> c2d29867-3d0b-d497-9191-18a9d8ee7830

(works at least in 8.4)

  • Thanks to @Erwin Brandstetter for clock_timestamp() explanation.

If you need a valid v4 UUID

SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring);

enter image description here * Thanks to @Denis Stafichuk @Karsten and @autronix


Also, in modern Postgres, you can simply cast:

SELECT md5(random()::text || clock_timestamp()::text)::uuid

How do I center align horizontal <UL> menu?

Demo - http://codepen.io/grantex/pen/InLmJ

<div class="navigation">
    <ul>
        <li><a href="">Home</a></li>
        <li><a href="">About</a></li>
        <li><a href="">Contact</a></li>
        <li><a href="">Menu</a></li>
        <li><a href="">Others</a></li>
    </ul>
</div>


.navigation {
    max-width: 700px;
    margin: 0 auto;
}
.navigation ul {
    list-style: none;
    display: table;
    width: 100%;
}
.navigation ul li {
    display: table-cell;
    text-align: center;
}
.navigation ul li a {
    padding: 5px 10px;
    width: 100%;
}

Omg so much cleaner.

Pass in an enum as a method parameter

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
    file = new File
    {  
       Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions
    };

    return file.Id;
}

Best data type to store money values in MySQL

Try using

Decimal(19,4)

this usually works with every other DB as well

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

How to calculate number of days between two dates

This works for me:

_x000D_
_x000D_
const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .startOf('day')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_
);
_x000D_
_x000D_
_x000D_

Java: Sending Multiple Parameters to Method

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

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

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

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

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

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

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

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

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

Here's my 2 cents:

import sys

map the path where the module file is located. In my case it was the desktop

sys.path.append('/Users/John/Desktop')

Either import the whole mapping module BUT then you have to use the .notation to map the classes like mapping.Shipping()

import mapping #mapping.py is the name of my module file

shipit = mapping.Shipment() #Shipment is the name of the class I need to use in the mapping module

Or import the specific class from the mapping module

from mapping import Mapping

shipit = Shipment() #Now you don't have to use the .notation

Using LINQ to concatenate strings

quick performance data for the StringBuilder vs Select & Aggregate case over 3000 elements:

Unit test - Duration (seconds)
LINQ_StringBuilder - 0.0036644
LINQ_Select.Aggregate - 1.8012535

    [TestMethod()]
    public void LINQ_StringBuilder()
    {
        IList<int> ints = new List<int>();
        for (int i = 0; i < 3000;i++ )
        {
            ints.Add(i);
        }
        StringBuilder idString = new StringBuilder();
        foreach (int id in ints)
        {
            idString.Append(id + ", ");
        }
    }
    [TestMethod()]
    public void LINQ_SELECT()
    {
        IList<int> ints = new List<int>();
        for (int i = 0; i < 3000; i++)
        {
            ints.Add(i);
        }
        string ids = ints.Select(query => query.ToString())
                         .Aggregate((a, b) => a + ", " + b);
    }

How to convert the time from AM/PM to 24 hour format in PHP?

$s = '07:05:45PM';
$tarr = explode(':', $s);
if(strpos( $s, 'AM') === false && $tarr[0] !== '12'){
    $tarr[0] = $tarr[0] + 12;
}elseif(strpos( $s, 'PM') === false && $tarr[0] == '12'){
    $tarr[0] = '00';
}
echo preg_replace("/[^0-9 :]/", '', implode(':', $tarr));

HTML5 form required attribute. Set custom validation message?

Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/> field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.

I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:

Hello.js

import React, { Component } from "react";
import SelectValid from "./SelectValid";

export default class Hello extends Component {
  render() {
    return (
      <form>
        <SelectValid placeholder="this one is optional" />
        <SelectValid placeholder="this one is required" required />
        <input
          required
          defaultValue="foo"
          onChange={e => e.target.setCustomValidity("")}
          onInvalid={e => e.target.setCustomValidity("foo")}
        />
        <button>button</button>
      </form>
    );
  }
}

SelectValid.js

import React, { Component } from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";

export default class SelectValid extends Component {
  render() {
    this.required = !this.props.required
      ? false
      : this.state && this.state.value ? false : true;
    let inputProps = undefined;
    let onInputChange = undefined;
    if (this.props.required) {
      inputProps = {
        onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
      };
      onInputChange = value => {
        this.selectComponent.input.input.setCustomValidity(
          value
            ? ""
            : this.required
              ? "foo"
              : this.selectComponent.props.value ? "" : "foo"
        );
        return value;
      };
    }
    return (
      <Select
        onChange={value => {
          this.required = !this.props.required ? false : value ? false : true;
          let state = this && this.state ? this.state : { value: null };
          state.value = value;
          this.setState(state);
          if (this.props.onChange) {
            this.props.onChange();
          }
        }}
        value={this && this.state ? this.state.value : null}
        options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
        placeholder={this.props.placeholder}
        required={this.required}
        clearable
        searchable
        inputProps={inputProps}
        ref={input => (this.selectComponent = input)}
        onInputChange={onInputChange}
      />
    );
  }
}

How can we programmatically detect which iOS version is device running on?

In MonoTouch:

To get the Major version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[0]

For minor version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[1]

Difference between e.target and e.currentTarget

I like visual answers.

enter image description here

When you click #btn, two event handlers get called and they output what you see in the picture.

Demo here: https://jsfiddle.net/ujhe1key/

When to use If-else if-else over switch statements and vice versa

If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.

Otherwise, stick with multiple if-else statements.

How to use the IEqualityComparer

The inclusion of your comparison class (or more specifically the AsEnumerable call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.

You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.

Find text string using jQuery?

Take a look at highlight (jQuery plugin).

How can the Euclidean distance be calculated with NumPy?

There's a function for that in SciPy. It's called Euclidean.

Example:

from scipy.spatial import distance
a = (1, 2, 3)
b = (4, 5, 6)
dst = distance.euclidean(a, b)

Interfaces with static fields in java for sharing 'constants'

Given the advantage of hindsight, we can see that Java is broken in many ways. One major failing of Java is the restriction of interfaces to abstract methods and static final fields. Newer, more sophisticated OO languages like Scala subsume interfaces by traits which can (and typically do) include concrete methods, which may have arity zero (constants!). For an exposition on traits as units of composable behavior, see http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf. For a short description of how traits in Scala compare with interfaces in Java, see http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5. In the context of teaching OO design, simplistic rules like asserting that interfaces should never include static fields are silly. Many traits naturally include constants and these constants are appropriately part of the public "interface" supported by the trait. In writing Java code, there is no clean, elegant way to represent traits, but using static final fields within interfaces is often part of a good workaround.

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

What is a Data Transfer Object (DTO)?

  1. To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing.
  2. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.

Confused about __str__ on list in Python

Python has two different ways to convert an object to a string: str() and repr(). Printing an object uses str(); printing a list containing an object uses str() for the list itself, but the implementation of list.__str__() calls repr() for the individual items.

So you should also overwrite __repr__(). A simple

__repr__ = __str__

at the end of the class body will do the trick.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

What is thread safe or non-thread safe in PHP?

Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).

So basically, from bottom to top

Linux

Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx

PHP-FPM + APC

ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.

Checking if an object is null in C#

Whenever you are creating objects of class you have to check the whether the object is null or not using the below code.

Example: object1 is object of class

void myFunction(object1)
{
  if(object1!=null)
  {
     object1.value1 //If we miss the null check then here we get the Null Reference exception
  }
}

Bootstrap 3 Gutter Size

You can keep the default behaviour (with gutter) and add a class to your CSS stylesheet for tasks like yours:

.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}

And here’s how you can use it in your HTML:

<div class="row no-gutter">
    <div class="col-md-4">
        ...
    </div>
    <div class="col-md-4">
        ...
    </div>
    <div class="col-md-4">
        ...
    </div>
</div>

How to force reloading a page when using browser back button?

Currently this is the most up to date way reload page if the user clicks the back button.

const [entry] = performance.getEntriesByType("navigation");

// Show it in a nice table in the developer console
console.table(entry.toJSON());

if (entry["type"] === "back_forward")
    location.reload();

See here for source

Adobe Acrobat Pro make all pages the same dimension

The page sizes are looking different in your PDF because the images were originally set to different DPI (even if images are identical HxW in pixels). The good news is - it's only a display issue - and can be fixed easily.

An image with a higher DPI value would display smaller in a PDF (displays at the 'print-size' of the image). To avoid this, open each image in an image editor like GIMP or Photoshop. Open relevant image print control dialog box and set a suitable uniform DPI info for all the images. Remake the PDF with these new images. If in the new PDF images are too big - redo the DPI setting for each to a higher value. If in the new PDF pages are too small to read on-screen without zooming, again - redo DPI adjustment, this time put a lower DPI value. Ideally, 150 DPI should be good enough for images of 2500X2500 pixel - on a 17 inch monitor set to 1366x768 resolution.

BTW, the PDF file shall print each page at the specified DPI of that page. If all images are same DPI, you'll get a uniform printing.

Hope this helps :)

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

When you want to show an URL of remote branches, try:

git remote -v

How to Detect Browser Window /Tab Close Event?

to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :

_x000D_
_x000D_
<script>_x000D_
    function endSession() {_x000D_
         // Browser or Broswer tab is closed_x000D_
         // Write code here_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<body onpagehide="endSession();">_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Javascript array value is undefined ... how do I test for that

There are more (many) ways to Rome:

//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null

cheers!

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

Beware when comparing a .Net DateTime to SqlDateTime.MinValue or MaxValue. For example, the following will throw an exception:

DateTime dte = new DateTime(1000, 1, 1);
if (dte >= SqlDateTime.MinValue)
    //do something

The reason is that MinValue returns a SqlDateTime, not a DateTime. So .Net tries to convert dte to a SqlDateTime for comparison and because it's outside the acceptable SqlDateTime range it throws the exception.

One solution to this is to compare your DateTime to SqlDateTime.MinValue.Value.

How to git clone a specific tag

Use --single-branch option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.

git clone <repo_url> --branch <tag_name> --single-branch

Using Python, how can I access a shared folder on windows network?

How did you try it? Maybe you are working with \ and omit proper escaping.

Instead of

open('\\HOST\share\path\to\file')

use either Johnsyweb's solution with the /s, or try one of

open(r'\\HOST\share\path\to\file')

or

open('\\\\HOST\\share\\path\\to\\file')

.

What parameters should I use in a Google Maps URL to go to a lat-lon?

This should help with the new Google Maps:

http://maps.google.com/maps/place/<name>/@<lat>,<long>,15z/data=<mode-value>
  • The 'place' adds a marker.
  • 'name' could be a search term like "realtors"/"lawyers".
  • lat and long are the coordinates in decimal format and in that order.
  • 15z sets zoom level to 15 (between 1 ~ 20).
  • You can enforce a particular view mode (map is default) - earth or terrain by adding these: Terrain: /data=!5m1!1e4
    Earth: /data=!3m1!1e3

E.g.: https://www.google.com/maps/place/Lawyer/@48.8187768,2.3792362,15z/data=!3m1!1e3

References:
https://moz.com/blog/new-google-maps-url-parameters http://dddavemaps.blogspot.in/2015/07/google-maps-url-tricks.html

Manifest Merger failed with multiple errors in Android Studio

As a newbie to Android Studio, in my case, I had moved an existing project from Eclipse to Android Studio and found that there was a duplicate definition of an activity within my Manifest.xml that hadn't been picked up by Eclipse was shown as a Gradle error.

I found this by going to the Gradle Console (bottom right of the screen).

Catching "Maximum request length exceeded"

You can solve this by increasing the maximum request length in your web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" />
    </system.web>
</configuration>

The example above is for a 100Mb limit.

How do I determine file encoding in OS X?

Classic 8-bit LaTeX is very restricted in which UTF8 characters it can use; it's highly dependent on the encoding of the font you're using and which glyphs that font has available.

Since you don't give a specific example, it's hard to know exactly where the problem is — whether you're attempting to use a glyph that your font doesn't have or whether you're not using the correct font encoding in the first place.

Here's a minimal example showing how a few UTF8 characters can be used in a LaTeX document:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\begin{document}
‘Héllø—thêrè.’
\end{document}

You may have more luck with the [utf8x] encoding, but be slightly warned that it's no longer supported and has some idiosyncrasies compared with [utf8] (as far as I recall; it's been a while since I've looked at it). But if it does the trick, that's all that matters for you.

How to Create Multiple Where Clause Query Using Laravel Eloquent?

You may use in several ways,

$results = User::where([
    ['column_name1', '=', $value1],
    ['column_name2', '<', $value2],
    ['column_name3', '>', $value3]
])->get();

You can also use like this,

$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<',  $value2);
$results = $results->where('column3','>',  $value3);
$results = $results->get();

How to mark a build unstable in Jenkins when running shell scripts

Modern Jenkins versions (since 2.26, October 2016) solved this: it's just an advanced option for the Execute shell build step!

exit code for build

You can just choose and set an arbitrary exit value; if it matches, the build will be unstable. Just pick a value which is unlikely to be launched by a real process in your build.

Gradle - Could not find or load main class

For a project structure like

project_name/src/main/java/Main_File.class

in the file build.gradle, add the following line

mainClassName = 'Main_File'

How do I capture response of form.submit

You can accomplish this using jQuery and the ajax() method:

_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<script language="javascript" type="text/javascript">_x000D_
function submitform() {_x000D_
      $.ajax({_x000D_
        headers: { _x000D_
          'Accept': 'application/json',_x000D_
          'Content-Type': 'application/json' _x000D_
        },_x000D_
        type: "POST",_x000D_
        url : "/hello.hello",_x000D_
        dataType : "json",_x000D_
        data : JSON.stringify({"hello_name": "hello"}),_x000D_
        error: function () {_x000D_
          alert('loading Ajax failure');_x000D_
        },_x000D_
     onFailure: function () {_x000D_
          alert('Ajax Failure');_x000D_
     },_x000D_
     statusCode: {_x000D_
          404: function() {_x000D_
          alert("missing info");_x000D_
          }   _x000D_
     },_x000D_
        success : function (response) {_x000D_
          alert("The server says: " + JSON.stringify(response));_x000D_
        }_x000D_
      })_x000D_
      .done(function( data ) {_x000D_
        $("#result").text(data['hello']);_x000D_
      });_x000D_
};</script>
_x000D_
_x000D_
_x000D_

URLEncoder not able to translate space character

Check out the java.net.URI class.

Get IP address of an interface on Linux

Try this:

#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>

int
main()
{
 int fd;
 struct ifreq ifr;

 fd = socket(AF_INET, SOCK_DGRAM, 0);

 /* I want to get an IPv4 IP address */
 ifr.ifr_addr.sa_family = AF_INET;

 /* I want IP address attached to "eth0" */
 strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);

 ioctl(fd, SIOCGIFADDR, &ifr);

 close(fd);

 /* display result */
 printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

 return 0;
}

The code sample is taken from here.

Uses for the '&quot;' entity in HTML

Reason #1

There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.

Reason #2

When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars() function is one such example. Though there are optional arguments to htmlspecialchars() that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.

TSQL DATETIME ISO 8601

this is very old question, but since I came here while searching worth putting my answer.

SELECT DATEPART(ISO_WEEK,'2020-11-13') AS ISO_8601_WeekNr

What is time_t ultimately a typedef to?

time_t is of type long int on 64 bit machines, else it is long long int.

You could verify this in these header files:

time.h: /usr/include
types.h and typesizes.h: /usr/include/x86_64-linux-gnu/bits

(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)

1)In time.h

typedef __time_t time_t;

2)In types.h

# define __STD_TYPE     typedef  
__STD_TYPE __TIME_T_TYPE __time_t;  

3)In typesizes.h

#define __TIME_T_TYPE       __SYSCALL_SLONG_TYPE  
#if defined __x86_64__ && defined __ILP32__  
# define __SYSCALL_SLONG_TYPE   __SQUAD_TYPE  
#else
# define __SYSCALL_SLONG_TYPE   __SLONGWORD_TYPE
#endif  

4) Again in types.h

#define __SLONGWORD_TYPE    long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE       __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE       long int  

#if __WORDSIZE == 64
typedef long int __quad_t;  
#else
__extension__ typedef long long int __quad_t;

How to read values from properties file?

In configuration class

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
   @Autowired
   Environment env;

   @Bean
   public TestBean testBean() {
       TestBean testBean = new TestBean();
       testBean.setName(env.getProperty("testbean.name"));
       return testBean;
   }
}

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

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

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


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

How to set a cell to NaN in a pandas dataframe

As of pandas 1.0.0, you no longer need to use numpy to create null values in your dataframe. Instead you can just use pandas.NA (which is of type pandas._libs.missing.NAType), so it will be treated as null within the dataframe but will not be null outside dataframe context.

Java: parse int value from a char

Using binary AND with 0b1111:

String element = "el5";

char c = element.charAt(2);

System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5

// '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
// '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
// '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
// '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
// '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
// '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
// '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
// '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
// '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9

passing form data to another HTML page

*first html page*

<form action="display.jsp" >
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>


*Second html page*
<body>
<p>The serial number is:<%=request.getParameter("serialNumber") %></p>
</body>


you will get the value of the textbox on another page.

Why is "throws Exception" necessary when calling a function?

Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

Applying styles to tables with Twitter Bootstrap

you can Add contextual classes to every single row as follows:

<tr class="table-success"></tr>
<tr class="table-error"></tr>
<tr class="table-warning"></tr>
<tr class="table-info"></tr>
<tr class="table-danger"></tr>

You can also add them to table data same as above

You can set your table size by setting classes as table-sm and so on.

You can add custom classes and add your own styling:

<table class="table">
  <thead style = "color:red;background-color:blue">
    <tr>
      <th></th>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>   
      <td>Asdf</td>
      <td>qwerty</td>
    </tr>
  </tbody>
</table>

This way you can add custom styling. I have showed inline styling just for example how it works, you can add classes and call them in your css as well.

Is there any boolean type in Oracle databases?

No, there isn't a boolean type in Oracle Database, but you can do this way:

You can put a check constraint on a column.

If your table hasn't a check column, you can add it:

ALTER TABLE table_name
ADD column_name_check char(1) DEFAULT '1';

When you add a register, by default this column get 1.

Here you put a check that limit the column value, just only put 1 or 0

ALTER TABLE table_name ADD
CONSTRAINT name_constraint 
column_name_check (ONOFF in ( '1', '0' ));

Sound effects in JavaScript / HTML5

You may also want to use this to detect HTML 5 audio in some cases:

http://diveintohtml5.ep.io/everything.html

HTML 5 JS Detect function

function supportsAudio()
{
    var a = document.createElement('audio'); 
    return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
}

Optional Parameters in Web Api Attribute Routing

Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:

[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]

The ? character is put always before the last } character

For more information see: Optional URI Parameters and Default Values

Docker - a way to give access to a host USB or serial device?

With latest versions of docker, this is enough:

docker run -ti --privileged ubuntu bash

It will give access to all system resources (in /dev for instance)

How do I use Ruby for shell scripting?

Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.

So, if you had a script called my_shell_script:

#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
  puts value
end

...make it executable (as others have mentioned):

chmod u+x my_shell_script

And call it like so:

> ./my_shell_script one two three four five

You'd get this:

I was passed: 
one
two
three
four
five

The arguments work nicely with filename expansion:

./my_shell_script *

I was passed: 
a_file_in_the_current_directory
another_file    
my_shell_script
the_last_file

Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.

How to do while loops with multiple conditions

use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish

while 1:
  if condition1 and condition2:
      break
  ...
  ...
  if condition3: break
  ...
  ...

How can I make a program wait for a variable change in javascript?

No you would have to create your own solution. Like using the Observer design pattern or something.

If you have no control over the variable or who is using it, I'm afraid you're doomed. EDIT: Or use Skilldrick's solution!

Mike

PHP Multidimensional Array Searching (Find key by specific value)

I would do like below, where $products is the actual array given in the problem at the very beginning.

print_r(
  array_search("breville-variable-temperature-kettle-BKE820XL", 
  array_map(function($product){return $product["slug"];},$products))
);

How do I set Tomcat Manager Application User Name and Password for NetBeans?

When you're launching tomcat server from netbeans IDE you need to check in menu "tools->servers" on connection tab for tomcat server - there is catalina base directory. And you need to include something like:

 <role rolename="manager"/>
  <user username="admin" password="admin" roles="manager"/>

at file

\CATALINA_BASE\conf\tomcat-users.xml

or use username automatically generated by IDE with description already placed in this file or on connection tab

For Manager Apps : GUI access:

<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>

TypeError : Unhashable type

A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

A list doesn't use a hash for indexing, so it isn't restricted to hashable items.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I came across a similar problem on my mac OSX. After a series of trial and error attempts I finally resolved it.

My ~/.bash_profile looked like this

export M2_HOME=/Users/xyz/maven-3.x/bin
export PATH=$PATH:$M2_HOME

and when I tried to echo M2_HOME from the terminal, it showed me the correct path but when I tried to fire any maven command like mvn clean or mvn install, it always gave the same problem

Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I solved this issue by changing my M2_HOME to this

export M2_HOME=/Users/xyz/maven-3.x
export PATH=$PATH:$M2_HOME/bin

And voila ! It started working ! Just by moving the position of /bin from M2_HOME to in front of the PATH

offsetting an html anchor to adjust for fixed header

how about hidden span tags with linkable IDs that provide the height of the navbar:

#head1 {
  padding-top: 60px;
  height: 0px;
  visibility: hidden;
}


<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>

heres the fiddle: http://jsfiddle.net/N6f2f/7

Markdown and image alignment

this work for me

<p align="center">
 <img src="/LogoOfficial.png" width="300" >
</p>

How to clear APC cache entries?

if you run fpm under ubuntu, need to run the code below (checked on 12 and 14)

service php5-fpm reload

HTML Submit-button: Different value / button-text?

I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.

How to check if a key exists in Json Object and get its value

Try

private boolean hasKey(JSONObject jsonObject, String key) {
    return jsonObject != null && jsonObject.has(key);
}

  try {
        JSONObject jsonObject = new JSONObject(yourJson);
        if (hasKey(jsonObject, "labelData")) {
            JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
            if (hasKey(labelDataJson, "video")) {
                String video = labelDataJson.getString("video");
            }
        }
    } catch (JSONException e) {

    }

Including external HTML file to another HTML file

Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.

<object data="html/stuff_to_include.html"> 
    Your browser doesn’t support the object tag. 
</object>

more info at http://www.w3schools.com/tags/tag_object.asp

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:

https://www.google.com/search?g=[value from input-field]

But when you search with google, you notice the following URL:

https://www.google.nl/search?q=google+search+bar

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

How can I delete one element from an array by value

I improved Niels's solution

class Array          
  def except(*values)
    self - values
  end    
end

Now you can use

[1, 2, 3, 4].except(3, 4) # return [1, 2]
[1, 2, 3, 4].except(4)    # return [1, 2, 3]

Why can't Python parse this JSON data?

As a python3 user,

The difference between load and loads methods is important especially when you read json data from file.

As stated in the docs:

json.load:

Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads:

json.loads: Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

json.load method can directly read opened json document since it is able to read binary file.

with open('./recipes.json') as data:
  all_recipes = json.load(data)

As a result, your json data available as in a format specified according to this conversion table:

https://docs.python.org/3.7/library/json.html#json-to-py-table

Put search icon near textbox using bootstrap

You can do it in pure CSS using the :after pseudo-element and getting creative with the margins.

Here's an example, using Font Awesome for the search icon:

_x000D_
_x000D_
.search-box-container input {_x000D_
  padding: 5px 20px 5px 5px;_x000D_
}_x000D_
_x000D_
.search-box-container:after {_x000D_
    content: "\f002";_x000D_
    font-family: FontAwesome;_x000D_
    margin-left: -25px;_x000D_
    margin-right: 25px;_x000D_
}
_x000D_
<!-- font awesome -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="search-box-container">_x000D_
  <input type="text" placeholder="Search..."  />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I set a TTL for @Cacheable

I use life hacking like this

@Configuration
@EnableCaching
@EnableScheduling
public class CachingConfig {
    public static final String GAMES = "GAMES";
    @Bean
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(GAMES);

        return cacheManager;
    }

@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 ,  initialDelay = 500)
public void reportCacheEvict() {
    System.out.println("Flush Cache " + dateFormat.format(new Date()));
}

PHP max_input_vars

You can add it to php.ini and it should work - just tested it on PHP 5.3.6.

Vue.js dynamic images not working

I got this working by following code

  getImgUrl(pet) {
    var images = require.context('../assets/', false, /\.png$/)
    return images('./' + pet + ".png")
  }

and in HTML:

<div class="col-lg-2" v-for="pic in pics">
   <img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>

But not sure why my earlier approach did not work.