insert data into database using servlet and jsp in eclipse
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have
the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
Using setDate in PreparedStatement
tl;dr
With JDBC 4.2 or later and java 8 or later:
myPreparedStatement.setObject( … , myLocalDate )
…and…
myResultSet.getObject( … , LocalDate.class )
Details
The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
LocalDate
In java.time, the java.time.LocalDate
class represents a date-only value without time-of-day and without time zone.
If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date
class. You can pass/fetch LocalDate
objects directly to/from your database via PreparedStatement::setObject
and ResultSet::getObject
.
LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate );
…and…
LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );
Before JDBC 4.2, convert
If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.
New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date
see the valueOf
and toLocalDate
methods.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
…and…
LocalDate localDate = sqlDate.toLocalDate();
Placeholder value
Be wary of using 0000-00-00
as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01
.
LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Java java.sql.SQLException: Invalid column index on preparing statement
As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....
The ?
and the OR
needs to be seperated by a space character. Do it wherever needed in the query string.
java.sql.SQLException: Missing IN or OUT parameter at index:: 1
This is not how SQL works:
INSERT INTO employee(hans,germany) values(?,?)
The values (hans,germany)
should use column names (emp_name, emp_address)
. The values are provided by your program by using the Statement.setString(pos,value)
methods. It is complaining because you said there were two parameters (the question marks) but didn't provide values.
You should be creating a PreparedStatement and then setting parameter values as in:
String insert= "INSERT INTO employee(emp_name,emp_address) values(?,?)";
PreparedStatement stmt = con.prepareStatement(insert);
stmt.setString(1,"hans");
stmt.setString(2,"germany");
stmt.execute();
Where's my invalid character (ORA-00911)
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Using "like" wildcard in prepared statement
We can use the CONCAT
SQL function.
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
This works perfectly for my case.
iOS UIImagePickerController result image orientation after upload
@an0, thanks for the answer!
The only thing is autoreleasepool:
func fixOrientation(img: UIImage) -> UIImage? {
let result: UIImage?
if img.imageOrientation == .up {
result = img
} else {
result = autoreleasepool { () -> UIImage? in
UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
img.draw(in: rect)
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return normalizedImage
}
}
return result
}
Java: Insert multiple rows into MySQL with PreparedStatement
@Ali Shakiba your code needs some modification. Error part:
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
Updated code:
String myArray[][] = {
{"1-1", "1-2"},
{"2-1", "2-2"},
{"3-1", "3-2"}
};
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString((2 * i) + 1, myArray[i][1]);
myStatement.setString((2 * i) + 2, myArray[i][2]);
}
myStatement.executeUpdate();
Undefined reference to vtable
The GCC FAQ has an entry on it:
The solution is to ensure that all virtual methods that are not pure are defined. Note that a destructor must be defined even if it is declared pure-virtual [class.dtor]/7.
Therefore, you need to provide a definition for the virtual destructor:
virtual ~CDasherModule()
{ };
Using prepared statements with JDBCTemplate
class Main {
public static void main(String args[]) throws Exception {
ApplicationContext ac = new
ClassPathXmlApplicationContext("context.xml", Main.class);
DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String prasobhName =
jdbcTemplate.query(
"select first_name from customer where last_name like ?",
new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws
SQLException {
preparedStatement.setString(1, "nair%");
}
},
new ResultSetExtractor<Long>() {
public Long extractData(ResultSet resultSet) throws SQLException,
DataAccessException {
if (resultSet.next()) {
return resultSet.getLong(1);
}
return null;
}
}
);
System.out.println(machaceksName);
}
}
PreparedStatement setNull(..)
This guide says:
6.1.5 Sending JDBC NULL as an IN parameter
The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.
A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.
So yes they're equivalent.
Java substring: 'string index out of range'
It is a pity that substring
is not implemented in a way that handles short strings – like in other languages e.g. Python.
Ok, we cannot change that and have to consider this edge case every time we use substr
, instead of if-else clauses I would go for this shorter variant:
myText.substring(0, Math.min(6, myText.length()))
PreparedStatement IN clause alternatives?
My workaround (JavaScript)
var s1 = " SELECT "
+ "FROM table t "
+ " where t.field in ";
var s3 = '(';
for(var i =0;i<searchTerms.length;i++)
{
if(i+1 == searchTerms.length)
{
s3 = s3+'?)';
}
else
{
s3 = s3+'?, ' ;
}
}
var query = s1+s3;
var pstmt = connection.prepareStatement(query);
for(var i =0;i<searchTerms.length;i++)
{
pstmt.setString(i+1, searchTerms[i]);
}
SearchTerms
is the array which contains your input/keys/fields etc
How to save username and password in Git?
You will be more secure if you use SSH authentication than username/password authentication.
If you are using a Mac, SSH client authentication is integrated into the MacOS keychain. Once you have created an SSH key, type into your terminal:
ssh-add -K ~/.ssh/id_rsa
This will add the SSH private key to the MacOS keychain. The git client will use ssh when it connects to the remote server. As long as you have registered your ssh public key with the server, you will be fine.
How to get the current location in Google Maps Android API v2?
try this
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
Could not reserve enough space for object heap to start JVM
According to this post this error message means:
Heap size is larger than your computer's physical memory.
Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.
Why not downsize other memory settings to free up space for the heap?
Key Listeners in python?
It's unfortunately not so easy to do that. If you're trying to make some sort of text user interface, you may want to look into curses
. If you want to display things like you normally would in a terminal, but want input like that, then you'll have to work with termios
, which unfortunately appears to be poorly documented in Python. Neither of these options are that simple, though, unfortunately. Additionally, they do not work under Windows; if you need them to work under Windows, you'll have to use PDCurses as a replacement for curses
or pywin32 rather than termios
.
I was able to get this working decently. It prints out the hexadecimal representation of keys you type. As I said in the comments of your question, arrows are tricky; I think you'll agree.
#!/usr/bin/env python
import sys
import termios
import contextlib
@contextlib.contextmanager
def raw_mode(file):
old_attrs = termios.tcgetattr(file.fileno())
new_attrs = old_attrs[:]
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
try:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
yield
finally:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)
def main():
print 'exit with ^C or ^D'
with raw_mode(sys.stdin):
try:
while True:
ch = sys.stdin.read(1)
if not ch or ch == chr(4):
break
print '%02x' % ord(ch),
except (KeyboardInterrupt, EOFError):
pass
if __name__ == '__main__':
main()
JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object
Just did this on Solaris and ran into this identical problem where even "java -version" does not work. There is a reason that the 64 bit versions of the distro are WAY smaller than the 32-bit. It is indeed as stated above:
In other words, to get a fully working 64-bit installation, you must first run the 32-bit installation, and follow that up with a 64-bit installation if you have a 64bit capable machine...
So I ran the installer for the 32-bit:
sh jdk-6u131-solaris-sparc.sh
Then I ran the installer for the 64-bit:
sh jdk-6u131-solaris-sparcv9.sh
This gives me several java executables to choose from:
- $ find . -name java
- ./jdk1.6.0_131/db/demo/programs/scores/java
- ./jdk1.6.0_131/db/demo/programs/vtis/java
- ./jdk1.6.0_131/bin/java
- ./jdk1.6.0_131/bin/sparcv9/java
- ./jdk1.6.0_131/jre/bin/java
- ./jdk1.6.0_131/jre/bin/sparcv9/java
The sparcv9 java's are the 64bit versions and they work with "-version" when installed alongside the 32bit JDK.
- ./jdk1.6.0_131/bin/sparcv9/java -version
- java version "1.6.0_131"
- Java(TM) SE Runtime Environment (build 1.6.0_131-b32)
- Java HotSpot(TM) 64-Bit Server VM (build 20.131-b32, mixed mode)
-Dan
replacing text in a file with Python
I might consider using a dict
and re.sub
for something like this:
import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
return repldict[match.group(0)]
regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
for line in fin:
fout.write(regex.sub(replfunc,line))
This has a slight advantage to replace
in that it is a bit more robust to overlapping matches.
Mutex lock threads
Q1.) Assuming process B tries to take ownership of the same mutex you locked in process A (you left that out of your pseudocode) then no, process B cannot access sharedResource while the mutex is locked since it will sit waiting to lock the mutex until it is released by process A. It will return from the mutex_lock() function when the mutex is locked (or when an error occurs!)
Q2.) In Process B, ensure you always lock the mutex, access the shared resource, and then unlock the mutex. Also, check the return code from the mutex_lock( pMutex ) routine to ensure that you actually own the mutex, and ONLY unlock the mutex if you have locked it. Do the same from process A.
Both processes should basically do the same thing when accessing the mutex.
lock()
If the lock succeeds, then {
access sharedResource
unlock()
}
Q3.)
Yes, there are lots of diagrams: =)
https://www.google.se/search?q=mutex+thread+process&rlz=1C1AFAB_enSE487SE487&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=ErodUcSmKqf54QS6nYDoAw&biw=1200&bih=1730&sei=FbodUbPbB6mF4ATarIBQ
Run java jar file on a server as background process
You can try this:
#!/bin/sh
nohup java -jar /web/server.jar &
The & symbol, switches the program to run in the background.
The nohup utility makes the command passed as an argument run in the background even after you log out.
In Excel, sum all values in one column in each row where another column is a specific value
You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false)
. To add an extra column with only the non-reimbursed amounts, you would use something like:
=IF(B1="No", A1, 0)
and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.
Custom designing EditText
edit_text.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff" />
<corners android:radius="5dp"/>
<stroke android:width="2dip" android:color="@color/button_color_submit" />
</shape>
use here
<EditText
-----
------
android:background="@drawable/edit_text.xml"
/>
Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";
function printr($data)
{
echo "<pre>";
print_r($data);
echo "</pre>";
}
And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php
include('functions.php');
printr($data);
Simple two column html layout without using tables
Well, if you want the super easiest method, just put
<div class="left">left</div>
<div class="right">right</div>
.left {
float: left;
}
though you may need more than that depending on what other layout requirements you have.
CSS Box Shadow - Top and Bottom Only
As Kristian has pointed out, good control over z-values will often solve your problems.
If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.
I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:
box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;
This will give you some control over the "amount" of shadow in each direction.
Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.
Hope this was what you were looking for!
Body set to overflow-y:hidden but page is still scrollable in Chrome
What works for me on /FF and /Chrome:
body {
position: fixed;
width: 100%;
height: 100%;
}
overflow: hidden
just disables display of the scrollbars. (But you can put it in there if you like to).
There is one drawback I found: If you use this method on a page which you want only temporarily to stop scrolling, setting position: fixed
will scroll it to the top.
This is because position: fixed uses absolute positions which are currently set to 0/0.
This can be repaired e.g. with jQuery:
var lastTop;
function stopScrolling() {
lastTop = $(window).scrollTop();
$('body').addClass( 'noscroll' )
.css( { top: -lastTop } )
;
}
function continueScrolling() {
$('body').removeClass( 'noscroll' );
$(window).scrollTop( lastTop );
}
TypeError: Missing 1 required positional argument: 'self'
You can call the method like pump.getPumps()
. By adding @classmethod
decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.
class Pump:
def __init__(self):
print ("init") # never prints
@classmethod
def getPumps(cls):
# Open database connection
# some stuff here that never gets executed because of error
So, simply call Pump.getPumps()
.
In java, it is termed as static
method.
enum Values to NSString (iOS)
This will be validated by compiler, so you won't mix up indices accidentally.
NSDictionary *stateStrings =
@{
@(MCSessionStateNotConnected) : @"MCSessionStateNotConnected",
@(MCSessionStateConnecting) : @"MCSessionStateConnecting",
@(MCSessionStateConnected) : @"MCSessionStateConnected",
};
NSString *stateString = [stateStrings objectForKey:@(state)];
var stateStrings: [MCSessionState: String] = [
.notConnected : "MCSessionState.notConnected",
.connecting : "MCSessionState.connecting",
.connected : "MCSessionState.connected"
]
var stateString = stateStrings[MCSessionState.Connected]
UPDATE: A more Swifty way is to extend the enum with CustomStringConvertible
conformance. Also, this way the compiler will safeguard to implement every new addition to the underlying enum (whereas using arrays does not), as switch
statements must be exhaustive.
extension MCSessionState: CustomStringConvertible {
public var description: String {
switch self {
case .notConnected:
return "MCSessionState.notConnected"
case .connecting:
return "MCSessionState.connecting"
case .connected:
return "MCSessionState.connected"
@unknown default:
return "Unknown"
}
}
}
// You can use it like this.
var stateString = MCSessionState.connected.description
// Or this.
var stateString = "\(MCSessionState.connected)"
jQuery select change show/hide div event
Try this:
$(function () {
$('#row_dim').hide(); // this line you can avoid by adding #row_dim{display:none;} in your CSS
$('#type').change(function () {
$('#row_dim').hide();
if (this.options[this.selectedIndex].value == 'parcel') {
$('#row_dim').show();
}
});
});
Returning first x items from array
If you just want to output the first 5 elements, you should write something like:
<?php
if (!empty ( $an_array ) ) {
$min = min ( count ( $an_array ), 5 );
$i = 0;
foreach ($value in $an_array) {
echo $value;
$i++;
if ($i == $min) break;
}
}
?>
If you want to write a function which returns part of the array, you should use array_slice:
<?php
function GetElements( $an_array, $elements ) {
return array_slice( $an_array, 0, $elements );
}
?>
Proxies with Python 'Requests' module
here is my basic class in python for the requests module with some proxy configs and stopwatch !
import requests
import time
class BaseCheck():
def __init__(self, url):
self.http_proxy = "http://user:pw@proxy:8080"
self.https_proxy = "http://user:pw@proxy:8080"
self.ftp_proxy = "http://user:pw@proxy:8080"
self.proxyDict = {
"http" : self.http_proxy,
"https" : self.https_proxy,
"ftp" : self.ftp_proxy
}
self.url = url
def makearr(tsteps):
global stemps
global steps
stemps = {}
for step in tsteps:
stemps[step] = { 'start': 0, 'end': 0 }
steps = tsteps
makearr(['init','check'])
def starttime(typ = ""):
for stemp in stemps:
if typ == "":
stemps[stemp]['start'] = time.time()
else:
stemps[stemp][typ] = time.time()
starttime()
def __str__(self):
return str(self.url)
def getrequests(self):
g=requests.get(self.url,proxies=self.proxyDict)
print g.status_code
print g.content
print self.url
stemps['init']['end'] = time.time()
#print stemps['init']['end'] - stemps['init']['start']
x= stemps['init']['end'] - stemps['init']['start']
print x
test=BaseCheck(url='http://google.com')
test.getrequests()
How to redirect to another page using PHP
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>
Java Enum Methods - return opposite direction enum
For a small enum like this, I find the most readable solution to be:
public enum Direction {
NORTH {
@Override
public Direction getOppositeDirection() {
return SOUTH;
}
},
SOUTH {
@Override
public Direction getOppositeDirection() {
return NORTH;
}
},
EAST {
@Override
public Direction getOppositeDirection() {
return WEST;
}
},
WEST {
@Override
public Direction getOppositeDirection() {
return EAST;
}
};
public abstract Direction getOppositeDirection();
}
python-How to set global variables in Flask?
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
swift UITableView set rowHeight
As pointed out in comments, you cannot call cellForRowAtIndexPath
inside heightForRowAtIndexPath
.
What you can do is creating a template cell used to populate with your data and then compute its height.
This cell doesn't participate to the table rendering, and it can be reused to calculate the height of each table cell.
Briefly, it consists of configuring the template cell with the data you want to display, make it resize accordingly to the content, and then read its height.
I have taken this code from a project I am working on - unfortunately it's in Objective C, I don't think you will have problems translating to swift
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
static PostCommentCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tblComments dequeueReusableCellWithIdentifier:POST_COMMENT_CELL_IDENTIFIER];
});
sizingCell.comment = self.comments[indexPath.row];
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}
PowerShell equivalent to grep -f
I had the same issue trying to find text in files with powershell. I used the following - to stay as close to the Linux environment as possible.
Hopefully this helps somebody:
PowerShell:
PS) new-alias grep findstr
PS) ls -r *.txt | cat | grep "some random string"
Explanation:
ls - lists all files
-r - recursively (in all files and folders and subfolders)
*.txt - only .txt files
| - pipe the (ls) results to next command (cat)
cat - show contents of files comming from (ls)
| - pipe the (cat) results to next command (grep)
grep - search contents from (cat) for "some random string" (alias to findstr)
Yes, this works as well:
PS) ls -r *.txt | cat | findstr "some random string"
What does "pending" mean for request in Chrome Developer Window?
I had the same issue on OSX Mavericks, it turned out that Sophos anti-virus was blocking certain requests, once I uninstalled it the issue went away.
If you think that it might be caused by an extension one easy way to try and test this is to open chrome with the '--disable-extensions
flag to see if it fixes the problem. If that doesn't fix it consider looking beyond the browser to see if any other application might be causing the problem, specifically security apps which can affect requests.
How to call a function, PostgreSQL
For Postgresql you can use PERFORM. PERFORM is only valid within PL/PgSQL procedure language.
DO $$ BEGIN
PERFORM "saveUser"(3, 'asd','asd','asd','asd','asd');
END $$;
The suggestion from the postgres team:
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
Retrieving a property of a JSON object by index?
There is no "second property" -- when you say var obj = { ... }
, the properties inside the braces are unordered. Even a 'for' loop walking through them might return them in different orders on different JavaScript implementations.
jquery - disable click
/** eworkyou **//
$('#navigation a').bind('click',function(e){
var $this = $(this);
var prev = current;
current = $this.parent().index() + 1; //
if (current == 1){
$("#navigation a:eq(1)").unbind("click"); //
}
if (current >= 2){
$("#navigation a:eq(1)").bind("click"); //
}
How can I execute Python scripts using Anaconda's version of Python?
The instructions in the official Python documentation worked for me: https://docs.python.org/2/using/windows.html#executing-scripts
Launch a command prompt.
Associate the correct file group with .py scripts:
assoc .py=Python.File
Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
The example shows how to associate the .py extension with the .pyw executable, but it works if you want to associate the .py extension with the Anaconda Python executable. You need administrative rights. The name "Python.File" could be anything, you just have to make sure is the same name in the ftype command. When you finish and before you try double-clicking the .py file, you must change the "Open with" in the file properties. The file type will be now ".py" and it is opened with the Anaconda python.exe.
How do I find the MySQL my.cnf location
mysql --help | grep /my.cnf | xargs ls
will tell you where my.cnf
is located on Mac/Linux
ls: cannot access '/etc/my.cnf': No such file or directory
ls: cannot access '~/.my.cnf': No such file or directory
/etc/mysql/my.cnf
In this case, it is in /etc/mysql/my.cnf
ls: /etc/my.cnf: No such file or directory
ls: /etc/mysql/my.cnf: No such file or directory
ls: ~/.my.cnf: No such file or directory
/usr/local/etc/my.cnf
In this case, it is in /usr/local/etc/my.cnf
How to change the current URL in javascript?
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
SQL query for today's date minus two months
TSQL, Alternative using variable declaration. (it might improve Query's readability)
DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.
SELECT
*
FROM
FB as A
WHERE
A.Dte <= @gapPeriod; --only older records.
How to form tuple column from two columns in Pandas
I'd like to add df.values.tolist()
. (as long as you don't mind to get a column of lists rather than tuples)
import pandas as pd
import numpy as np
size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)})
%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Spring JPA and persistence.xml
If anyone wants to use purely Java configuration instead of xml
configuration of hibernate, use this:
You can configure Hibernate without using persistence.xml at all in Spring like like this:
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
Map<String, Object> properties = new Hashtable<>();
properties.put("javax.persistence.schema-generation.database.action",
"none");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); //you can change this if you have a different DB
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(adapter);
factory.setDataSource(this.springJpaDataSource());
factory.setPackagesToScan("package name");
factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
factory.setValidationMode(ValidationMode.NONE);
factory.setJpaPropertyMap(properties);
return factory;
}
Since you are not using persistence.xml, you should create a bean that returns DataSource which you specify in the above method that sets the data source:
@Bean
public DataSource springJpaDataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:mysql://localhost/SpringJpa");
dataSource.setUsername("tomcatUser");
dataSource.setPassword("password1234");
return dataSource;
}
Then you use @EnableTransactionManagement
annotation over this configuration file. Now when you put that annotation, you have to create one last bean:
@Bean
public PlatformTransactionManager jpaTransactionManager()
{
return new JpaTransactionManager(
this.entityManagerFactoryBean().getObject());
}
Now, don't forget to use @Transactional
Annotation over those method that deal with DB.
Lastly, don't forget to inject EntityManager
in your repository (This repository class should have @Repository
annotation over it).
Get the Query Executed in Laravel 3/4
Since the profiler is not yet out in Laravel 4, I've created this helper function to see the SQL being generated:
public static function q($all = true)
{
$queries = DB::getQueryLog();
if($all == false) {
$last_query = end($queries);
return $last_query;
}
return $queries;
}
NOTE: Set the $all flag to false if you only want the last SQL query.
I keep this sort of functions in a class called DBH.php (short for Database Helper) so I can call it from anywhere like this:
dd(DBH::q());
Here is the output I get:
In case you are wondering, I use Kint for the dd() formatting.
http://raveren.github.io/kint/
Best way to return a value from a python script
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
Return values (from a wrapping-function)
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
Exit codes as indicators
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor.
I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
Stdout as your relay
If not you'd have to use stdout to communicate with the outside world (like you've described).
But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
Files as conveyors
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
Sockets as conveyors
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
Angular 2: Passing Data to Routes?
1. Set up your routes to accept data
{
path: 'some-route',
loadChildren:
() => import(
'./some-component/some-component.module'
).then(
m => m.SomeComponentModule
),
data: {
key: 'value',
...
},
}
2. Navigate to route:
From HTML:
<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>
Or from Typescript:
import {Router} from '@angular/router';
...
this.router.navigate(
[
'/some-component',
{
key: 'value',
...
}
]
);
3. Get data from route
import {ActivatedRoute} from '@angular/router';
...
this.value = this.route.snapshot.params['key'];
Failed to serialize the response in Web API with Json
I resolved it using this code to WebApiConfig.cs file
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
Timeout a command in bash without unnecessary delay
There's also cratimeout
by Martin Cracauer (written in C for Unix and Linux systems).
# cf. http://www.cons.org/cracauer/software.html
# usage: cratimeout timeout_in_msec cmd args
cratimeout 5000 sleep 1
cratimeout 5000 sleep 600
cratimeout 5000 tail -f /dev/null
cratimeout 5000 sh -c 'while sleep 1; do date; done'
SQL Server Installation - What is the Installation Media Folder?
For the SQL Server 2017 (Developer Edition)
installation, I did the following:
- Open
SQL Server Installation Center
- Click on
Installation
- Click on
New SQL Server stand-alone installation or add features to an existing installation
- Browse to
C:\SQLServer2017Media\Developer_ENU
and click OK
Replacing objects in array
I am only submitting this answer because people expressed concerns over browsers and maintaining the order of objects. I recognize that it is not the most efficient way to accomplish the goal.
Having said this, I broke the problem down into two functions for readability.
// The following function is used for each itertion in the function updateObjectsInArr
const newObjInInitialArr = function(initialArr, newObject) {
let id = newObject.id;
let newArr = [];
for (let i = 0; i < initialArr.length; i++) {
if (id === initialArr[i].id) {
newArr.push(newObject);
} else {
newArr.push(initialArr[i]);
}
}
return newArr;
};
const updateObjectsInArr = function(initialArr, newArr) {
let finalUpdatedArr = initialArr;
for (let i = 0; i < newArr.length; i++) {
finalUpdatedArr = newObjInInitialArr(finalUpdatedArr, newArr[i]);
}
return finalUpdatedArr
}
const revisedArr = updateObjectsInArr(arr1, arr2);
jsfiddle
Proper way to assert type of variable in Python
You might want to try this example for version 2.6 of Python.
def my_print(text, begin, end):
"Print text in UPPER between 'begin' and 'end' in lower."
for obj in (text, begin, end):
assert isinstance(obj, str), 'Argument of wrong type!'
print begin.lower() + text.upper() + end.lower()
However, have you considered letting the function fail naturally instead?
Android 6.0 multiple permissions
The following methodology is about
- asking permissions dynamically ;
- showing a AlertDialog if the user denies any permission
- looping until the user accepts permission(s)
Create a "static" class for permissions methods
public class PermissionsUtil {
public static final int PERMISSION_ALL = 1;
public static boolean doesAppNeedPermissions(){
return android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1;
}
public static String[] getPermissions(Context context)
throws PackageManager.NameNotFoundException {
PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_PERMISSIONS);
return info.requestedPermissions;
}
public static void askPermissions(Activity activity){
if(doesAppNeedPermissions()) {
try {
String[] permissions = getPermissions(activity);
if(!checkPermissions(activity, permissions)){
ActivityCompat.requestPermissions(activity, permissions,
PERMISSION_ALL);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
public static boolean checkPermissions(Context context, String... permissions){
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null &&
permissions != null) {
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(context, permission) !=
PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
}
In MainActivity.java
private void checkPermissions(){
PermissionsUtil.askPermissions(this);
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PermissionsUtil.PERMISSION_ALL: {
if (grantResults.length > 0) {
List<Integer> indexesOfPermissionsNeededToShow = new ArrayList<>();
for(int i = 0; i < permissions.length; ++i) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
indexesOfPermissionsNeededToShow.add(i);
}
}
int size = indexesOfPermissionsNeededToShow.size();
if(size != 0) {
int i = 0;
boolean isPermissionGranted = true;
while(i < size && isPermissionGranted) {
isPermissionGranted = grantResults[indexesOfPermissionsNeededToShow.get(i)]
== PackageManager.PERMISSION_GRANTED;
i++;
}
if(!isPermissionGranted) {
showDialogNotCancelable("Permissions mandatory",
"All the permissions are required for this app",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
checkPermissions();
}
});
}
}
}
}
}
}
private void showDialogNotCancelable(String title, String message,
DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setCancelable(false)
.create()
.show();
}
JavaFX - create custom button with image
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
Set EditText cursor color
you can use code below in layout
android:textCursorDrawable="@color/red"
android:textColor="@color/black
How do I read text from the clipboard?
The most upvoted answer above is weird in a way that it simply clears the Clipboard and then gets the content (which is then empty). One could clear the clipboard to be sure that some clipboard content type like "formated text" does not "cover" your plain text content you want to save in the clipboard.
The following piece of code replaces all newlines in the clipboard by spaces, then removes all double spaces and finally saves the content back to the clipboard:
import win32clipboard
win32clipboard.OpenClipboard()
c = win32clipboard.GetClipboardData()
win32clipboard.EmptyClipboard()
c = c.replace('\n', ' ')
c = c.replace('\r', ' ')
while c.find(' ') != -1:
c = c.replace(' ', ' ')
win32clipboard.SetClipboardText(c)
win32clipboard.CloseClipboard()
How to Bootstrap navbar static to fixed on scroll?
/**
* Scroll management
*/
$(document).ready(function () {
// Define the menu we are working with
var menu = $('.navbar.navbar-default.navbar-inverse');
// Get the menus current offset
var origOffsetY = menu.offset().top;
/**
* scroll
* Perform our menu mod
*/
function scroll() {
// Check the menus offset.
if ($(window).scrollTop() >= origOffsetY) {
//If it is indeed beyond the offset, affix it to the top.
$(menu).addClass('navbar-fixed-top');
} else {
// Otherwise, un affix it.
$(menu).removeClass('navbar-fixed-top');
}
}
// Anytime the document is scrolled act on it
document.onscroll = scroll;
});
How do I do a simple 'Find and Replace" in MsSQL?
This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext
data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:
Argument data type ntext is invalid for argument 1 of replace
function.
The simplest fix, if your column data fits within nvarchar
, is to cast the column during replace. Borrowing the code from the accepted answer:
UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'
This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!
How to convert datetime to integer in python
It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime
module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp())
.
If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:
2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)
def to_integer(dt_time):
return 10000*dt_time.year + 100*dt_time.month + dt_time.day
E.g.
In [1]: import datetime
In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
: return 10000*dt_time.year + 100*dt_time.month + dt_time.day
: # Or take the appropriate chars from a string date representation.
:--
In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613
If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.
I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.
It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.
Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.
It's generally much better to leave the value in a date context, like datetime.date
, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.
Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio
The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel
. The basic idea is to use QScrollArea
as a container for the QLabel
and if needed use label.setScaledContents(bool)
and scrollarea.setWidgetResizable(bool)
to fill available space and/or ensure QLabel inside is resizable.
Additionally, to resize QLabel while honoring aspect ratio use:
label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));
The width
and height
can be set based on scrollarea.width()
and scrollarea.height()
.
In this way there is no need to subclass QLabel.
invalid operands of types int and double to binary 'operator%'
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the
operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
minimize app to system tray
try this
private void Form1_Load(object sender, EventArgs e)
{
notifyIcon1.BalloonTipText = "Application Minimized.";
notifyIcon1.BalloonTipTitle = "test";
}
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
ShowInTaskbar = false;
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(1000);
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
ShowInTaskbar = true;
notifyIcon1.Visible = false;
WindowState = FormWindowState.Normal;
}
how to install multiple versions of IE on the same system?
To answer your question: no, it's not possible to have multiple versions of IE (if that is what you meant) installed in a 'normal' way (i.e. not a hack, a sandbox or a VM etc). It's perfectly ok to have multiple browsers of different types installed on the same machine, such as IE8, Firefox 3 and Chrome all at once.
SandboxIE should allow you to install multiple versions of IE side-by-side (as well as other software), and this is less hassle than going down the virtual machine route.
However, from a QA point of view I'd strongly recommend installing different versions on different machines as the best option from a testing point of view. This will give you the most realistic testing environment. If you don't have the hardware for that, then virtual machines are the next best option as mentioned in some of the other answers.
How to get row from R data.frame
If you don't know the row number, but do know some values then you can use subset
x <- structure(list(A = c(5, 3.5, 3.25, 4.25, 1.5 ),
B = c(4.25, 4, 4, 4.5, 4.5 ),
C = c(4.5, 2.5, 4, 2.25, 3 )
),
.Names = c("A", "B", "C"),
class = "data.frame",
row.names = c(NA, -5L)
)
subset(x, A ==5 & B==4.25 & C==4.5)
JavaScript and Threads
With the HTML5 "side-specs" no need to hack javascript anymore with setTimeout(), setInterval(), etc.
HTML5 & Friends introduces the javascript Web Workers specification. It is an API for running scripts asynchronously and independently.
Links to the specification and a tutorial.
How to stop a function
def player(game_over):
do something here
game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
if not game_over:
computer(game_over) #We are only going to do this if check_winner comes back as False
def check_winner():
check something
#here needs to be an if / then statement deciding if the game is over, return True if over, false if not
if score == 100:
return True
else:
return False
def computer(game_over):
do something here
game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
if not game_over:
player(game_over) #We are only going to do this if check_winner comes back as False
game_over = False #We need a variable to hold wether the game is over or not, we'll start it out being false.
player(game_over) #Start your loops, sending in the status of game_over
Above is a pretty simple example... I made up a statement for check_winner
using score = 100
to denote the game being over.
You will want to use similar method of passing score
into check_winner
, using game_over = check_winner(score)
. Then you can create a score at the beginning of your program and pass it through to computer
and player
just like game_over
is being handled.
How to display Wordpress search results?
I am using searchform.php
and search.php
files as already mentioned, but here I provide the actual code.
Creating a Search Page codex
page helps here and #Creating_a_Search_Page_Template
shows the search query.
In my case I pass the $search_query
arguments to the WP_Query Class
(which can determine if is search query!). I then run The Loop to display the post information I want to, which in my case is the the_permalink and the_title
.
Search box form:
<form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
<button type="submit" role="button" class="btn btn-default right"/><span class="glyphicon glyphicon-search white"></span></button>
</form>
search.php
template file:
<?php
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach
$the_query = new WP_Query($search_query);
if ( $the_query->have_posts() ) :
?>
<!-- the loop -->
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
MSBuild doesn't copy references (DLL files) if using project dependencies in solution
The issue I was facing was I have a project that is dependent on a library project. In order to build I was following these steps:
msbuild.exe myproject.vbproj /T:Rebuild
msbuild.exe myproject.vbproj /T:Package
That of course meant I was missing my library's dll files in bin and most importantly in the package zip file. I found this works perfectly:
msbuild.exe myproject.vbproj /T:Rebuild;Package
I have no idea why this work or why it didn't in the first place. But hope that helps.
Remove header and footer from window.print()
<html>
<head>
<title>Print</title>
<script type="text/javascript">
window.print();
document.margin='none';
</script>
</head>
<body>
<p>hello</p>
<p>hi</p>
</body>
</html>
//place it in a script file or in the script tag.
This will remove all the margins and you won't be able to see the headers and footers.
Select option padding not working in chrome
Arbitrary Indentation of any Option
If you just want to indent random, arbitrary <option />
elements, you can use
, which has the greatest cross-browser compatibility of the solutions posted here...
_x000D_
_x000D_
.optionGroup {
font-weight: bold;
font-style: italic;
}
_x000D_
<select>
<option class="optionGroup" selected disabled>Choose one</option>
<option value="sydney" class="optionChild"> Sydney</option>
<option value="melbourne" class="optionChild"> Melbourne</option>
<option value="cromwell" class="optionChild"> Cromwell</option>
<option value="queenstown" class="optionChild"> Queenstown</option>
</select>
_x000D_
_x000D_
_x000D_
Ordered Indentation of Options
But if you have some sorted, ordered structure to your data, then it is recommended that you use the <optgroup/>
syntax....
The HTML element creates a grouping of options within a element.
(Source: MDN Web Docs: <optgroup>
)
_x000D_
_x000D_
<select>
<optgroup label="Australia" default selected>
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
</optgroup>
<optgroup label="United Kingdom">
<option value="london">London</option>
<option value="glasgow">Glasgow</option>
</optgroup>
</select>
_x000D_
_x000D_
_x000D_
Unfortunately, only one <optgroup />
level is allowed and currently supported by browsers today. (Source: w3.org.) Personally, I would consider that part of the spec broken, but you can always extend to third, fourth, etc., levels of indentation with using the
trick up above.
Get the current cell in Excel VB
Try this
Dim app As Excel.Application = Nothing
Dim Active_Cell As Excel.Range = Nothing
Try
app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
Active_Cell = app.ActiveCell
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
' .address will return the cell reference :)
Java ElasticSearch None of the configured nodes are available
This means we are not able to instantiate ES transportClient and throw this exception. There are couple of possibilities that cause this issue.
- Cluster name is incorrect. So open
ES_HOME_DIR/config/elasticserach.yml
file and check the cluster name value OR use this command: curl -XGET 'http://localhost:9200/_nodes'
- Verify port 9200 is http port but elasticsearch service is using tcp port 9300 [by default]. So verify that the port is not blocked.
Authentication issue: set the header in transportClient's context for authentication:
client.threadPool().getThreadContext()
.putHeader("Authorization", "Basic " + encodeBase64String(basicHeader.getBytes()));
If you are still facing this issue then add the following property:
put("client.transport.ignore_cluster_name", true)
The below basic code is working fine for me:
Settings settings = Settings.builder()
.put("cluster.name", "my-application").put("client.transport.sniff", true).put("client.transport.ignore_cluster_name", false).build();
TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
How to disassemble a memory range with GDB?
This isn't the direct answer to your question, but since you seem to just want to disassemble the binary, perhaps you could just use objdump
:
objdump -d program
This should give you its dissassembly. You can add -S
if you want it source-annotated.
transform object to array with lodash
Transforming object to array with plain JavaScript's(ECMAScript-2016
) Object.values
:
_x000D_
_x000D_
var obj = {_x000D_
22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.values(obj)_x000D_
_x000D_
console.log(values);
_x000D_
_x000D_
_x000D_
If you also want to keep the keys use Object.entries
and Array#map
like this:
_x000D_
_x000D_
var obj = {_x000D_
22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.entries(obj).map(([k, v]) => ({[k]: v}))_x000D_
_x000D_
console.log(values);
_x000D_
_x000D_
_x000D_
What is the difference between include and require in Ruby?
What's the difference between
"include" and "require" in Ruby?
Answer:
The include and require methods do
very different things.
The require method does what include
does in most other programming
languages: run another file. It also
tracks what you've required in the
past and won't require the same file
twice. To run another file without
this added functionality, you can use
the load method.
The include method takes all the
methods from another module and
includes them into the current module.
This is a language-level thing as
opposed to a file-level thing as with
require. The include method is the
primary way to "extend" classes with
other modules (usually referred to as
mix-ins). For example, if your class
defines the method "each", you can
include the mixin module Enumerable
and it can act as a collection. This
can be confusing as the include verb
is used very differently in other
languages.
Source
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require
.
Oddly enough, Ruby's require
is analogous to C's include
, while Ruby's include
is almost nothing like C's include
.
How to set a cookie for another domain
You cannot set cookies for another domain. Allowing this would present an enormous security flaw.
You need to get b.com to set the cookie. If a.com redirect the user to b.com/setcookie.php?c=value
The setcookie script could contain the following to set the cookie and redirect to the correct page on b.com
<?php
setcookie('a', $_GET['c']);
header("Location: b.com/landingpage.php");
?>
Removing spaces from a variable input using PowerShell 4.0
The Replace
operator means Replace something with something else; do not be confused with removal functionality.
Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace()
, nor -replace
modifies the original variable.
To remove all spaces, use 'Replace any space symbol with empty string'
$string = $string -replace '\s',''
To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use
$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '
or the more native System.String
method
$string = $string.Trim()
Regexp is preferred, because ' '
means only 'spacebar' symbol, and '\s'
means 'spacebar, tab and other space symbols'. Note that $string.Replace()
does 'Normal' replace, and $string -replace
does RegEx replace, which is more heavy but more functional.
Note that RegEx have some special symbols like dot (.
), braces ([]()
), slashes (\
), hats (^
), mathematical signs (+-
) or dollar signs ($
) that need do be escaped. ( 'my.space.com' -replace '\.','-'
=> 'my-space-com'
. A dollar sign with a number (ex $1
) must be used on a right part with care
'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033
UPDATE: You can also use $str = $str.Trim()
, along with TrimEnd()
and TrimStart()
. Read more at System.String MSDN page.
Get MAC address using shell script
Observe that the interface name and the MAC address are the first and last fields on a line with no leading whitespace.
If one of the indented lines contains inet addr:
the latest interface name and MAC address should be printed.
ifconfig -a |
awk '/^[a-z]/ { iface=$1; mac=$NF; next }
/inet addr:/ { print iface, mac }'
Note that multiple interfaces could meet your criteria. Then, the script will print multiple lines. (You can add ; exit
just before the final closing brace if you always only want to print the first match.)
How can I clone a JavaScript object except for one key?
What about this?
I never found this patter around but I was just trying to exclude one or more properties without the need of creating an extra object. This seems to do the job but there are some side effects I'm not able to see. For sure is not very readable.
const postData = {
token: 'secret-token',
publicKey: 'public is safe',
somethingElse: true,
};
const a = {
...(({token, ...rest} = postData) => (rest))(),
}
/**
a: {
publicKey: 'public is safe',
somethingElse: true,
}
*/
Error message "Strict standards: Only variables should be passed by reference"
Consider the following code:
error_reporting(E_STRICT);
class test {
function test_arr(&$a) {
var_dump($a);
}
function get_arr() {
return array(1, 2);
}
}
$t = new test;
$t->test_arr($t->get_arr());
This will generate the following output:
Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
The reason? The test::get_arr()
method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr()
method returns an array value.
To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:
function test_arr($a) {
var_dump($a);
}
Since you can't change the signature of array_shift
you can also use an intermediate variable:
$inter = get_arr();
$el = array_shift($inter);
What is the size of a pointer?
On 32-bit machine sizeof pointer is 32 bits ( 4 bytes), while on 64 bit machine it's 8 byte. Regardless of what data type they are pointing to, they have fixed size.
Android Studio-No Module
I was able to resolve this issue by performing a Gradle sync
To do this:
In project view, right click the root (in my example below, "JamsMusicPlayer"
Click "Synchronize {ProjectName}"
Once this completes, you should see a module in your "Run" dialog
How to replace captured groups only?
A simplier option is to just capture the digits and replace them.
_x000D_
_x000D_
const name = 'preceding_text_0_following_text';_x000D_
const matcher = /(\d+)/;_x000D_
_x000D_
// Replace with whatever you would like_x000D_
const newName = name.replace(matcher, 'NEW_STUFF');_x000D_
console.log("Full replace", newName);_x000D_
_x000D_
// Perform work on the match and replace using a function_x000D_
// In this case increment it using an arrow function_x000D_
const incrementedName = name.replace(matcher, (match) => ++match);_x000D_
console.log("Increment", incrementedName);
_x000D_
_x000D_
_x000D_
Resources
Convert YYYYMMDD to DATE
In your case it should be:
Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb
AngularJS - $http.post send data as json
i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer
will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}
Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php
It is unfortunately easy to program in PHP in a way that consumes memory faster than you realise. Copying strings, arrays and objects instead of using references will do it, though PHP 5 is supposed to do this more automatically than in PHP 4. But dealing with your data set in entirety over several steps is also wasteful compared to processing the smallest logical unit at a time. The classic example is working with large resultsets from a database: most programmers fetch the entire resultset into an array and then loop over it one or more times with foreach()
. It is much more memory efficient to use a while()
loop to fetch and process one row at a time. The same thing applies to processing a file.
How to load a text file into a Hive table stored as sequence files
You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.
Start with a tab delimited file:
% cat /tmp/input.txt
a b
a2 b2
create a sequence file
hive> create table test_sq(k string, v string) stored as sequencefile;
try to load; as expected, this will fail:
hive> load data local inpath '/tmp/input.txt' into table test_sq;
But with this table:
hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;
The load works just fine:
hive> load data local inpath '/tmp/input.txt' into table test_t;
OK
hive> select * from test_t;
OK
a b
a2 b2
Now load into the sequence table from the text table:
insert into table test_sq select * from test_t;
Can also do load/insert with overwrite to replace all.
Accessing a value in a tuple that is in a list
Ignacio's answer is what you want. However, as someone also learning Python, let me try to dissect it for you... As mentioned, it is a list comprehension (covered in DiveIntoPython3, for example). Here are a few points:
[x[1] for x in L]
- Notice the
[]
's around the line of code. These are what define a list. This tells you that this code returns a list, so it's of the list
type. Hence, this technique is called a "list comprehension."
- L is your original list. So you should define
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
prior to executing the above code.
x
is a variable that only exists in the comprehension - try to access x
outside of the comprehension, or type type(x)
after executing the above line and it will tell you NameError: name 'x' is not defined
, whereas type(L)
returns <class 'list'>
.
x[1]
points to the second item in each of the tuples whereas x[0]
would point to each of the first items.
- So this line of code literally reads "return the second item in a tuple for all tuples in list L."
It's tough to tell how much you attempted the problem prior to asking the question, but perhaps you just weren't familiar with comprehensions? I would spend some time reading through Chapter 3 of DiveIntoPython, or any resource on comprehensions. Good luck.
When should I use curly braces for ES6 import?
Dan Abramov's answer explains about the default exports and named exports.
Which to use?
Quoting David Herman: ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise.
However, in TypeScript named export is favored because of refactoring. Example, if you default export a class and rename it, the class name will change only in that file and not in the other references, with named exports class name will be renamed in all the references.
Named exports is also preferred for utilities.
Overall use whatever you prefer.
Additional
Default export is actually a named export with name default, so default export can be imported as:
import {default as Sample} from '../Sample.js';
Java: parse int value from a char
Try the following:
str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;
if u subtract by char '0', the ASCII value needs not to be known.
How to check if a table contains an element in Lua?
I know this is an old post, but I wanted to add something for posterity.
The simple way of handling the issue that you have is to make another table, of value to key.
ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.
function addValue(key, value)
if (value == nil) then
removeKey(key)
return
end
_primaryTable[key] = value
_secodaryTable[value] = key
end
function removeKey(key)
local value = _primaryTable[key]
if (value == nil) then
return
end
_primaryTable[key] = nil
_secondaryTable[value] = nil
end
function getValue(key)
return _primaryTable[key]
end
function containsValue(value)
return _secondaryTable[value] ~= nil
end
You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.
If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring
on it for example, and then use that as the key.
Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object.
If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.
The wording of the question however strongly suggests that you have a large number of items to deal with.
Date Difference in php on days?
Below code will give the output for number of days, by taking out the difference
between two dates..
$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);
How can I install a .ipa file to my iPhone simulator
UPDATE: For Xcode 8.0+ you need to follow below Steps:
- Download application from iTunes
- Select downloaded app, right click show in finder
- Copy
.ipa
file to Desktop, rename it to .zip
file
- Extract that
.zip
file and you will get directory with application name
Check that directory you will find app
file in Payload folder, copy this app
file
Go to ~/Library/Developer/CoreSimulator/Devices
FYI: Library
folder is hidden by default in mac, you can see hidden file using below command.
defaults write com.apple.finder AppleShowAllFiles YES;
killall Finder /System/Library/CoreServices/Finder.app
Now here you'll see many directories with long hexadecimal names, these all are simulators.
To find your desired simulator, sort these directories using "Arranged By > Date Modified".
Select that simulator file and go to below location.
<HEXADECIMAL-SIMULATOR-STRING>/data/Containers/Bundle/Application/
- Create new folder name with
<download-app-name>
and paste app
file in that folder
Open Terminal and run below command to install this application
xcrun simctl install booted <APP_FILE_PATH>
Example <APP_FILE_PATH>
will be looks like below:
~/Library/Developer/CoreSimulator/Devices/<HEXADECIMAL-SIMULATOR-STRING>/data/Containers/Bundle/Application/<APP_NAME>
Find duplicate entries in a column
Using:
SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
...will show you the ctn_no
value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:
SELECT t.ctn_no
FROM YOUR_TABLE t
WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
If you want to see the other column values associated with the duplicate, you'll want to use a self join:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no
How to sort an array of objects in Java?
You can try something like this:
List<Book> books = new ArrayList<Book>();
Collections.sort(books, new Comparator<Book>(){
public int compare(Book o1, Book o2)
{
return o1.name.compareTo(o2.name);
}
});
Python: How to use RegEx in an if statement?
The REPL makes it easy to learn APIs. Just run python
, create an object and then ask for help
:
$ python
>>> import re
>>> help(re.compile(r''))
at the command line shows, among other things:
search(...)
search(string[, pos[, endpos]])
--> match object or None
.
Scan through string looking for a match, and return a corresponding
MatchObject
instance. Return None
if no position in the string matches.
so you can do
regex = re.compile(regex_txt, re.IGNORECASE)
match = regex.search(content) # From your file reading code.
if match is not None:
# use match
Incidentally,
regex_txt = "facebook.com"
has a .
which matches any character, so re.compile("facebook.com").search("facebookkcom") is not None
is true because .
matches any character. Maybe
regex_txt = r"(?i)facebook\.com"
The \.
matches a literal "."
character instead of treating .
as a special regular expression operator.
The r"..."
bit means that the regular expression compiler gets the escape in \.
instead of the python parser interpreting it.
The (?i)
makes the regex case-insensitive like re.IGNORECASE
but self-contained.
Is there a /dev/null on Windows?
If you need to perform in Microsoft Windows the equivalent of a symlink to /dev/null
in Linux you would open and administrator's cmd
and type:
For files:
mklink c:\path\to\file.ext NUL:
Or, for directories:
mklink /D c:\path\to\dir NUL:
This will keep the file/direcotry always at 0 byte, and still return success to every write attempt.
JavaScript Regular Expression Email Validation
You should bear in mind that a-z, A-Z, 0-9, ., _ and - are not the only valid characters in the start of an email address.
Gmail, for example, lets you put a "+" sign in the address to "fake" a different email (e.g. [email protected] will also get email sent to [email protected]).
micky.o'[email protected] would not appreciate your code stopping them entering their address ... apostrophes are perfectly valid in email addresses.
The Closure "check" of a valid email address mentioned above is, as it states itself, quite naïve:
http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/format/emailaddress.js#198
I recommend being very open in your client side code, and then much more heavyweight like sending an email with a link to really check that it's "valid" (as in - syntactically valid for their provider, and also not misspelled).
Something like this:
var pattern = /[^@]+@[-a-z\.]\.[a-z\.]{2,6}/
Bearing in mind that theoretically you can have two @ signs in an email address, and I haven't even included characters beyond latin1 in the domain names!
http://www.eurid.eu/en/eu-domain-names/idns-eu
http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
UTF-8 encoding in JSP page
I used encoding filter which has solved my all encoding problem...
package com.dina.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
*
* @author DINANATH
*/
public class EncodingFilter implements Filter {
private String encoding = "utf-8";
public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
// response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String encodingParam = filterConfig.getInitParameter("encoding");
if (encodingParam != null) {
encoding = encodingParam;
}
}
public void destroy() {
// nothing todo
}
}
in web.xml
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>
com.dina.filter.EncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Python vs Cpython
A programming language implementation is a system for executing computer programs.
There are two general approaches to programming language implementation:
- Interpretation: An interpreter takes as input a program in some language, and performs the actions written in that language on some machine.
- Compilation: A compiler takes as input a program in some language, and translates that program into some other language, which may serve as input to another interpreter or another compiler.
Python is an interpreted high-level programming language created by Guido van Rossum in 1991.
CPython is reference version of the Python computing language, which is written in C created by Guido van Rossum too.
Other list of Python Implementations
Source
Python str vs unicode types
unicode
is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8
, latin-1
...).
Note that unicode
is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.
On the contrary str
in Python 2 is a plain sequence of bytes. It does not represent text!
You can think of unicode
as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str
.
Note: In Python 3, unicode
was renamed to str
and there is a new bytes
type for a plain sequence of bytes.
Some differences that you can see:
>>> len(u'à') # a single code point
1
>>> len('à') # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8') # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?
Note that using str
you have a lower-level control on the single bytes of a specific encoding representation, while using unicode
you can only control at the code-point level. For example you can do:
>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù
What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text.
You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.
How can I pass arguments to anonymous functions in JavaScript?
Example:
<input type="button" value="Click me" id="myButton">
<script>
var myButton = document.getElementById("myButton");
var test = "zipzambam";
myButton.onclick = function(eventObject) {
if (!eventObject) {
eventObject = window.event;
}
if (!eventObject.target) {
eventObject.target = eventObject.srcElement;
}
alert(eventObject.target);
alert(test);
};
(function(myMessage) {
alert(myMessage);
})("Hello");
</script>
Correct way to integrate jQuery plugins in AngularJS
i have alreay 2 situations where directives and services/factories didnt play well.
the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).
in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.
i even tried to make a directive with a controller and an isolated-scope
only when i moved everything to a controller and it worked like magic.
example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS
How do I get a python program to do nothing?
You could use a pass
statement:
if condition:
pass
Python 2.x documentation
Python 3.x documentation
However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if
statement.
If you have something like this:
if condition: # condition in your case being `num2 == num5`
pass
else:
do_something()
You can in general change it to this:
if not condition:
do_something()
But in this specific case you could (and should) do this:
if num2 != num5: # != is the not-equal-to operator
do_something()
Fitting polynomial model to data in R
Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:
x <- 1:10
y <- x + c(-0.5,0.5)
plot(x,y, xlim=c(0,11), ylim=c(-1,12))
fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )
fit7 <- lm( y ~ x + cos(x*pi) )
xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')
Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).
How to enable local network users to access my WAMP sites?
it's simple , and it's really worked for me .
run you wamp server => click right mouse button => and click on "put online"
then open your cmd as an administrateur , and pass in this commande word
ipconfig => and press enter
then lot of adresses show-up , then you have just to take the first one , it's look like this example: Adresse IPv4. . . . . . . . . . . . . .: 192.168.67.190
well done ! , that's the adresse, that you will use to cennecte to your wampserver in local.
Is there a way to detect if a browser window is not currently active?
Since originally writing this answer, a new specification has reached recommendation status thanks to the W3C. The Page Visibility API (on MDN) now allows us to more accurately detect when a page is hidden to the user.
document.addEventListener("visibilitychange", onchange);
Current browser support:
- Chrome 13+
- Internet Explorer 10+
- Firefox 10+
- Opera 12.10+ [read notes]
The following code falls back to the less reliable blur/focus method in incompatible browsers:
(function() {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;
function onchange (evt) {
var v = "visible", h = "hidden",
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};
evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
}
// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});
})();
onfocusin
and onfocusout
are required for IE 9 and lower, while all others make use of onfocus
and onblur
, except for iOS, which uses onpageshow
and onpagehide
.
Postgresql Windows, is there a default password?
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
Reference
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
Can't find @Nullable inside javax.annotation.*
In case someone has this while trying to compile an Android project, there is an alternative Nullable implementation in android.support.annotation.Nullable
. So take care which package you've referenced in your import
s.
C# '@' before a String
It means to interpret the string literally (that is, you cannot escape any characters within the string if you use the @ prefix). It enhances readability in cases where it can be used.
For example, if you were working with a UNC path, this:
@"\\servername\share\folder"
is nicer than this:
"\\\\servername\\share\\folder"
Escape regex special characters in a Python string
I'm surprised no one has mentioned using regular expressions via re.sub()
:
import re
print re.sub(r'([\"])', r'\\\1', 'it\'s "this"') # it's \"this\"
print re.sub(r"([\'])", r'\\\1', 'it\'s "this"') # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"') # it\'s\ \"this\"
Important things to note:
- In the search pattern, include
\
as well as the character(s) you're looking for.
You're going to be using \
to escape your characters, so you need to escape
that as well.
- Put parentheses around the search pattern, e.g.
([\"])
, so that the substitution
pattern can use the found character when it adds \
in front of it. (That's what
\1
does: uses the value of the first parenthesized group.)
- The
r
in front of r'([\"])'
means it's a raw string. Raw strings use different
rules for escaping backslashes. To write ([\"])
as a plain string, you'd need to
double all the backslashes and write '([\\"])'
. Raw strings are friendlier when
you're writing regular expressions.
- In the substitution pattern, you need to escape
\
to distinguish it from a
backslash that precedes a substitution group, e.g. \1
, hence r'\\\1'
. To write
that as a plain string, you'd need '\\\\\\1'
— and nobody wants that.
How do I parse a HTML page with Node.js
November 2020 Update
I searched for the top NodeJS html parser libraries.
Because my use cases didn't require a library with many features, I could focus on stability and performance.
By stability I mean that I want the library to be used long enough by the community in order to find bugs and that it will be still maintained and that open issues will be closed.
Its hard to understand the future of an open source library, but I did a small summary based on the top 10 libraries in openbase.
I divided into 2 groups according to the last commit (and on each group the order is according to Github starts):
Last commit is in the last 6 months:
jsdom - Last commit: 3 Months, Open issues: 331, Github stars: 14.9K
.
htmlparser2 - Last commit: 8 days, Open issues: 2, Github stars: 2.7K
.
parse5 - Last commit: 2 Months, Open issues: 21, Github stars: 2.5K
.
swagger-parser - Last commit: 2 Months, Open issues: 48, Github stars: 663
.
html-parse-stringify - Last commit: 4 Months, Open issues: 3, Github stars: 215
.
node-html-parser - Last commit: 7 days, Open issues: 15, Github stars: 205
.
Last commit is 6 months and above:
cheerio - Last commit: 1 year, Open issues: 174, Github stars: 22.9K
.
koa-bodyparser - Last commit: 6 months, Open issues: 9, Github stars: 1.1K
.
sax-js - Last commit: 3 Years, Open issues: 65, Github stars: 941
.
draftjs-to-html - Last commit: 1 Year, Open issues: 27, Github stars: 233
.
I picked Node-html-parser because it seems quiet fast and very active at this moment.
(*) Openbase adds much more information regarding each library like the number of contributors (with +3 commits), weekly downloads, Monthly commits, Version etc'.
(**) The table above is a snapshot according to the specific time and date - I would check the reference again and as a first step check the level of recent activity and then dive into the smaller details.
How do I set the background color of my main screen in Flutter?
Here's one way that I found to do it. I don't know if there are better ways, or what the trade-offs are.
Container "tries to be as big as possible", according to https://flutter.io/layout/. Also, Container can take a decoration
, which can be a BoxDecoration, which can have a color
(which, is the background color).
Here's a sample that does indeed fill the screen with red, and puts "Hello, World!" into the center:
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(color: Colors.red),
child: new Center(
child: new Text("Hello, World!"),
),
);
}
}
Note, the Container is returned by the MyApp build(). The Container has a decoration and a child, which is the centered text.
See it in action here:
MySQL: Enable LOAD DATA LOCAL INFILE
I solved this problem on MySQL 8.0.11 with the mysql terminal command:
SET GLOBAL local_infile = true;
I mean I logged in first with the usual:
mysql -u user -p*
After that you can see the status with the command:
SHOW GLOBAL VARIABLES LIKE 'local_infile';
It should be ON. I will not be writing about security issued with loading local files into database here.
Curl and PHP - how can I pass a json through curl by PUT,POST,GET
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
- $result['status'] is the HTTP response code
- $result['data'] an array with the JSON response parsed
- $result['header'] a string with the response headers
Hope it helps
How to get substring of NSString?
Here is a little combination of @Regexident Option 1 and @Garett answers, to get a powerful string cutter between a prefix and suffix, with MORE...ANDMORE words on it.
NSString *haystack = @"MOREvalue:hello World:valueANDMORE";
NSString *prefix = @"value:";
NSString *suffix = @":value";
NSRange prefixRange = [haystack rangeOfString:prefix];
NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix];
NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle);
How can I get date and time formats based on Culture Info?
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"));
How can I get an HTTP response body as a string?
The Answer by McDowell is correct one. However if you try other suggestion in few of the posts above.
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
response = EntityUtils.toString(responseEntity);
S.O.P (response);
}
Then it will give you illegalStateException stating that content is already consumed.
how to access parent window object using jquery?
If you are in a po-up and you want to access the opening window, use window.opener
.
The easiest would be if you could load JQuery in the parent window as well:
window.opener.$("#serverMsg").html
// this uses JQuery in the parent window
or you could use plain old document.getElementById
to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):
element = window.opener.document.getElementById("serverMsg");
element = $(element);
If you are in an iframe or frameset and want to access the parent frame, use window.parent
instead of window.opener
.
According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.
HTML Button : Navigate to Other Page - Different Approaches
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install
My 2 cents on this error, even if not related to an export/import scenario:
when adding the mobile provisioning certificate (i.e. the PROV
file), DO NOT drag the file from Finder to Keychain Access. Instead, just double click the PROV file within Finder, while keeping the Keychain Access application running somewhere.
I've actually seen my former provisioning item in Keychain (the one with yellow light) being substituted with a new, green one with same name and app ID. HTH
SVN Commit specific files
I make a (sub)folder named "hide", move the file I don't want committed to there.
Then do my commit, ignoring complaint about the missing file.
Then move the hidden file from hide back to ./
I know of no downside to this tactic.
Dynamically load a JavaScript file
Here is a simple one with callback and IE support:
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
//jQuery loaded
console.log('jquery loaded');
});
How to escape single quotes in MySQL
The way I do, by using Delphi:
TheString to "escape":
TheString=" bla bla bla 'em some more apo:S 'em and so on ";
Solution:
StringReplace(TheString, #39,'\'+#39, [rfReplaceAll, rfIgnoreCase]);
Result:
TheString=" bla bla bla \'em some more apo:S \'em and so on ";
This function will replace all Char(39) with "\'" allowing you to insert or update text fields in MySQL without any problem.
Similar functions are found in all programming languages!
Non-static variable cannot be referenced from a static context
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color
. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()
). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main()
method creates an instance of the class it contains (sounds strange but since main()
is created with the class instead of with the instance, it can do this) and then calls an instance method (run()
).
Plotting with C#
FWIW, you probably want to look at F# instead of C# in the context of technical computing because F# is specifically designed for that purpose. However, I developed my own commercial plotting library because I was not satisfied with anything freely available on .NET.
html table span entire width?
Just in case you're using bootstrap 4, you can add px-0
(set left/right padding to 0) and mx-0
(set left/right margin to 0) CSS class to body tag, like below:
<body class="px-0; mx-0">
<!--your body HTML-->
</body>
What is JavaScript garbage collection?
Good quote taken from a blog
The DOM component is "garbage collected", as is the JScript component, which means that if you create an object within either component, and then lose track of that object, it will eventually be cleaned up.
For example:
function makeABigObject() {
var bigArray = new Array(20000);
}
When you call that function, the JScript component creates an object (named bigArray) that is accessible within the function. As soon as the function returns, though, you "lose track" of bigArray because there's no way to refer to it anymore. Well, the JScript component realizes that you've lost track of it, and so bigArray is cleaned up--its memory is reclaimed. The same sort of thing works in the DOM component. If you say document.createElement('div')
, or something similar, then the DOM component creates an object for you. Once you lose track of that object somehow, the DOM component will clean up the related.
Random word generator- Python
There is a package random_word could implement this request very conveniently:
$ pip install random-word
from random_word import RandomWords
r = RandomWords()
# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()
Lollipop : draw behind statusBar with its color set to transparent
I had the same problem so i create ImageView that draw behind status bar API 19+
Set custom image behind Status Bar gist.github.com
public static void setTransparent(Activity activity, int imageRes) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
// set flags
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
} else {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
// get root content of system window
//ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
// rootView.setFitsSystemWindows(true);
// rootView.setClipToPadding(true);
ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
if (contentView.getChildCount() > 1) {
contentView.removeViewAt(1);
}
// get status bar height
int res = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
int height = 0;
if (res != 0)
height = activity.getResources().getDimensionPixelSize(res);
// create new imageview and set resource id
ImageView image = new ImageView(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
image.setLayoutParams(params);
image.setImageResource(imageRes);
image.setScaleType(ScaleType.MATRIX);
// add image view to content view
contentView.addView(image);
// rootView.setFitsSystemWindows(true);
}
Any way to make a WPF textblock selectable?
Adding to @torvin's answer and as @Dave Huang mentioned in the comments if you have TextTrimming="CharacterEllipsis"
enabled the application crashes when you hover over the ellipsis.
I tried other options mentioned in the thread about using a TextBox but it really doesn't seem to be the solution either as it doesn't show the 'ellipsis' and also if the text is too long to fit the container selecting the content of the textbox 'scrolls' internally which isn't a TextBlock behaviour.
I think the best solution is @torvin's answer but has the nasty crash when hovering over the ellipsis.
I know it isn't pretty, but subscribing/unsubscribing internally to unhandled exceptions and handling the exception was the only way I found of solving this problem, please share if somebody has a better solution :)
public class SelectableTextBlock : TextBlock
{
static SelectableTextBlock()
{
FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);
// remove the focus rectangle around the control
FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
}
private readonly TextEditorWrapper _editor;
public SelectableTextBlock()
{
_editor = TextEditorWrapper.CreateFor(this);
this.Loaded += (sender, args) => {
this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
};
this.Unloaded += (sender, args) => {
this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;
};
}
private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (!string.IsNullOrEmpty(e?.Exception?.StackTrace))
{
if (e.Exception.StackTrace.Contains("System.Windows.Controls.TextBlock.GetTextPositionFromDistance"))
{
e.Handled = true;
}
}
}
}
checked = "checked" vs checked = true
checked
attribute is a boolean value so "checked"
value of other "string"
except boolean false
converts to true
.
Any string value will be true. Also presence of attribute make it true:
<input type="checkbox" checked>
You can make it uncheked only making boolean change in DOM using JS.
So the answer is: they are equal.
w3c
c++ exception : throwing std::string
All these work:
#include <iostream>
using namespace std;
//Good, because manual memory management isn't needed and this uses
//less heap memory (or no heap memory) so this is safer if
//used in a low memory situation
void f() { throw string("foo"); }
//Valid, but avoid manual memory management if there's no reason to use it
void g() { throw new string("foo"); }
//Best. Just a pointer to a string literal, so no allocation is needed,
//saving on cleanup, and removing a chance for an allocation to fail.
void h() { throw "foo"; }
int main() {
try { f(); } catch (string s) { cout << s << endl; }
try { g(); } catch (string* s) { cout << *s << endl; delete s; }
try { h(); } catch (const char* s) { cout << s << endl; }
return 0;
}
You should prefer h to f to g. Note that in the least preferable option you need to free the memory explicitly.
What is the purpose of class methods?
I was asking myself the same question few times. And even though the guys here tried hard to explain it, IMHO the best answer (and simplest) answer I have found is the description of the Class method in the Python Documentation.
There is also reference to the Static method. And in case someone already know instance methods (which I assume), this answer might be the final piece to put it all together...
Further and deeper elaboration on this topic can be found also in the documentation:
The standard type hierarchy (scroll down to Instance methods section)
Download file from web in Python 3
You can use wget which is popular downloading shell tool for that. https://pypi.python.org/pypi/wget
This will be the simplest method since it does not need to open up the destination file. Here is an example.
import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'
wget.download(url, '/Users/scott/Downloads/cat4.jpg')
What does the "static" modifier after "import" mean?
The import
allows the java programmer to access classes of a package without package qualification.
The static import
feature allows to access the static members of a class without the class qualification.
The import
provides accessibility to classes and interface whereas static import
provides accessibility to static members of the class.
Example :
With import
import java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
System.out.println("Hello");
System.out.println("Java");
}
}
With static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
See also : What is static import in Java 5
Read a zipped file as a pandas DataFrame
It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.
import pandas as pd
df = pd.read_csv('filename.zip')
(Of course you will need to specify separator, header, etc. if they are different from the defaults.)
How to find the duration of difference between two dates in java?
This is a program I wrote, which gets the number of days between 2 dates(no time here).
import java.util.Scanner;
public class HelloWorld {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter starting date separated by dots: ");
String inp1 = s.nextLine();
System.out.print("Enter ending date separated by dots: ");
String inp2 = s.nextLine();
int[] nodim = {
0,
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};
String[] inpArr1 = split(inp1);
String[] inpArr2 = split(inp2);
int d1 = Integer.parseInt(inpArr1[0]);
int m1 = Integer.parseInt(inpArr1[1]);
int y1 = Integer.parseInt(inpArr1[2]);
int d2 = Integer.parseInt(inpArr2[0]);
int m2 = Integer.parseInt(inpArr2[1]);
int y2 = Integer.parseInt(inpArr2[2]);
if (y1 % 4 == 0) nodim[2] = 29;
int diff = m1 == m2 && y1 == y2 ? d2 - (d1 - 1) : (nodim[m1] - (d1 - 1));
int mm1 = m1 + 1, mm2 = m2 - 1, yy1 = y1, yy2 = y2;
for (; yy1 <= yy2; yy1++, mm1 = 1) {
mm2 = yy1 == yy2 ? (m2 - 1) : 12;
if (yy1 % 4 == 0) nodim[2] = 29;
else nodim[2] = 28;
if (mm2 == 0) {
mm2 = 12;
yy2 = yy2 - 1;
}
for (; mm1 <= mm2 && yy1 <= yy2; mm1++) diff = diff + nodim[mm1];
}
System.out.print("No. of days from " + inp1 + " to " + inp2 + " is " + diff);
}
public static String[] split(String s) {
String[] retval = {
"",
"",
""
};
s = s + ".";
s = s + " ";
for (int i = 0; i <= 2; i++) {
retval[i] = s.substring(0, s.indexOf("."));
s = s.substring((s.indexOf(".") + 1), s.length());
}
return retval;
}
}
http://pastebin.com/HRsjTtUf
How to reduce a huge excel file
I save files in .XLSB format to cut size. The XLSB also allows for VBA and macros to stay with the file. I've seen 50 meg files down to less than 10 with the Binary formatting.
How to create UILabel programmatically using Swift?
An alternative using a closure to separate out the code into something a bit neater using Swift 4:
class theViewController: UIViewController {
/** Create the UILabel */
var theLabel: UILabel = {
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.textColor = UIColor.white
label.textAlignment = .left
label.numberOfLines = 3
label.font = UIFont(name: "Helvetica-Bold", size: 22)
return label
}()
override func viewDidLoad() {
/** Add theLabel to the ViewControllers view */
view.addSubview(theLabel)
}
override func viewDidLayoutSubviews() {
/* Set the frame when the layout is changed */
theLabel.frame = CGRect(x: 0,
y: 0,
width: view.frame.width - 30,
height: 24)
}
}
As a note, attributes for theLabel
can still be changed whenever using functions in the VC. You're just setting various defaults inside the closure and minimizing clutter in functions like viewDidLoad()
Large Numbers in Java
import java.math.BigInteger;
import java.util.*;
class A
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.print("Enter The First Number= ");
String a=in.next();
System.out.print("Enter The Second Number= ");
String b=in.next();
BigInteger obj=new BigInteger(a);
BigInteger obj1=new BigInteger(b);
System.out.println("Sum="+obj.add(obj1));
}
}
SQL grouping by all the columns
Here is my suggestion:
DECLARE @FIELDS VARCHAR(MAX), @NUM INT
--DROP TABLE #FIELD_LIST
SET @NUM = 1
SET @FIELDS = ''
SELECT
'SEQ' = IDENTITY(int,1,1) ,
COLUMN_NAME
INTO #FIELD_LIST
FROM Req.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'new340B'
WHILE @NUM <= (SELECT COUNT(*) FROM #FIELD_LIST)
BEGIN
SET @FIELDS = @FIELDS + ',' + (SELECT COLUMN_NAME FROM #FIELD_LIST WHERE SEQ = @NUM)
SET @NUM = @NUM + 1
END
SET @FIELDS = RIGHT(@FIELDS,LEN(@FIELDS)-1)
EXEC('SELECT ' + @FIELDS + ', COUNT(*) AS QTY FROM [Req].[dbo].[new340B] GROUP BY ' + @FIELDS + ' HAVING COUNT(*) > 1 ')
Access parent URL from iframe
Get All Parent Iframe functions and HTML
var parent = $(window.frameElement).parent();
//alert(parent+"TESTING");
var parentElement=window.frameElement.parentElement.parentElement.parentElement.parentElement;
var Ifram=parentElement.children;
var GetUframClass=Ifram[9].ownerDocument.activeElement.className;
var Decision_URLLl=parentElement.ownerDocument.activeElement.contentDocument.URL;
Difference between Ctrl+Shift+F and Ctrl+I in Eclipse
If you press CTRL + I it will just format tabs/whitespaces in code and pressing CTRL + SHIFT + F format all code that is format tabs/whitespaces and also divide code lines in a way that it is visible without horizontal scroll.
Swift - Remove " character from string
You've instantiated text2 as an Optional (e.g. var text2: String?).
This is why you receive Optional("5") in your string.
take away the ? and replace with:
var text2: String = ""
Change project name on Android Studio
For one, I'd strongly suggest updating to the latest Android Studio (0.3.7 as of now); there are tons of bug fixes.
You're running into bug https://code.google.com/p/android/issues/detail?id=57692, which is that if you try to use the UI to rename modules or your project, it doesn't update the build files. Sorry, it's really broken right now. I'd suggest changing the directory names directly in the filesystem, and updating your settings.gradle
file to reflect the changes. Your project on disk should look something like this (with many more files than what's shown here):
projectFolder
|--settings.gradle
|--applicationModuleFolder
| |--build.gradle
| |--src
it uses projectFolder's name as the project name and applicationModuleFolder as the name of the module that your Android App lives in (the upper and lower outlined boxes in your screenshot, respectively). I think the way your project is set up now, they both have the same name; you can rename both to the same new name if you like, or you can give them different names; it doesn't matter.
Once they're renamed, edit your settings.gradle
file; it will look something like:
include ':applicationModuleFolder'
just change the name to your new name there as well. Once these changes are made, click the Sync Project with Gradle Files button in the toolbar (if you're running a very old version of Android Studio, it may not have that button, so you can close the project and reopen it in that case) and it should pick up the changes.
Iterate over array of objects in Typescript
In Typescript and ES6 you can also use for..of:
for (var product of products) {
console.log(product.product_desc)
}
which will be transcoded to javascript:
for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
var product = products_1[_i];
console.log(product.product_desc);
}
SOAP request in PHP with CURL
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
How to Install Font Awesome in Laravel Mix
I am using Laravel 5.5.14 and none of the above worked for me. So here are the steps I did to make it work.
1.Install font-awesome by using npm:
npm install font-awesome --save
2.Move the fonts to your public directory by adding this line in your webpack.mixin.js
mix.copyDirectory('node_modules/font-awesome/fonts', 'public/fonts/font-awesome');
3.Open your app.scss to specify the path of the fonts in your node_modules and which relative path to use for compilation:
$fa-font-path: "../fonts/font-awesome" !default;
@import "~font-awesome/scss/font-awesome.scss";
insert vertical divider line between two nested divs, not full height
Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.
See it here: http://jsfiddle.net/ZSgLJ/
#left {
float: left;
width: 44%;
margin: 0;
padding: 0;
border-right: 1px solid white;
height:400px;
}
#right {
position: relative;
float: right;
width: 49%;
margin: 0;
padding: 0;
height:400px;
}
#blue_box {
background-color:blue;
border-radius: 10px;
-moz-border-radius:10px;
-webkit-border-radius: 10px;
width: 45%;
min-width: 400px;
max-width: 600px;
padding: 2%;
float: right;
}
MySQL count occurrences greater than 2
To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:
SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1
To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:
SELECT COUNT(*)
FROM
(
SELECT NULL
FROM words
GROUP BY word
HAVING COUNT(*) > 1
) T1
How can I put CSS and HTML code in the same file?
<html>
<head>
<style type="text/css">
.title {
color: blue;
text-decoration: bold;
text-size: 1em;
}
.author {
color: gray;
}
</style>
</head>
<body>
<p>
<span class="title">La super bonne</span>
<span class="author">proposée par Jérém</span>
</p>
</body>
</html>
On a side note, it would have been much easier to just do this.
Why can't I use the 'await' operator within the body of a lock statement?
I did try using a Monitor (code below) which appears to work but has a GOTCHA... when you have multiple threads it will give... System.Threading.SynchronizationLockException Object synchronization method was called from an unsynchronized block of code.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MyNamespace
{
public class ThreadsafeFooModifier :
{
private readonly object _lockObject;
public async Task<FooResponse> ModifyFooAsync()
{
FooResponse result;
Monitor.Enter(_lockObject);
try
{
result = await SomeFunctionToModifyFooAsync();
}
finally
{
Monitor.Exit(_lockObject);
}
return result;
}
}
}
Prior to this I was simply doing this, but it was in an ASP.NET controller so it resulted in a deadlock.
public async Task<FooResponse> ModifyFooAsync()
{
lock(lockObject)
{
return SomeFunctionToModifyFooAsync.Result;
}
}
Nullable DateTime conversion
You can try this
var lastPostDate = reader[3] == DBNull.Value ?
default(DateTime?):
Convert.ToDateTime(reader[3]);
How to declare std::unique_ptr and what is the use of it?
From cppreference, one of the std::unique_ptr
constructors is
explicit unique_ptr( pointer p ) noexcept;
So to create a new std::unique_ptr
is to pass a pointer to its constructor.
unique_ptr<int> uptr (new int(3));
Or it is the same as
int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);
The different is you don't have to clean up after using it. If you don't use std::unique_ptr
(smart pointer), you will have to delete it like this
delete int_ptr;
when you no longer need it or it will cause a memory leak.
align right in a table cell with CSS
Use
text-align: right
The text-align CSS property describes
how inline content like text is
aligned in its parent block element.
text-align does not control the
alignment of block elements itself,
only their inline content.
See
text-align
<td class='alnright'>text to be aligned to right</td>
<style>
.alnright { text-align: right; }
</style>
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.