Programs & Examples On #Phishing

Should I use the Reply-To header when sending emails as a service to others?

After reading all of this, I might just embed a hyperlink in the email body like this:

To reply to this email, click here <a href="mailto:...">[email protected]</a>

How to validate phone number in laravel 5.2?

I used the code below, and it works

'PHONE' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:9',

How can I execute Python scripts using Anaconda's version of Python?

I like to run a "bare-bones" version of Python 2 to verify scripts that I create for other people without an advanced python setup. But Anaconda and Python 3 have a lot of nice features. To enjoy both things on the same computer I do this on my Windows computer which allows me to easily switch.

C:\Users>python --version
Python 2.7.11

C:\Users>conda create --name p3 python=3

C:\Users>conda info --envs
Using Anaconda Cloud api site https://api.anaconda.org
# conda environments:
#
p3                       C:\Anaconda3\envs\p3
root                  *  C:\Anaconda3

C:\Users>activate p3
Deactivating environment "C:\Anaconda3"...
Activating environment "C:\Anaconda3\envs\p3"...

[p3] C:\Users>python --version
Python 3.5.1 :: Continuum Analytics, Inc.

For more info: http://conda.pydata.org/docs/test-drive.html

JPA and Hibernate - Criteria vs. JPQL or HQL

I don't want to kick a dead horse here, but it is important to mention that Criteria queries are now deprecated. Use HQL.

Angular 5 - Copy to clipboard

As of Angular Material v9, it now has a clipboard CDK

Clipboard | Angular Material

It can be used as simply as

<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>

Using CSS how to change only the 2nd column of a table

on this web http://quirksmode.org/css/css2/columns.html i found that easy way

<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..

How to update/modify an XML file in python?

While I agree with Tim and Oben Sonne that you should use an XML library, there are ways to still manipulate it as a simple string object.

I likely would not try to use a single file pointer for what you are describing, and instead read the file into memory, edit it, then write it out.:

inFile = open('file.xml', 'r')
data = inFile.readlines()
inFile.close()
# some manipulation on `data`
outFile = open('file.xml', 'w')
outFile.writelines(data)
outFile.close()

How to get a list of column names on Sqlite3 database?

PRAGMA table_info(table_name);

will get you a list of all the column names.

Creating a new ArrayList in Java

Fixed the code for you:

ArrayList<Class> myArray= new ArrayList<Class>();

Is there a concurrent List in Java's JDK?

ConcurrentLinkedQueue

If you don't care about having index-based access and just want the insertion-order-preserving characteristics of a List, you could consider a java.util.concurrent.ConcurrentLinkedQueue. Since it implements Iterable, once you've finished adding all the items, you can loop over the contents using the enhanced for syntax:

Queue<String> globalQueue = new ConcurrentLinkedQueue<String>();

//Multiple threads can safely call globalQueue.add()...

for (String href : globalQueue) {
    //do something with href
}

Subtract a value from every number in a list in Python?

This will work:

for i in range(len(a)):
  a[i] -= 13

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

I had success doing it this way:

db.collection.update(  { _id:...} , { $set: { 'key.another_key' : new_info  } } );

I have a function that handles my profile updates dynamically

function update(prop, newVal) {
  const str = `profile.${prop}`;
  db.collection.update( { _id:...}, { $set: { [str]: newVal } } );
}

Note: 'profile' is specific to my implementation, it is just the string of the key that you would like to modify.

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.


Prophylactic measures to prevent you getting the error again

The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.

Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.


Common syntactic mistakes that generate these errors

Mismatched parentheses, braces or brackets

If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.

{}}
## Error: unexpected '}' in "{}}"
{{}} # OK

Missing * when doing multiplication

This is a common mistake by mathematicians.

5x
Error: unexpected symbol in "5x"
5*x # OK

Not wrapping if, for, or return values in parentheses

This is a common mistake by MATLAB users. In R, if, for, return, etc., are functions, so you need to wrap their contents in parentheses.

if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK

Not using multiple lines for code

Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.

x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK

else starting on a new line

In an if-else statement, the keyword else must appear on the same line as the end of the if block.

if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"    
if(TRUE) 1 else 2 # OK
if(TRUE) 
{
  1
} else            # also OK
{
  2
}

= instead of ==

= is used for assignment and giving values to function arguments. == tests two values for equality.

if(x = 0) {}
## Error: unexpected '=' in "if(x ="    
if(x == 0) {} # OK

Missing commas between arguments

When calling a function, each argument must be separated by a comma.

c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK

Not quoting file paths

File paths are just strings. They need to be wrapped in double or single quotes.

path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK

Quotes inside strings

This is a common problem when trying to pass quoted values to the shell via system, or creating quoted xPath or sql queries.

Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.

"x"y"
## Error: unexpected symbol in ""x"y"   
"x\"y" # OK
'x"y'  # OK  

Using curly quotes

So-called "smart" quotes are not so smart for R programming.

path.expand(“~”)
## Error: unexpected input in "path.expand(“"    
path.expand("~") # OK

Using non-standard variable names without backquotes

?make.names describes what constitutes a valid variable name. If you create a non-valid variable name (using assign, perhaps), then you need to access it with backquotes,

assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK

This also applies to column names in data frames created with check.names = FALSE.

dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y`   # also OK

It also applies when passing operators and other special values to functions. For example, looking up help on %in%.

?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK

Sourcing non-R code

The source function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table.

source(textConnection("x y"))
## Error in source(textConnection("x y")) : 
##   textConnection("x y"):1:3: unexpected symbol
## 1: x y
##       ^

Corrupted RStudio desktop file

RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.


Using expression without paste in mathematical plot annotations

When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath page. Otherwise the contents should be contained inside a call to paste.

plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK

How to change an image on click using CSS alone?

No, you will need scripting to place a click Event handler on the Element that does what you want.

How to pass arguments to addEventListener listener function?

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

function() { some_function(someVar); } 

was created.

Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

Android ListView with different layouts for each row

In your custom array adapter, you override the getView() method, as you presumably familiar with. Then all you have to do is use a switch statement or an if statement to return a certain custom View depending on the position argument passed to the getView method. Android is clever in that it will only give you a convertView of the appropriate type for your position/row; you do not need to check it is of the correct type. You can help Android with this by overriding the getItemViewType() and getViewTypeCount() methods appropriately.

When should I use nil and NULL in Objective-C?

To expand on a comment from @cobbal:

MacTypes.h contains:

#ifndef nil
   #define nil NULL
#endif

What is @ModelAttribute in Spring MVC?

So I will try to explain it in simpler way. Let's have:

public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }
}

As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments. And of course we can have both use at the same time in one controller.

1.Method annotation

@ModelAttribute(“cities”)
 public List<String> checkOptions(){
 return new Arrays.asList(new[]{“Sofia”,”Pleven","Ruse”});//and so on
}

Purpose of such method is to add attribute in the model. So in our case cities key will have the list new Arras.asList(new[]{“Sofia”,”Pleven","Ruse”}) as value in the Model (you can think of Model as map(key:value)). @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.

Here we want to add to the Model common information which will be used in the form to display to the user. For example it can be used to fill a HTML select:

enter image description here

2.Method argument

public String findPerson(@ModelAttriute(value="person") Person person) {
    //..Some logic with person
    return "person.jsp";
}

An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. So in this case we expect that we have in the Model person object as key and we want to get its value and put it to the method argument Person person. If such does not exists or (sometimes you misspell the (value="persson")) then Spring will not find it in the Model and will create empty Person object using its defaults. Then will take the request parameters and try to data bind them in the Person object using their names.

name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&

So we have name and it will be bind to Person.name using setName(String name). So in

//..Some logic with person

we have access to this filled name with value "Dimitrij".

Of course Spring can bind more complex objects like Lists, Maps, List of Sets of Maps and so on but behind the scene it makes the data binding magic.

  1. We can have at the same time model annotated method and request method handler with @ModelAttribute in the arguments. Then we have to union the rules.

  2. Of course we have tons of different situations - @ModelAttribute methods can also be defined in an @ControllerAdvice and so on...

Does HTTP use UDP?

In theory yes it is possible to use UDP for http but that might be problematic. Say for instance in your example a mp3 or a video is being streamed there will be problem of ordering and some bits might go missing as UDP is not connection oriented there is no retransmit mechanism.

Difference between Hashing a Password and Encrypting it

As correct as the other answers may be, in the context that the quote was in, hashing is a tool that may be used in securing information, encryption is a process that takes information and makes it very difficult for unauthorized people to read/use.

Get the new record primary key ID from MySQL insert query?

If you are using PHP: On a PDO object you can simple invoke the lastInsertId method after your insert.

Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

How to install 2 Anacondas (Python 2 and 3) on Mac OS

This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.

  1. Install anaconda. Latest version can be found here
  2. Open the navigator by typing anaconda-navigator in terminal
  3. Open environments. Click on create and then choose your python version in that.
  4. Now new environment will be created for your python version and you can install the IDE's(which are listed there) just by clicking install in that.
  5. Launch the IDE in your environment so that that IDE will use the specified version for that environment.

Hope it helps!!

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

How to get parameters from the URL with JSP

example you wanted to delete the subject record with its subject_id

@RequestMapping(value="subject_setup/delete/{subjectid}",method = RequestMethod.GET)
public ModelAndView delete(@PathVariable int subjectid) {
    subjectsDao.delete(subjectid);
    return new ModelAndView("redirect:/subject_setup");
}

and the parameter will be used for input on your query

public int delete(int subjectid) {
    String sql = "update tbl_subject set isdeleted= '1' where id = "+subjectid+"";
    return template.update(sql);
}

.map() a Javascript ES6 Map?

If you don't want to convert the entire Map into an array beforehand, and/or destructure key-value arrays, you can use this silly function:

_x000D_
_x000D_
/**_x000D_
 * Map over an ES6 Map._x000D_
 *_x000D_
 * @param {Map} map_x000D_
 * @param {Function} cb Callback. Receives two arguments: key, value._x000D_
 * @returns {Array}_x000D_
 */_x000D_
function mapMap(map, cb) {_x000D_
  let out = new Array(map.size);_x000D_
  let i = 0;_x000D_
  map.forEach((val, key) => {_x000D_
    out[i++] = cb(key, val);_x000D_
  });_x000D_
  return out;_x000D_
}_x000D_
_x000D_
let map = new Map([_x000D_
  ["a", 1],_x000D_
  ["b", 2],_x000D_
  ["c", 3]_x000D_
]);_x000D_
_x000D_
console.log(_x000D_
  mapMap(map, (k, v) => `${k}-${v}`).join(', ')_x000D_
); // a-1, b-2, c-3
_x000D_
_x000D_
_x000D_

how to merge 200 csv files in Python

You could import csv then loop through all the CSV files reading them into a list. Then write the list back out to disk.

import csv

rows = []

for f in (file1, file2, ...):
    reader = csv.reader(open("f", "rb"))

    for row in reader:
        rows.append(row)

writer = csv.writer(open("some.csv", "wb"))
writer.writerows("\n".join(rows))

The above is not very robust as it has no error handling nor does it close any open files. This should work whether or not the the individual files have one or more rows of CSV data in them. Also I did not run this code, but it should give you an idea of what to do.

Check if passed argument is file or directory in Bash

At least write the code without the bushy tree:

#!/bin/bash

PASSED=$1

if   [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
     exit 1
fi

When I put that into a file "xx.sh" and create a file "xx sh", and run it, I get:

$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$

Given that you are having problems, you should debug the script by adding:

ls -l "${PASSED}"

This will show you what ls thinks about the names you pass the script.

Fastest way to check if a file exist using standard C++/C++11/C?

You can use std::ifstream, funcion like is_open, fail, for example as below code (the cout "open" means file exist or not):

enter image description here

enter image description here

cited from this answer

jQuery - Disable Form Fields

try this

$("#inp").focus(function(){$("#sel").attr('disabled','true');});

$("#inp").blur(function(){$("#sel").removeAttr('disabled');});

vice versa for the select also.

$.focus() not working

I also had this problem. The solution that worked in my case was using the tabindex property on the HTML element.

I was using ng-repeat for some li elements inside a list and I was not able to bring focus to the first li using .focus(), so I simply added the tabindex attribute to each li during the loop.

so now <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>

That +1 was index starts from 0. Also make sure that the element is present in DOM before calling the .focus() function

I hope this helps.

How do I get row id of a row in sql server

SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id is an IDENTITY column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON). If employee_id is an IDENTITY column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:

SELECT 
   ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID, 
   EMPLOYEE_ID,
   EMPLOYEE_NAME 
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;

You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).

ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743 
-- wow, who named this?
  ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES() - e.g. you may have to revisit your code and define a proper, explicit column list.

Oracle 10g: Extract data (select) from XML (CLOB Type)

In case of :

<?xml version="1.0" encoding="iso-8859-1"?>
<info xmlns="http://namespaces.default" xmlns:ns2="http://namespaces.ns2" >
    <id> 954 </id>
    <idboss> 954 </idboss>
    <name> Fausto </name>
    <sorname> Anonimo </sorname>
    <phone> 040000000 </phone>
    <fax> 040000001 </fax>
</info>

Query :

Select *
from xmltable(xmlnamespaces(default 'http://namespaces.default'
                              'http://namespaces.ns2' as "ns",
                       ), 
                '/info'
                passing xmltype.createxml(xml) 
                columns id varchar2(10) path '/id',
                        idboss varchar2(500) path '/idboss',
                        etc....

                ) nice_xml_table

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

How can I set the PATH variable for javac so I can manually compile my .java works?

That would be:

set "PATH=%PATH%;C:\Program Files\Java\jdk1.6.0_18\bin"

You can also append ;C:\Program Files\Java\jdk1.6.0_18\bin to the PATH in the user environment dialog. That would allow you to use javac and other java tools directly form any cmd shell without setting the path first. The user environment dialog used to be somewhere in the system properties in XP, I have no idea where it is in Windows 7.

How do you set the EditText keyboard to only consist of numbers on Android?

Place the below lines in your <EditText>:

android:digits="0123456789"
android:inputType="phone"

Strangest language feature

The C preprocessor and its usages. Specifically preprocessor metaprogramming and using the preprocessor to generate portable code -- total mindfcuk.

How to insert data into SQL Server

string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();

Eclipse error "Could not find or load main class"

If You are using eclipse then the following steps will solve your problem:

Go to Run -> Run Configurations -> Main Class Search -> Locate your class manually -> Apply -> Run

Image resizing in React Native

Use Resizemode with 'cover' or 'contain' and set the height and with of the Image.

Passing Objects By Reference or Value in C#

Objects aren't passed at all. By default, the argument is evaluated and its value is passed, by value, as the initial value of the parameter of the method you're calling. Now the important point is that the value is a reference for reference types - a way of getting to an object (or null). Changes to that object will be visible from the caller. However, changing the value of the parameter to refer to a different object will not be visible when you're using pass by value, which is the default for all types.

If you want to use pass-by-reference, you must use out or ref, whether the parameter type is a value type or a reference type. In that case, effectively the variable itself is passed by reference, so the parameter uses the same storage location as the argument - and changes to the parameter itself are seen by the caller.

So:

public void Foo(Image image)
{
    // This change won't be seen by the caller: it's changing the value
    // of the parameter.
    image = Image.FromStream(...);
}

public void Foo(ref Image image)
{
    // This change *will* be seen by the caller: it's changing the value
    // of the parameter, but we're using pass by reference
    image = Image.FromStream(...);
}

public void Foo(Image image)
{
    // This change *will* be seen by the caller: it's changing the data
    // within the object that the parameter value refers to.
    image.RotateFlip(...);
}

I have an article which goes into a lot more detail in this. Basically, "pass by reference" doesn't mean what you think it means.

Subtract minute from DateTime in SQL Server 2005

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); 

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); 

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)

How to run Java program in terminal with external library JAR

You can do :

1) javac -cp /path/to/jar/file Myprogram.java

2) java -cp .:/path/to/jar/file Myprogram

So, lets suppose your current working directory in terminal is src/Report/

javac -cp src/external/myfile.jar Reporter.java

java -cp .:src/external/myfile.jar Reporter

Take a look here to setup Classpath

Getting the current date in SQL Server?

As you are using SQL Server 2008, go with Martin's answer.

If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

SQLFiddle

Downloading Java JDK on Linux via wget is shown license page instead

Updated for JDK 8u171 RPM

wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u171-b11/512cd62ec5174c3487ac17c61aaa89e8/jdk-8u171-linux-x64.rpm

Outdated links below

Updated for JDK 8u161 RPM

wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u161-b12/2f38c3b165be4555a1fa6e98c45e0808/jdk-8u161-linux-x64.rpm

Updated for JDK 8u152 RPM

wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u152-b16/aa0333dd3019491ca4f6ddbe78cdb6d0/jdk-8u152-linux-x64.rpm

Updated for JDK 8u144 RPM

wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.rpm

Updated for JDK 8u131 RPM

wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm

Updated for JDK 8u121 RPM

wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u121-b13/e9e7ea248e2c4826b92b3f075a80e441/jdk-8u121-linux-x64.rpm

GitHub README.md center image

if modifying the image is not a problem for you, and

if you know the approximate width of the container that will display your markdown, and

if your image is used in one place only (for example a README used only in GitHub),

then you can edit your image in an image editor and pad it equally on both sides.

Before padding:
Image before edit

After padding:
Image after edit

Original image (width = 250px):
Original image

Padded image (width = 660px):
Padded image

What is the difference between "expose" and "publish" in Docker?

Most people use docker compose with networks. The documentation states:

The Docker network feature supports creating networks without the need to expose ports within the network, for detailed information see the overview of this feature).

Which means that if you use networks for communication between containers you don't need to worry about exposing ports.

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

PHPExcel auto size column width

// Auto-size columns for all worksheets
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    foreach ($worksheet->getColumnIterator() as $column) {
        $worksheet
            ->getColumnDimension($column->getColumnIndex())
            ->setAutoSize(true);
    } 
}

What are some alternatives to ReSharper?

I think that CodeRush has a free, limited version, too. I ended up going with ReSharper, and I still recommend it, even though some of the functionality is in Visual Studio 2010. There are just some things that make it worth it.

Keep in mind that you don't need the full ReSharper license if you only code in one language. I have the C# version, and it's cheaper.

HTML5 Video Autoplay not working correctly

//You might want to add some scripts if your software doesn't support jQuery or giving any reference type error.

//Use above scripts only if the software you are working on doesn't support jQuery.

$(document).ready(function() { //Change the location of your mp3 or any music file. var source = "../Assets/music.mp3"; var audio = new Audio(); audio.src = source; audio.autoplay = true; });

What is the easiest way to remove all packages installed by pip?

This works with the latest. I think it's the shortest and most declarative way to do it.

virtualenv --clear MYENV

But usually I just delete and recreate the virtualenv since immutability rules!

IIS7 Permissions Overview - ApplicationPoolIdentity

Remember to use the server's local name, not the domain name, when resolving the name

IIS AppPool\DefaultAppPool

(just a reminder because this tripped me up for a bit):enter image description here

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

'do...while' vs. 'while'

This is my personal opinion, but this question begs for an answer rooted in experience:

  • I have been programming in C for 38 years, and I never use do / while loops in regular code.

  • The only compelling use for this construct is in macros where it can wrap multiple statements into a single statement via a do { multiple statements } while (0)

  • I have seen countless examples of do / while loops with bogus error detection or redundant function calls.

  • My explanation for this observation is programmers tend to model problems incorrectly when they think in terms of do / while loops. They either miss an important ending condition or they miss the possible failure of the initial condition which they move to the end.

For these reasons, I have come to believe that where there is a do / while loop, there is a bug, and I regularly challenge newbie programmers to show me a do / while loop where I cannot spot a bug nearby.

This type of loop can be easily avoided: use a for (;;) { ... } and add the necessary termination tests where they are appropriate. It is quite common that there need be more than one such test.

Here is a classic example:

/* skip the line */
do {
    c = getc(fp);
} while (c != '\n');

This will fail if the file does not end with a newline. A trivial example of such a file is the empty file.

A better version is this:

int c;  // another classic bug is to define c as char.
while ((c = getc(fp)) != EOF && c != '\n')
    continue;

Alternately, this version also hides the c variable:

for (;;) {
    int c = getc(fp);
    if (c == EOF || c == '\n')
        break;
}

Try searching for while (c != '\n'); in any search engine, and you will find bugs such as this one (retrieved June 24, 2017):

In ftp://ftp.dante.de/tex-archive/biblio/tib/src/streams.c , function getword(stream,p,ignore), has a do / while and sure enough at least 2 bugs:

  • c is defined as a char and
  • there is a potential infinite loop while (c!='\n') c=getc(stream);

Conclusion: avoid do / while loops and look for bugs when you see one.

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

Assign variable in if condition statement, good practice or not?

You can do this in Java too. And no, it's not a good practice. :)

(And use the === in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

functional way to iterate over range (ES6/7)

One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:

Array(8).fill().map((_, i) => i * i);

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

Postgresql - unable to drop database because of some auto connections to DB

In my case, I am using AWS Redshift (based on Postgres). And it appears there are no other connections to the DB, but I am getting this same error.

ERROR:  database "XYZ" is being accessed by other users

In my case, it seems the database cluster is still doing some processing on the database, and while there are no other external/user connections, the database is still internally in use. I found this by running the following:

SELECT * FROM stv_sessions;

So my hack was to write a loop in my code, looking for rows with my database name in it. (of course the loop is not infinite, and is a sleepy loop, etc)

SELECT * FROM stv_sessions where db_name = 'XYZ';

If rows found, proceed to delete each PID, one by one.

SELECT pg_terminate_backend(PUT_PID_HERE);

If no rows found, proceed to drop the database

DROP DATABASE XYZ;

Note: In my case, I am writing Java unit/system tests, where this could be considered acceptable. This is not acceptable for production code.


Here is the complete hack, in Java (ignore my test/utility classes).

  int i = 0;
  while (i < 10) {
    try {
      i++;
      logStandardOut("First try to delete session PIDs, before dropping the DB");
      String getSessionPIDs = String.format("SELECT stv_sessions.process, stv_sessions.* FROM stv_sessions where db_name = '%s'", dbNameToReset);
      ResultSet resultSet = databaseConnection.execQuery(getSessionPIDs);
      while (resultSet.next()) {
        int sessionPID = resultSet.getInt(1);
        logStandardOut("killPID: %s", sessionPID);
        String killSessionPID = String.format("select pg_terminate_backend(%s)", sessionPID);
        try {
          databaseConnection.execQuery(killSessionPID);
        } catch (DatabaseException dbEx) {
          //This is most commonly when a session PID is transient, where it ended between my query and kill lines
          logStandardOut("Ignore it, you did your best: %s, %s", dbEx.getMessage(), dbEx.getCause());
        }
      }

      //Drop the DB now
      String dropDbSQL = String.format("DROP DATABASE %s", dbNameToReset);
      logStandardOut(dropDbSQL);
      databaseConnection.execStatement(dropDbSQL);
      break;
    } catch (MissingDatabaseException ex) {
      //ignore, if the DB was not there (to be dropped)
      logStandardOut(ex.getMessage());
      break;
    } catch (Exception ex) {
      logStandardOut("Something went wrong, sleeping for a bit: %s, %s", ex.getMessage(), ex.getCause());
      sleepMilliSec(1000);
    }
  }

Importing Maven project into Eclipse

Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:

  • File > Projects from File System... - This works for Eclipse projects (containing the file .project) as well as for non-Eclipse projects that only contain the file pom.xml.
  • If importing from a Git repository, in the Git Repositories view right-click the repository node, one folder or multiple selected folders in the Working Tree and choose Import Projects.... This opens the same dialog, but you don't have to select the directory.

Add Keypair to existing EC2 instance

Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.

stackoverflow.com/questions/7881469/change-key-pair-for-ec2-instance

Laravel, sync() - how to sync an array and also pass additional pivot fields?

This works for me

foreach ($photos_array as $photo) {

    //collect all inserted record IDs
    $photo_id_array[$photo->id] = ['type' => 'Offence'];  

}

//Insert into offence_photo table
$offence->photos()->sync($photo_id_array, false);//dont delete old entries = false

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

Foreign key constraints: When to use ON UPDATE and ON DELETE

Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.

For example if you delete a record using ORM, and your DELETE CASCADE will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

I ran into this problem and inspired by @Jeremy Cook's answer, I bit the bullet to find out what the heck caused IIS 7 Integrated mode to not like my web.config. Here's my scenario:

  1. Web API (version 4.0.030506.0 aka the old one)
  2. .NET 4.0
  3. Attribute Routing 3.5.6 for Web API [spoiler alert: it was this guy!]

I wanted to use attribute routing in a project that (unfortunately) had to use .NET 4 and hence could not use Web API 2.2 (which needs .NET 4.5). The well meaning NuGet package added this section under the <system.web> section:

<system.web>
<httpHandlers>
      <add verb="*" path="routes.axd" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" />
    </httpHandlers>
</system.web>

[I say well meaning, because this part is required on older versions of IIS]

Removing this section got me past the HTTP 500.23!!

Summary: I second Jeremy's words that it is important to understand why things don't work rather than just "masking the symptom". Even if you have to mask the symptom, you know what you are doing (and why) :-)

How to change plot background color?

One method is to manually set the default for the axis background color within your script (see Customizing matplotlib):

import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'

This is in contrast to Nick T's method which changes the background color for a specific axes object. Resetting the defaults is useful if you're making multiple different plots with similar styles and don't want to keep changing different axes objects.

Note: The equivalent for

fig = plt.figure()
fig.patch.set_facecolor('black')

from your question is:

plt.rcParams['figure.facecolor'] = 'black'

How to prevent Google Colab from disconnecting?

This one worked for me (it seems like they changed the button classname or id) :

_x000D_
_x000D_
function ClickConnect(){_x000D_
    console.log("Working"); _x000D_
    document.querySelector("colab-connect-button").click() _x000D_
}_x000D_
setInterval(ClickConnect,60000)
_x000D_
_x000D_
_x000D_

How to show live preview in a small popup of linked page on mouse over on link?

You can use an iframe to display a preview of the page on mouseover:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
This live preview for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
    <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
    </iframe>_x000D_
  </div> _x000D_
remains open on mouseover.
_x000D_
_x000D_
_x000D_

Here's an example with multiple live previews:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
Live previews for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
and <a href="https://www.jquery.com/">JQuery</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://www.jquery.com/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
will appear when these links are moused over.
_x000D_
_x000D_
_x000D_

PHP max_input_vars

You need to uncomment max_input_vars value in php.ini file and increase it (exp. 2000), also dont forget to restart your server this will help for 99,99%.

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

Using SSIS BIDS with Visual Studio 2012 / 2013

Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.

The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

Creating a constant Dictionary in C#

Just another idea since I am binding to a winforms combobox:

public enum DateRange {
    [Display(Name = "None")]
    None = 0,
    [Display(Name = "Today")]
    Today = 1,
    [Display(Name = "Tomorrow")]
    Tomorrow = 2,
    [Display(Name = "Yesterday")]
    Yesterday = 3,
    [Display(Name = "Last 7 Days")]
    LastSeven = 4,
    [Display(Name = "Custom")]
    Custom = 99
    };

int something = (int)DateRange.None;

To get the int value from the display name from:

public static class EnumHelper<T>
{
    public static T GetValueFromName(string name)
    {
        var type = typeof(T);
        if (!type.IsEnum) throw new InvalidOperationException();

        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DisplayAttribute)) as DisplayAttribute;
            if (attribute != null)
            {
                if (attribute.Name == name)
                {
                    return (T)field.GetValue(null);
                }
            }
            else
            {
                if (field.Name == name)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentOutOfRangeException("name");
    }
}

usage:

var z = (int)EnumHelper<DateRange>.GetValueFromName("Last 7 Days");

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

Email and phone Number Validation in android

Use Pattern package in Android to match the input validation for email and phone

Do like

android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();

Multiple Where clauses in Lambda expressions

Can be

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty && l.InternalName != String.Empty)

or

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty)
     .Where(l => l.InternalName != String.Empty)

When you are looking at Where implementation, you can see it accepts a Func(T, bool); that means:

  • T is your IEnumerable type
  • bool means it needs to return a boolean value

So, when you do

.Where(l => l.InternalName != String.Empty)
//     ^                   ^---------- boolean part
//     |------------------------------ "T" part

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Get total size of file in bytes

public static void main(String[] args) {
        try {
            File file = new File("test.txt");
            System.out.println(file.length());
        } catch (Exception e) {
        }
    }

How do I set the visibility of a text box in SSRS using an expression?

the rdl file content:

<Visibility><Hidden>=Parameters!casetype.Value=300</Hidden></Visibility>

so the text box will hidden, if your expression is true.

WAMP won't turn green. And the VCRUNTIME140.dll error

As Oriol said, you need the following redistributables before installing WAMP.

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

How to Check whether Session is Expired or not in asp.net

I use the @Adi-lester answer and add some methods.

Method to verify if Session is Alive

public static void SessionIsAlive(HttpSessionStateBase Session)
{
    if (Session.Contents.Count == 0)
    {
        Response.Redirect("Timeout.html"); 
    }
    else
    {
        InitializeControls();
    }
}

Create session var in Page Load

protected void Page_Load(object sender, EventArgs e)
{
    Session["user_id"] = 1;
}

Create SaveData method (but you can use it in all methods)

protected void SaveData()
{
    // Verify if Session is Alive
    SessionIsAlive(Session);

    //Save Data Process
    // bla
    // bla
    // bla
}

How do I record audio on iPhone with AVAudioRecorder?

Actually, there are no examples at all. Here is my working code. Recording is triggered by the user pressing a button on the navBar. The recording uses cd quality (44100 samples), stereo (2 channels) linear pcm. Beware: if you want to use a different format, especially an encoded one, make sure you fully understand how to set the AVAudioRecorder settings (read carefully the audio types documentation), otherwise you will never be able to initialize it correctly. One more thing. In the code, I am not showing how to handle metering data, but you can figure it out easily. Finally, note that the AVAudioRecorder method deleteRecording as of this writing crashes your application. This is why I am removing the recorded file through the File Manager. When recording is done, I save the recorded audio as NSData in the currently edited object using KVC.

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]


- (void) startRecording{

UIBarButtonItem *stopButton = [[UIBarButtonItem alloc] initWithTitle:@"Stop" style:UIBarButtonItemStyleBordered  target:self action:@selector(stopRecording)];
self.navigationItem.rightBarButtonItem = stopButton;
[stopButton release];

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
    NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
    return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err){
    NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
    return;
}

recordSetting = [[NSMutableDictionary alloc] init];

[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];



// Create a new dated file
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];

NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
if(!recorder){
    NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
    UIAlertView *alert =
    [[UIAlertView alloc] initWithTitle: @"Warning"
                               message: [err localizedDescription]
                              delegate: nil
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
    [alert show];
    [alert release];
    return;
}

//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;

BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
    UIAlertView *cantRecordAlert =
    [[UIAlertView alloc] initWithTitle: @"Warning"
                               message: @"Audio input hardware not available"
                              delegate: nil
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
    [cantRecordAlert show];
    [cantRecordAlert release]; 
    return;
}

// start recording
[recorder recordForDuration:(NSTimeInterval) 10];

}

- (void) stopRecording{

[recorder stop];

NSURL *url = [NSURL fileURLWithPath: recorderFilePath];
NSError *err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(!audioData)
    NSLog(@"audio data: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
[editedObject setValue:[NSData dataWithContentsOfURL:url] forKey:editedFieldKey];   

//[recorder deleteRecording];


NSFileManager *fm = [NSFileManager defaultManager];

err = nil;
[fm removeItemAtPath:[url path] error:&err];
if(err)
    NSLog(@"File Manager: %@ %d %@", [err domain], [err code], [[err userInfo] description]);



UIBarButtonItem *startButton = [[UIBarButtonItem alloc] initWithTitle:@"Record" style:UIBarButtonItemStyleBordered  target:self action:@selector(startRecording)];
self.navigationItem.rightBarButtonItem = startButton;
[startButton release];

}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{

NSLog (@"audioRecorderDidFinishRecording:successfully:");
// your actions here

}

Replace or delete certain characters from filenames of all files in a folder

This batch file can help, but it has some limitations. The filename characters = and % cannot be replaced (going from memory here) and an ^ in the filenames might be a problem too.

In this portion %newname: =_% on every line in the lower block it replaces the character after : with the character after = so as it stands the bunch of characters are going to be replaced with an underscore.

Remove the echo to activate the ren command as it will merely print the commands to the console window until you do.

It will only process the current folder, unless you add /s to the DIR command portion and then it will process all folders under the current one too.

To delete a certain character, remove the character from after the = sign. In %newname:z=% an entry like this would remove all z characters (case insensitive).

@echo off
for /f "delims=" %%a in ('dir /a:-d /o:n /b') do call :next "%%a"
pause
GOTO:EOF
:next
set "newname=%~nx1"

set "newname=%newname: =_%"
set "newname=%newname:)=_%"
set "newname=%newname:(=_%"
set "newname=%newname:&=_%"
set "newname=%newname:^=_%"
set "newname=%newname:$=_%"
set "newname=%newname:#=_%"
set "newname=%newname:@=_%"
set "newname=%newname:!=_%"
set "newname=%newname:-=_%"
set "newname=%newname:+=_%"
set "newname=%newname:}=_%"
set "newname=%newname:{=_%"
set "newname=%newname:]=_%"
set "newname=%newname:[=_%"
set "newname=%newname:;=_%"
set "newname=%newname:'=_%"
set "newname=%newname:`=_%"
set "newname=%newname:,=_%"

echo ren %1 "%newname%

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

Open Virtual Box. Select your virtual Android Device and click on Settings.

enter image description here

Select Network.

enter image description here

Make sure "Enable Network Adapter" box is checked. Also Make sure "Attached to:" has "Host-only Adapter selected". Note the name of the adapter.

enter image description here

Open Settings and click on "Network & Internet"

enter image description here

In the window that opens click on "Change Adapter Options"

enter image description here

In the window that opens you can find many Network names listed. Find the network name that matches with the network name that you noted earlier in the Virtual Box.

enter image description here

Note if that network is Enabled or Disabled.

If the network is Disabled, right click and click Enable.

If the network is Enabled, right click, click Disable and then again click Enable.

enter image description here

Close the window, open Genymotion and start your Virtual Device. The device should now boot without any error.

Android - shadow on text?

 <style name="WhiteTextWithShadow" parent="@android:style/TextAppearance">
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
    <item name="android:shadowColor">@android:color/black</item>
    <item name="android:textColor">@android:color/white</item>
</style>

then use as

 <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            tools:text="Today, May 21"
            style="@style/WhiteTextWithShadow"/>

Can Mockito capture arguments of a method called multiple times?

With Java 8's lambdas, a convenient way is to use

org.mockito.invocation.InvocationOnMock

when(client.deleteByQuery(anyString(), anyString())).then(invocationOnMock -> {
    assertEquals("myCollection", invocationOnMock.getArgument(0));
    assertThat(invocationOnMock.getArgument(1), Matchers.startsWith("id:"));
}

How to get value of checked item from CheckedListBox?

Egypt Development Blog : Get value of checked item in CheckedListBox in vb.net

after bind CheckedListBox with data you can get value of checked items

For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
                    Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(i), DataRowView)
                    Dim XDR As DataRow = XDRV.Row
                    Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
                    Dim XValueMember As String = XDR(CheckedListBox1.ValueMember).ToString()
                    MsgBox("DisplayMember : " & XDisplayMember & "   - ValueMember : " & XValueMember )
Next

now you can use the value or Display of checked items in CheckedListBox from the 2 variable XDisplayMember And XValueMember in the loop

hope to be useful.

Postgresql - change the size of a varchar column to lower length

I have found a very easy way to change the size i.e. the annotation @Size(min = 1, max = 50) which is part of "import javax.validation.constraints" i.e. "import javax.validation.constraints.Size;"

@Size(min = 1, max = 50)
private String country;


when executing  this is hibernate you get in pgAdmin III 


CREATE TABLE address
(
.....
  country character varying(50),

.....

)

How can I verify a Google authentication API access token?

Google oauth code flow response in addition to access_token also returns id_token that contains useful for validation info in encrypted form.

One thing that makes ID tokens useful is that fact that you can pass them around different components of your app. These components can use an ID token as a lightweight authentication mechanism authenticating the app and the user. But before you can use the information in the ID token or rely on it as an assertion that the user has authenticated, you must validate it.

Validation of an ID token requires several steps:

  • Verify that the ID token is a JWT which is properly signed with an appropriate Google public key.
  • Verify that the value of aud in the ID token is equal to your app’s client ID.
  • Verify that the value of iss in the ID token is equal to accounts.google.com or https://accounts.google.com.
  • Verify that the expiry time (exp) of the ID token has not passed.
  • If you passed a hd parameter in the request, verify that the ID token has a hd claim that matches your Google Apps hosted domain.

https://developers.google.com/identity/protocols/OpenIDConnect#validatinganidtoken link has code samples for validation of ID tokens.

See also https://security.stackexchange.com/questions/37818/why-use-openid-connect-instead-of-plain-oauth.

LaTeX table too wide. How to make it fit?

Use p{width} column specifier: e.g. \begin{tabular}{ l p{10cm} } will put column's content into 10cm-wide parbox, and the text will be properly broken to several lines, like in normal paragraph.

You can also use tabular* environment to specify width for the entire table.

How can I add a class to a DOM element in JavaScript?

If you want to create a new input field with for example file type:

 // Create a new Input with type file and id='file-input'
 var newFileInput = document.createElement('input');

 // The new input file will have type 'file'
 newFileInput.type = "file";

 // The new input file will have class="w-95 mb-1" (width - 95%, margin-bottom: .25rem)
 newFileInput.className = "w-95 mb-1"

The output will be: <input type="file" class="w-95 mb-1">


If you want to create a nested tag using JavaScript, the simplest way is with innerHtml:

var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';

The output will be:

<li>
    <span class="toggle">Jan</span>
</li>

Populating a database in a Laravel migration file

Another clean way to do it is to define a private method which create instance et persist concerned Model.

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('label', 256);
        $table->timestamps();
        $table->softDeletes();
    });

    $this->postCreate('admin', 'user');
}

private function postCreate(string ...$roles)  {
    foreach ($roles as $role) {
        $model = new Role();
        $model->setAttribute('label', $role);
        $model->save();
    }
}

With this solution, timestamps fields will be generated by Eloquent.

EDIT: it's better to use seeder system to disctinct database structure generation and database population.

How to build a 'release' APK in Android Studio?

AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle

android {

    signingConfigs {

        release {

            storeFile file('android.keystore')
            storePassword "pwd"
            keyAlias "alias"
            keyPassword "pwd"
        }
    }

    buildTypes {

       release {

           signingConfig signingConfigs.release
       }
    }
}

To actually run your application at emulator or device run gradle installDebug or gradle installRelease.

You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872

libpng warning: iCCP: known incorrect sRGB profile

Thanks to the fantastic answer from Glenn, I used ImageMagik's "mogrify *.png" functionality. However, I had images buried in sub-folders, so I used this simple Python script to apply this to all images in all sub-folders and thought it might help others:

import os
import subprocess

def system_call(args, cwd="."):
    print("Running '{}' in '{}'".format(str(args), cwd))
    subprocess.call(args, cwd=cwd)
    pass

def fix_image_files(root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        # sys.stdout.write('.')
        for dir in dirs:
            system_call("mogrify *.png", "{}".format(os.path.join(path, dir)))


fix_image_files(os.curdir)

What does jQuery.fn mean?

fn literally refers to the jquery prototype.

This line of code is in the source code:

jQuery.fn = jQuery.prototype = {
 //list of functions available to the jQuery api
}

But the real tool behind fn is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this will refer to the jquery object.

$.fn.myExtension = function(){
 var currentjQueryObject = this;
 //work with currentObject
 return this;//you can include this if you would like to support chaining
};

So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.

jsFiddle Demo

$.fn.blueBorder = function(){
 this.each(function(){
  $(this).css("border","solid blue 2px");
 });
 return this;
};
$.fn.blueText = function(){
 this.each(function(){
  $(this).css("color","blue");
 });
 return this;
};

Now you can use those against a class like this:

$('.blue').blueBorder().blueText();

(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)

This answer has a good example of a full fledged extension.

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

Convert the integer into a string and then you can use the STUFF function to insert in your colons into time string. Once you've done that you can convert the string into a time datatype.

SELECT CAST(STUFF(STUFF(STUFF(cast(23421155 as varchar),3,0,':'),6,0,':'),9,0,'.') AS TIME)

That should be the simplest way to convert it to a time without doing anything to crazy.

In your example you also had an int where the leading zeros are not there. In that case you can simple do something like this:

SELECT CAST(STUFF(STUFF(STUFF(RIGHT('00000000' + CAST(421151 AS VARCHAR),8),3,0,':'),6,0,':'),9,0,'.') AS TIME)

Python 3 Float Decimal Points/Precision

The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'

or equivalently with f-strings (Python 3.6+):

>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'

As always, the float value is an approximation:

>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.

How do I print a datetime in the local timezone?

I use this function datetime_to_local_timezone(), which seems overly convoluted but I found no simpler version of a function that converts a datetime instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:

import time, datetime

def datetime_to_local_timezone(dt):
    epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
    st_time = time.localtime(epoch) #  Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
    tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.

    return dt.astimezone(tz) # Move the datetime instance to the new time zone.

utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect

print(dt1)
print(datetime_to_local_timezone(dt1))

print(dt2)
print(datetime_to_local_timezone(dt2))

This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:

2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00

2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Posed question

Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.

Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.

Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:

Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.

Application-specific question

However, returning to your task, I'd research 2 topics:

  1. metrics commonly used for your specific task - it lets (a) to compare your method with others and understand if you do something wrong, and (b) to not explore this by yourself and reuse someone else's findings;
  2. cost of different errors of your methods - for example, use-case of your application may rely on 4- and 5-star reviewes only - in this case, good metric should count only these 2 labels.

Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:

  1. Accuracy, which is used, e.g. in

Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."

(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.

Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.

(link)

  1. MSE (or, less often, Mean Absolute Error - MAE) - see, for example,

Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).

(link) - they explore both accuracy and MSE, considering the latter to be better

Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.

(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.

Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.

About approaches, not metrics

Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.

Rails: Can't verify CSRF token authenticity when making a POST request

The simplest solution for the problem is do standard things in your controller or you can directely put it into ApplicationController

class ApplicationController < ActionController::Base protect_from_forgery with: :exception, prepend: true end

Execute a large SQL script (with GO commands)

Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-2D00-the-easy-way

Sample code:

public static void Main()    
{        
  string scriptDirectory = "c:\\temp\\sqltest\\";
  string sqlConnectionString = "Integrated Security=SSPI;" +
  "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)";
  DirectoryInfo di = new DirectoryInfo(scriptDirectory);
  FileInfo[] rgFiles = di.GetFiles("*.sql");
  foreach (FileInfo fi in rgFiles)
  {
        FileInfo fileInfo = new FileInfo(fi.FullName);
        string script = fileInfo.OpenText().ReadToEnd();
        using (SqlConnection connection = new SqlConnection(sqlConnectionString))
        {
            Server server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
   }
}

If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

How to turn off caching on Firefox?

The Web Developer Toolbar has an option to disable caching which makes it very easy to turn it on and off when you need it.

Getting a list item by index

Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array.

List[index]

See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx

sudo in php exec()

It sounds like you need to set up passwordless sudo. Try:

%admin ALL=(ALL) NOPASSWD: osascript myscript.scpt

Also comment out the following line (in /etc/sudoers via visudo), if it is there:

Defaults    requiretty

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.

Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);

customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;

DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));

CSS blur on background image but not on content

jsfiddle.

<div> 
    <img class="class" src="http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465">
    </img>
    <span>
        Hello World!
    </span>
</div>

What about this? No absolute positioning on div, but instead on img and span.

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

How to free memory in Java?

If you really want to allocate and free a block of memory you can do this with direct ByteBuffers. There is even a non-portable way to free the memory.

However, as has been suggested, just because you have to free memory in C, doesn't mean it a good idea to have to do this.

If you feel you really have a good use case for free(), please include it in the question so we can see what you are rtying to do, it is quite likely there is a better way.

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

How do I read a string entered by the user in C?

You should never use gets (or scanf with an unbounded string size) since that opens you up to buffer overflows. Use the fgets with a stdin handle since it allows you to limit the data that will be placed in your buffer.

Here's a little snippet I use for line input from the user:

#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

This allows me to set the maximum size, will detect if too much data is entered on the line, and will flush the rest of the line as well so it doesn't affect the next input operation.

You can test it with something like:

// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        // Extra NL since my system doesn't output that on EOF.
        printf ("\nNo input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long [%s]\n", buff);
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}

How can I get the username of the logged-in user in Django?

request.user.get_username() or request.user.username, former is preferred.

Django docs say:

Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.

P.S. For templates, use {{ user.get_username }}

How to resolve ORA 00936 Missing Expression Error?

Remove the coma at the end of your SELECT statement (VALUE,), and also remove the one at the end of your FROM statement (rrf b,)

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

Logical operator in a handlebars.js {{#if}} conditional

if you just want to check if one or the other element are present you can use this custom helper

Handlebars.registerHelper('if_or', function(elem1, elem2, options) {
  if (Handlebars.Utils.isEmpty(elem1) && Handlebars.Utils.isEmpty(elem2)) {
    return options.inverse(this);
  } else {
    return options.fn(this);
  }
});

like this

{{#if_or elem1 elem2}}
  {{elem1}} or {{elem2}} are present
{{else}}
  not present
{{/if_or}}

if you also need to be able to have an "or" to compare function return values I would rather add another property that returns the desired result.

The templates should be logicless after all!

MySQL: How to copy rows, but change a few fields?

INSERT INTO Table
          ( Event_ID
          , col2
           ...
          )
     SELECT "155"
          , col2
           ...
      FROM Table WHERE Event_ID = "120"

Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

Is there an equivalent to background-size: cover and contain for image elements?

I found a simple solution to emulate both cover and contain, which is pure CSS, and works for containers with dynamic dimensions, and also doesn't make any restriction on the image ratio.

Note that if you don't need to support IE, or Edge before 16, then you better use object-fit.

background-size: cover

_x000D_
_x000D_
.img-container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.background-image {_x000D_
  position: absolute;_x000D_
  min-width: 1000%;_x000D_
  min-height: 1000%;_x000D_
  left: 50%;_x000D_
  top: 50%;_x000D_
  transform: translateX(-50%) translateY(-50%) scale(0.1);_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div class="img-container">_x000D_
  <img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
  <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The 1000% is used here in case the image natural size is bigger than the size it is being displayed. For example, if the image is 500x500, but the container is only 200x200. With this solution, the image will be resized to 2000x2000 (due to min-width/min-height), then scaled down to 200x200 (due to transform: scale(0.1)).

The x10 factor can be replaced by x100 or x1000, but it is usually not ideal to have a 2000x2000 image being rendered on a 20x20 div. :)

background-size: contain

Following the same principle, you can also use it to emulate background-size: contain:

_x000D_
_x000D_
.img-container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  z-index: 0;_x000D_
}_x000D_
_x000D_
.background-image {_x000D_
  position: absolute;_x000D_
  max-width: 10%;_x000D_
  max-height: 10%;_x000D_
  left: 50%;_x000D_
  top: 50%;_x000D_
  transform: translateX(-50%) translateY(-50%) scale(10);_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div style="background-color: black">_x000D_
  <div class="img-container">_x000D_
    <img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
    <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to read request body in an asp.net core webapi controller?

A clearer solution, works in ASP.Net Core 2.1 / 3.1

Filter class

using Microsoft.AspNetCore.Authorization;
// For ASP.NET 2.1
using Microsoft.AspNetCore.Http.Internal;
// For ASP.NET 3.1
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

public class ReadableBodyStreamAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // For ASP.NET 2.1
        // context.HttpContext.Request.EnableRewind();
        // For ASP.NET 3.1
        // context.HttpContext.Request.EnableBuffering();
    }
}

In an Controller

[HttpPost]
[ReadableBodyStream]
public string SomePostMethod()
{
    //Note: if you're late and body has already been read, you may need this next line
    //Note2: if "Note" is true and Body was read using StreamReader too, then it may be necessary to set "leaveOpen: true" for that stream.
    HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

    using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
    {
        string body = stream.ReadToEnd();
        // body = "param=somevalue&param2=someothervalue"
    }
}

CMAKE_MAKE_PROGRAM not found

I had the same problem and specified CMAKE_MAKE_PROGRAM in a toolchain file, cmake didn't find it. Then I tried adding -D CMAKE_MAKE_PROGRAM=... in the command-line, then it worked. Then I tried changing the generator from "MinGW Makefiles" to "Unix Makefiles" and removed the -D CMAKE_MAKE_PROGRAM from the command-line, and then it worked also!

So for some reason when the generator is set to "MinGW Makefiles" then the CMAKE_MAKE_PROGRAM setting in the toolchain file is not effective, but for the "Unix Makefiles" generator it is.

Is there a color code for transparent in HTML?

{background-color: transparent;}

Regular Expression For Duplicate Words

This is the regex I use to remove duplicate phrases in my twitch bot:

(\S+\s*)\1{2,}

(\S+\s*) looks for any string of characters that isn't whitespace, followed whitespace.

\1{2,} then looks for more than 2 instances of that phrase in the string to match. If there are 3 phrases that are identical, it matches.

send checkbox value in PHP form

try changing this part,

<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up   for newsletter

for this

<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up   for newsletter

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

It's according to spec.

12.5 The if Statement 
.....

2. If ToBoolean(GetValue(exprRef)) is true, then 
a. Return the result of evaluating the first Statement. 
3. Else, 
....

ToBoolean, according to the spec, is

The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:

And that table says this about strings:

enter image description here

The result is false if the argument is the empty String (its length is zero); otherwise the result is true

Now, to explain why "0" == false you should read the equality operator, which states it gets its value from the abstract operation GetValue(lref) matches the same for the right-side.

Which describes this relevant part as:

if IsPropertyReference(V), then 
a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get
be the special [[Get]] internal method defined below. 
b. Return the result of calling the get internal method using base as its this value, and passing 
GetReferencedName(V) for the argument

Or in other words, a string has a primitive base, which calls back the internal get method and ends up looking false.

If you want to evaluate things using the GetValue operation use ==, if you want to evaluate using the ToBoolean, use === (also known as the "strict" equality operator)

Cannot ignore .idea/workspace.xml - keeps popping up

To remove .idea/ completely from the git without affecting your IDE config you could just do:

git rm -r --cached '.idea/'
echo .idea >> .gitignore
git commit -am "removed .idea/ directory"

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

Is there a C++ decompiler?

Yes, but none of them will manage to produce readable enough code to worth the effort. You will spend more time trying to read the decompiled source with assembler blocks inside, than rewriting your old app from scratch.

Run bash script as daemon

To run it as a full daemon from a shell, you'll need to use setsid and redirect its output. You can redirect the output to a logfile, or to /dev/null to discard it. Assuming your script is called myscript.sh, use the following command:

setsid myscript.sh >/dev/null 2>&1 < /dev/null &

This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null with your /path/to/logfile.

You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).

How does strcmp() work?

Here is my version, written for small microcontroller applications, MISRA-C compliant. The main aim with this code was to write readable code, instead of the one-line goo found in most compiler libs.

int8_t strcmp (const uint8_t* s1, const uint8_t* s2)
{
  while ( (*s1 != '\0') && (*s1 == *s2) )
  {
    s1++; 
    s2++;
  }

  return (int8_t)( (int16_t)*s1 - (int16_t)*s2 );
}

Note: the code assumes 16 bit int type.

UIDevice uniqueIdentifier deprecated - What to do now?

I would also suggest changing over from uniqueIdentifier to this open source library (2 simple categories really) that utilize the device’s MAC Address along with the App Bundle Identifier to generate a unique ID in your applications that can be used as a UDID replacement.

Keep in mind that unlike the UDID this number will be different for every app.

You simply need to import the included NSString and UIDevice categories and call [[UIDevice currentDevice] uniqueDeviceIdentifier] like so:

#import "UIDevice+IdentifierAddition.h"
#import "NSString+MD5Addition.h"
NSString *iosFiveUDID = [[UIDevice currentDevice] uniqueDeviceIdentifier]

You can find it on Github here:

UIDevice with UniqueIdentifier for iOS 5


Here are the categories (just the .m files - check the github project for the headers):

UIDevice+IdentifierAddition.m

#import "UIDevice+IdentifierAddition.h"
#import "NSString+MD5Addition.h"

#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@interface UIDevice(Private)

- (NSString *) macaddress;

@end

@implementation UIDevice (IdentifierAddition)

////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Private Methods

// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
- (NSString *) macaddress{
    
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", 
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Public Methods

- (NSString *) uniqueDeviceIdentifier{
    NSString *macaddress = [[UIDevice currentDevice] macaddress];
    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];  
    NSString *stringToHash = [NSString stringWithFormat:@"%@%@",macaddress,bundleIdentifier];
    NSString *uniqueIdentifier = [stringToHash stringFromMD5];  
    return uniqueIdentifier;
}

- (NSString *) uniqueGlobalDeviceIdentifier{
    NSString *macaddress = [[UIDevice currentDevice] macaddress];
    NSString *uniqueIdentifier = [macaddress stringFromMD5];    
    return uniqueIdentifier;
}

@end

NSString+MD5Addition.m:

#import "NSString+MD5Addition.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString(MD5Addition)

- (NSString *) stringFromMD5{
    
    if(self == nil || [self length] == 0)
        return nil;
    
    const char *value = [self UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    return [outputString autorelease];
}

@end

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

Swift days between two NSDates

  func completeOffset(from date:Date) -> String? {

    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .brief

    return  formatter.string(from: Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date, to: self))




}

if you need year month days and hours as string use this

var tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())!

let dc = tomorrow.completeOffset(from: Date())

Creating random colour in Java?

You seem to want light random colors. Not sure what you mean exactly with light. But if you want random 'rainbow colors', try this

Random r = new Random();
Color c = Color.getHSBColor(r.nextFloat(),//random hue, color
                1.0,//full saturation, 1.0 for 'colorful' colors, 0.0 for grey
                1.0 //1.0 for bright, 0.0 for black
                );

Search for HSB color model for more information.

How to do tag wrapping in VS code?

With VSCode 1.47+ you can simply use OPT-w for this.

Utilizing built-in functionality to trigger emmet, this is the easiest way:

  1. Select your text/html.
  2. Option+w
  3. In the emmet window opened in the command palette, type in the tag or wrapping code you need.
  4. Enter
  5. Voila

gpg decryption fails with no secret key error

When migrating from one machine to another-

  1. Check the gpg version and supported algorithms between the two systems.

    gpg --version

  2. Check the presence of keys on both systems.

    gpg --list-keys

    pub 4096R/62999779 2020-08-04 sub 4096R/0F799997 2020-08-04

    gpg --list-secret-keys

    sec 4096R/62999779 2020-08-04 ssb 4096R/0F799997 2020-08-04

Check for the presence of same pair of key ids on the other machine. For decrypting, only secret key(sec) and secret sub key(ssb) will be needed.

If the key is not present on the other machine, export the keys in a file from the machine on which keys are present, scp the file and import the keys on the machine where it is missing.

Do not recreate the keys on the new machine with the same passphrase, name, user details as the newly generated key will have new unique id and "No secret key" error will still appear if source is using previously generated public key for encryption. So, export and import, this will ensure that same key id is used for decryption and encryption.

gpg --output gpg_pub_key --export <Email address>
gpg --output gpg_sec_key --export-secret-keys <Email address>
gpg --output gpg_sec_sub_key --export-secret-subkeys <Email address>

gpg --import gpg_pub_key
gpg --import gpg_sec_key
gpg --import gpg_sec_sub_key

Bootstrap 3 Carousel Not Working

Well, Bootstrap Carousel has various parameters to control.

i.e.

Interval: Specifies the delay (in milliseconds) between each slide.

pause: Pauses the carousel from going through the next slide when the mouse pointer enters the carousel, and resumes the sliding when the mouse pointer leaves the carousel.

wrap: Specifies whether the carousel should go through all slides continuously, or stop at the last slide

For your reference:

enter image description here

Fore more details please click here...

Hope this will help you :)

Note: This is for the further help.. I mean how can you customise or change default behaviour once carousel is loaded.

How to refresh a Page using react-route Link

To refresh page you don't need react-router, simple js:

window.location.reload();

To re-render view in React component, you can just fire update with props/state.

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

How can I display the users profile pic using the facebook graph api?

Knowing the user id the URL for their profile picture is:-

http://graph.facebook.com/[UID]/picture

where in place of [UID] you place your $uid variable, and that URL can be passed to flash

Check for column name in a SqlDataReader object

Here the solution from Jasmine in one line... (one more, tho simple!):

reader.GetSchemaTable().Select("ColumnName='MyCol'").Length > 0;

Import JSON file in React

One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:

import Profile from './components/profile';

This answer explains more.

show more/Less text with just HTML and JavaScript

This should resolve your problem:

function toggleSeeMore() {
    if(document.getElementById("textarea").style.display == 'none') {
        document.getElementById("textarea").style.display = 'block';
        document.getElementById("seeMore").innerHTML = 'See less';
    }
    else {
        document.getElementById("textarea").style.display = 'none';
        document.getElementById("seeMore").innerHTML = 'See more';        
    }
}

The complete working example is here: http://jsfiddle.net/akhikhl/zLA5K/

Best way to list files in Java, sorted by Date Modified?

There is also a completely different way which may be even easier, as we do not deal with large numbers.

Instead of sorting the whole array after you retrieved all filenames and lastModified dates, you can just insert every single filename just after you retrieved it at the right position of the list.

You can do it like this:

list.add(1, object1)
list.add(2, object3)
list.add(2, object2)

After you add object2 to position 2, it will move object3 to position 3.

How can I check if an InputStream is empty without reading from it?

Without reading you can't do this. But you can use a work around like below.

You can use mark() and reset() methods to do this.

mark(int readlimit) method marks the current position in this input stream.

reset() method repositions this stream to the position at the time the mark method was last called on this input stream.

Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.

The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.

To apply this functionalities for this use case, we need to mark the position as 0 and then read the input stream. There after we need to reset the input stream and the input stream will be reverted to the original one.

    if (inputStream.markSupported()) {
          inputStream.mark(0);
          if (inputStream.read() != -1) {
               inputStream.reset();
          } else {
               //Inputstream is empty
          }
    }

Here if the input stream is empty then read() method will return -1.

Android studio logcat nothing to show

In Android 3.6.1 I had to:

  • Upgrade to latest Android Studio version (4.x.x)
  • Restart Logcat
  • Restart the app
  • Restart Android Studio
  • Restart the Android testing device

What is the use of adding a null key or value to a HashMap in Java?

A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.

A corresponding null field value would for example be represented as "(please select)" in the UI selection.

How to unescape HTML character entities in Java?

This did the job for me,

import org.apache.commons.lang.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml(encodedXML);

or

import org.apache.commons.lang3.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml4(encodedXML);

I guess its always better to use the lang3 for obvious reasons. Hope this helps :)

Convert digits into words with JavaScript

Update: Looks like this is more useful than I thought. I've just published this on npm. https://www.npmjs.com/package/num-words


Here's a shorter code. with one RegEx and no loops. converts as you wanted, in south asian numbering system

_x000D_
_x000D_
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];_x000D_
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];_x000D_
_x000D_
function inWords (num) {_x000D_
    if ((num = num.toString()).length > 9) return 'overflow';_x000D_
    n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);_x000D_
    if (!n) return; var str = '';_x000D_
    str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';_x000D_
    str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';_x000D_
    str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';_x000D_
    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';_x000D_
    str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';_x000D_
    return str;_x000D_
}_x000D_
_x000D_
document.getElementById('number').onkeyup = function () {_x000D_
    document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);_x000D_
};
_x000D_
<span id="words"></span>_x000D_
<input id="number" type="text" />
_x000D_
_x000D_
_x000D_

The only limitation is, you can convert maximum of 9 digits, which I think is more than sufficient in most cases..

Fastest method of screen capturing on Windows

In my Impression, the GDI approach and the DX approach are different in its nature. painting using GDI applies the FLUSH method, the FLUSH approach draws the frame then clear it and redraw another frame in the same buffer, this will result in flickering in games require high frame rate.

  1. WHY DX quicker? in DX (or graphics world), a more mature method called double buffer rendering is applied, where two buffers are present, when present the front buffer to the hardware, you can render to the other buffer as well, then after the frame 1 is finished rendering, the system swap to the other buffer( locking it for presenting to hardware , and release the previous buffer ), in this way the rendering inefficiency is greatly improved.
  2. WHY turning down hardware acceleration quicker? although with double buffer rendering, the FPS is improved, but the time for rendering is still limited. modern graphic hardware usually involves a lot of optimization during rendering typically like anti-aliasing, this is very computation intensive, if you don't require that high quality graphics, of course you can just disable this option. and this will save you some time.

I think what you really need is a replay system, which I totally agree with what people discussed.

What is the 'open' keyword in Swift?

open is a new access level in Swift 3, introduced with the implementation of

It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.

In short:

  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

So open is what public used to be in previous Swift releases and the access of public has been restricted. Or, as Chris Lattner puts it in SE-0177: Allow distinguishing between public access and public overridability:

“open” is now simply “more public than public”, providing a very simple and clean model.

In your example, open var hashValue is a property which is accessible and can be overridden in NSObject subclasses.

For more examples and details, have a look at SE-0117.

How to map atan2() to degrees 0-360

angle = Math.atan2(x,y)*180/Math.PI;

I have made a Formula for orienting angle into 0 to 360

angle + Math.ceil( -angle / 360 ) * 360;

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

password-check directive in angularjs

This worked for me.

Directive:

modulename.directive('passwordCheck', function () {

    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, elem, attrs, ngModel) {
            if (!ngModel) return; // do nothing if no ng-model

            var Value = null;

            // watch own value and re-validate on change
            scope.$watch(attrs.ngModel, function (val) {
                Value = val;


                validate();
            });

            // observe the other value and re-validate on change
            attrs.$observe('passwordCheck', function () {
                validate();
            });

            var validate = function () {

                // values
                var val1 = Value;
                var val2 = attrs.passwordCheck;

                // set validity

                if (val1 != '' && val1 != undefined) {
                    ngModel.$setValidity('passwordCheck', val1 == val2);

                }

                else {
                    ngModel.$setValidity('passwordCheck', true);
                }
            };
        }
    }
});

HTML:

ng-model="confirmpassword.selected" type="password" name="confirmpassword" 

password-check="{{password.selected}}"

ng-show="resetpasswordform.confirmpassword.$error.passwordCheck && submitted" Password does not match

How can I list all commits that changed a specific file?

Alternatively (since Git 1.8.4), it is also possible to just get all the commits which has changed a specific part of a file. You can get this by passing the starting line and the ending line number.

The result returned would be the list of commits that modified this particular part. The command goes like:

git log --pretty=short -u -L <upperLimit>,<lowerLimit>:<path_to_filename>

where upperLimit is the start_line_number and lowerLimit is the ending_line_number

More Info - https://www.techpurohit.com/list-some-useful-git-commands

Spring Data JPA and Exists query

in my case it didn't work like following

@Query("select count(e)>0 from MyEntity e where ...")

You can return it as boolean value with following

@Query(value = "SELECT CASE  WHEN count(pl)> 0 THEN true ELSE false END FROM PostboxLabel pl ...")

Interface/enum listing standard mime-type constants

There is now also the class org.apache.http.entity.ContentType from package org.apache.httpcomponents.httpcore, starting from 4.2 up.

Disallow Twitter Bootstrap modal window from closing

$(document).ready(function(e){

  $("#modalId").modal({
     backdrop: 'static',
     keyboard: false,
     show: false
  });

});

"backdrop:'static'" will prevent closing modal when clicking outside of it; "keyboard: false" specifies that the modal can be closed from escape key (Esc) "show: false" will hide the modal when the page has finished loading

How to send Basic Auth with axios

I just faced this issue, doing some research I found that the data values has to be sended as URLSearchParams, I do it like this:

getAuthToken: async () => {
const data = new URLSearchParams();
data.append('grant_type', 'client_credentials');
const fetchAuthToken = await axios({
  url: `${PAYMENT_URI}${PAYMENT_GET_TOKEN_PATH}`,
  method: 'POST',
  auth: {
    username: PAYMENT_CLIENT_ID,
    password: PAYMENT_SECRET,
  },
  headers: {
    Accept: 'application/json',
    'Accept-Language': 'en_US',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Access-Control-Allow-Origin': '*',
  },
  data,
  withCredentials: true,
});
return fetchAuthToken;

},

Execute jQuery function after another function completes

Deferred promises are a nice way to chain together function execution neatly and easily. Whether AJAX or normal functions, they offer greater flexibility than callbacks, and I've found easier to grasp.

function Typer()
{
var dfd = $.Deferred();
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];

UPDATE :

////////////////////////////////

  var timer=    setInterval(function() {
                    if(i == srcText.length) {

    // clearInterval(this);


       clearInterval(timer);

////////////////////////////////


   dfd.resolve();
                        };
                        i++;
                        result += srcText[i].replace("\n", "<br />");
                        $("#message").html( result);
                },
                100);
              return dfd.promise();
            }

I've modified the play function so it returns a promise when the audio finishes playing, which might be useful to some. The third function fires when sound finishes playing.

   function playBGM()
    {
      var playsound = $.Deferred();
      $('#bgm')[0].play();
      $("#bgm").on("ended", function() {
         playsound.resolve();
      });
        return playsound.promise();
    }


    function thirdFunction() {
        alert('third function');
    }

Now call the whole thing with the following: (be sure to use Jquery 1.9.1 or above as I found that 1.7.2 executes all the functions at once, rather than waiting for each to resolve.)

Typer().then(playBGM).then(thirdFunction);  

Before today, I had no luck using deferred promises in this way, and finally have grasped it. Precisely timed, chained interface events occurring exactly when we want them to, including async events, has never been easy. For me at least, I now have it under control thanks largely to others asking questions here.

Entity Framework change connection at runtime

Linq2SQLDataClassesDataContext db = new Linq2SQLDataClassesDataContext();

var query = from p in db.SyncAudits orderby p.SyncTime descending select p;
Console.WriteLine(query.ToString());

try this code...

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

background: fixed no repeat not working on mobile

I had a very simple solution for this, after struggling with all the methods of fixing this.

i had the problem on my mobile IOS devices.

css (desktop)

#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}

Then i overwrite it with media query removing "fixed" as background attachment.

css (mobile)

@media (max-width: 767px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}

initial - Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.

This worked for me on every device. Hope it helps someone else as well.

max(length(field)) in mysql

In case you need both max and min from same table:

    select * from (
(select city, length(city) as maxlen from station
order by maxlen desc limit 1)
union
(select city, length(city) as minlen from station
order by minlen,city limit 1))a;

Flexbox not working in Internet Explorer 11

I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex

IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.

Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.

html,body {
    display: flex;
    flex-flow:column nowrap;
    height:100vh; /* fix IE11 */
    min-height:100%; /* fix IE11 */  
}

A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.

main{
    flex:1 1 auto;
    overflow:hidden; /* IE EDGE overflow fix */  
}

enter image description here

You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

For iOS 8 above it's really simple:

override func viewDidLoad() {  
    super.viewDidLoad()

    self.tableView.estimatedRowHeight = 80
    self.tableView.rowHeight = UITableView.automaticDimension
}

or

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

But for iOS 7, the key is calculate the height after autolayout:

func calculateHeightForConfiguredSizingCell(cell: GSTableViewCell) -> CGFloat {
    cell.setNeedsLayout()
    cell.layoutIfNeeded()
    let height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height + 1.0
    return height
}

Important

  • If multiple lines labels, don't forget set the numberOfLines to 0.

  • Don't forget label.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds)

The full example code is here.

Disable Logback in SpringBoot

It might help if you say what your preferred logger is exactly, and what you did to try and install it. Anyway, Spring Boot tries to work with whatever is in the classpath, so if you don't want logback, take it off the classpath. There are instructions for log4j in the docs, but the same thing would apply to other supported logging systems (anything slf4j, log4j or java util).

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

What is the difference between statically typed and dynamically typed languages?

Statically Typed

The types are checked before run-time so mistakes can be caught earlier.

Examples = c++

Dynamically Typed

The types are checked during execution.

Examples = Python

iconv - Detected an illegal character in input string

If you used the accepted answer, however, you will still receive the PHP Notice if a character in your input string cannot be transliterated:

<?php
$cp1252 = '';

for ($i = 128; $i < 256; $i++) {
    $cp1252 .= chr($i);
}

echo iconv("cp1252", "utf-8//TRANSLIT", $cp1252);

PHP Notice:  iconv(): Detected an illegal character in input string in CP1252.php on line 8

Notice: iconv(): Detected an illegal character in input string in CP1252.php on line 8

So you should use IGNORE, which will ignore what can't be transliterated:

echo iconv("cp1252", "utf-8//IGNORE", $cp1252);

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

one time i found this script, this copy folder and files and keep the same structure of the source in the destination, you can make some tries with this.

# Find the source files
$sourceDir="X:\sourceFolder"

# Set the target file
$targetDir="Y:\Destfolder\"
Get-ChildItem $sourceDir -Include *.* -Recurse |  foreach {

    # Remove the original  root folder
    $split = $_.Fullname  -split '\\'
    $DestFile =  $split[1..($split.Length - 1)] -join '\' 

    # Build the new  destination file path
    $DestFile = $targetDir+$DestFile

    # Move-Item won't  create the folder structure so we have to 
    # create a blank file  and then overwrite it
    $null = New-Item -Path  $DestFile -Type File -Force
    Move-Item -Path  $_.FullName -Destination $DestFile -Force
}

CSS scale height to match width - possibly with a formfactor

You can set its before and after to force a constant width-to-height ratio

HTML:

<div class="squared"></div>

CSS:

.squared {
  background: #333;
  width: 300px; 
}
.squared::before {
  content: '';
  padding-top: 100%;
  float: left;
}
.squared::after {
  content: '';
  display: block;
  clear: both;
}

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

How to play only the audio of a Youtube video using HTML 5?

UPDATED FOR 2020

It seems in Septeber 2019, YouTube updated the values that are returned by get_video_info.

Rather than data.url_encoded_fmt_stream_map and data.adaptive_fmts (as used in the other older examples) now we are looking for for data.formats and data.adaptiveFormats.

Anyways here is what you are all here for some code that loads a YouTube video into an <audio> element. Try it on CodePen

_x000D_
_x000D_
// YouTube video ID
var videoID = "CMNry4PE93Y";

// Fetch video info (using a proxy to avoid CORS errors)
fetch('https://cors-anywhere.herokuapp.com/' + "https://www.youtube.com/get_video_info?video_id=" + videoID).then(response => {
  if (response.ok) {
    response.text().then(ytData => {
      
      // parse response to find audio info
      var ytData = parse_str(ytData);
      var getAdaptiveFormats = JSON.parse(ytData.player_response).streamingData.adaptiveFormats;
      var findAudioInfo = getAdaptiveFormats.findIndex(obj => obj.audioQuality);
      
      // get the URL for the audio file
      var audioURL = getAdaptiveFormats[findAudioInfo].url;
      
      // update the <audio> element src
      var youtubeAudio = document.getElementById('youtube');
      youtubeAudio.src = audioURL;
      
    });
  }
});

function parse_str(str) {
  return str.split('&').reduce(function(params, param) {
    var paramSplit = param.split('=').map(function(value) {
      return decodeURIComponent(value.replace('+', ' '));
    });
    params[paramSplit[0]] = paramSplit[1];
    return params;
  }, {});
}
_x000D_
<audio id="youtube" controls></audio>
_x000D_
_x000D_
_x000D_

How to convert a file into a dictionary?

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.

Can we open pdf file using UIWebView on iOS?

An update to Martin Alléus's answer, to get the full screen whether it is a phone or a iPad without having to hard code:

CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];

NSString *path = [[NSBundle mainBundle] pathForResource:@"pdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

Adding Text to DataGridView Row Header

Here's a little "coup de pouce"

Public Class DataGridViewRHEx
Inherits DataGridView

Protected Overrides Function CreateRowsInstance() As System.Windows.Forms.DataGridViewRowCollection
    Dim dgvRowCollec As DataGridViewRowCollection = MyBase.CreateRowsInstance()
    AddHandler dgvRowCollec.CollectionChanged, AddressOf dvgRCChanged
    Return dgvRowCollec
End Function

Private Sub dvgRCChanged(sender As Object, e As System.ComponentModel.CollectionChangeEventArgs)
    If e.Action = System.ComponentModel.CollectionChangeAction.Add Then
        Dim dgvRow As DataGridViewRow = e.Element
        dgvRow.DefaultHeaderCellType = GetType(DataGridViewRowHeaderCellEx)
    End If
End Sub
End Class

 

Public Class DataGridViewRowHeaderCellEx
Inherits DataGridViewRowHeaderCell

Protected Overrides Sub Paint(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, cellBounds As System.Drawing.Rectangle, rowIndex As Integer, dataGridViewElementState As System.Windows.Forms.DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As System.Windows.Forms.DataGridViewCellStyle, advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, paintParts As System.Windows.Forms.DataGridViewPaintParts)
    If Not Me.OwningRow.DataBoundItem Is Nothing Then
        If TypeOf Me.OwningRow.DataBoundItem Is DataRowView Then

        End If
    End If
'HERE YOU CAN USE DATAGRIDROW TAG TO PAINT STRING

    formattedValue = CStr(Me.DataGridView.Rows(rowIndex).Tag)
    MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
End Sub
End Class

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

Vagrant error : Failed to mount folders in Linux guest

Your log complains about not finding exportfs: sudo: /usr/bin/exportfs: command not found

The exportfs makes local directories available for NFS clients to mount.

Should IBOutlets be strong or weak under ARC?

It looks like something has changed over the years and now Apple recommends to use strong in general. The evidence on their WWDC session is in session 407 - Implementing UI Designs in Interface Builder and starts at 32:30. My note from what he says is (almost, if not exactly, quoting him):

  • outlet connections in general should be strong especially if we connect a subview or constraint that is not always retained by the view hierarchy

  • weak outlet connection might be needed when creating custom views that has some reference to something back up in the view hierarchy and in general it is not recommended

In other wards it should be always strong now as long as some of our custom view doesn't create a retain cycle with some of the view up in the view hierarchy

EDIT :

Some may ask the question. Does keeping it with a strong reference doesn't create a retain cycle as the root view controller and the owning view keeps the reference to it? Or why that changed happened? I think the answer is earlier in this talk when they describe how the nibs are created from the xib. There is a separate nib created for a VC and for the view. I think this might be the reason why they change the recommendations. Still it would be nice to get a deeper explanation from Apple.

How to "wait" a Thread in Android

You can try this one it is short :)

SystemClock.sleep(7000);

It will sleep for 7 sec look at documentation

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Add store name to template like {% url 'app_name:url_name' %}

App_name = store

In urls.py, path('search', views.searched, name="searched"),

<form action="{% url 'store:searched' %}" method="POST">

How to log out user from web site using BASIC authentication?

You can do it entirely in JavaScript:

IE has (for a long time) standard API for clearing Basic Authentication cache:

document.execCommand("ClearAuthenticationCache")

Should return true when it works. Returns either false, undefined or blows up on other browsers.

New browsers (as of Dec 2012: Chrome, FireFox, Safari) have "magic" behavior. If they see a successful basic auth request with any bogus other username (let's say logout) they clear the credentials cache and possibly set it for that new bogus user name, which you need to make sure is not a valid user name for viewing content.

Basic example of that is:

var p = window.location.protocol + '//'
// current location must return 200 OK for this GET
window.location = window.location.href.replace(p, p + 'logout:password@')

An "asynchronous" way of doing the above is to do an AJAX call utilizing the logout username. Example:

(function(safeLocation){
    var outcome, u, m = "You should be logged out now.";
    // IE has a simple solution for it - API:
    try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
    // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
    if (!outcome) {
        // Let's create an xmlhttp object
        outcome = (function(x){
            if (x) {
                // the reason we use "random" value for password is 
                // that browsers cache requests. changing
                // password effectively behaves like cache-busing.
                x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                x.send("")
                // x.abort()
                return 1 // this is **speculative** "We are done." 
            } else {
                return
            }
        })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
    }
    if (!outcome) {
        m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
    }
    alert(m)
    // return !!outcome
})(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)

You can make it a bookmarklet too:

javascript:(function(c){var a,b="You should be logged out now.";try{a=document.execCommand("ClearAuthenticationCache")}catch(d){}a||((a=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):void 0)?(a.open("HEAD",c||location.href,!0,"logout",(new Date).getTime().toString()),a.send(""),a=1):a=void 0);a||(b="Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.");alert(b)})(/*pass safeLocation here if you need*/);

Converting between strings and ArrayBuffers

Unlike the solutions here, I needed to convert to/from UTF-8 data. For this purpose, I coded the following two functions, using the (un)escape/(en)decodeURIComponent trick. They're pretty wasteful of memory, allocating 9 times the length of the encoded utf8-string, though those should be recovered by gc. Just don't use them for 100mb text.

function utf8AbFromStr(str) {
    var strUtf8 = unescape(encodeURIComponent(str));
    var ab = new Uint8Array(strUtf8.length);
    for (var i = 0; i < strUtf8.length; i++) {
        ab[i] = strUtf8.charCodeAt(i);
    }
    return ab;
}

function strFromUtf8Ab(ab) {
    return decodeURIComponent(escape(String.fromCharCode.apply(null, ab)));
}

Checking that it works:

strFromUtf8Ab(utf8AbFromStr('latin????????aß?de???????'))
-> "latin????????aß?de???????"

How to parse this string in Java?

...
String str = "bla!/bla/bla/"

String parts[] = str.split("/");

//To get fist "bla!"
String dir1 = parts[0];

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Others have pointed to the root issue, but in my case I was using dbeaver and initially when setting up the mysql connection with dbeaver was selecting the wrong mysql driver (credit here for answer: https://github.com/dbeaver/dbeaver/issues/4691#issuecomment-442173584 )

Selecting the MySQL choice in the below figure will give the error mentioned as the driver is mysql 4+ which can be seen in the database information tip.


For this error selecting the top mysql 4+ choice in this figure will give the error mentioned in this quesiton


Rather than selecting the MySQL driver instead select the MySQL 8+ driver, shown in the figure below.


enter image description here

SQL Error: ORA-00913: too many values

You should specify column names as below. It's good practice and probably solve your problem

insert into abc.employees (col1,col2) 
select col1,col2 from employees where employee_id=100; 

EDIT:

As you said employees has 112 columns (sic!) try to run below select to compare both tables' columns

select * 
from ALL_TAB_COLUMNS ATC1
left join ALL_TAB_COLUMNS ATC2 on ATC1.COLUMN_NAME = ATC1.COLUMN_NAME 
                               and  ATC1.owner = UPPER('2nd owner')
where ATC1.owner = UPPER('abc')
and ATC2.COLUMN_NAME is null
AND ATC1.TABLE_NAME = 'employees'

and than you should upgrade your tables to have the same structure.

How to use multiple @RequestMapping annotations in spring?

The following is acceptable as well:

@GetMapping(path = { "/{pathVariable1}/{pathVariable1}/somePath", 
                     "/fixedPath/{some-name}/{some-id}/fixed" }, 
            produces = "application/json")

Same can be applied to @RequestMapping as well

How to replace a char in string with an Empty character in C#.NET

You can use a different overload of Replace() that takes string.

val = val.Replace("-", string.Empty)