Oracle listener not running and won't start
I solved it by updating listener.ora file inside oracle directory oraclexe\app\oracle\product\11.2.0\server\network\ADMIN.
Why did it happen to me was because I changed my system name but inside listener.ora there was old name for HOST.
This might be one of the reasons... for those who still face such issue might think of this possibility as well.
Oracle - What TNS Names file am I using?
On my development machine I have three different versions of Oracle client software. I manage the tnsnames.ora
file in one of them. In the other two, I have entered in the tnsnames.ora
file:
ifile=path_to_tnsnames.ora_file/tnsnames.ora
This way, if for some reason the wrong tnsnames.ora
file is used by a client, it will always end up at the up-to-date version.
Oracle TNS names not showing when adding new connection to SQL Developer
None of the above changes made any difference in my case. I could run TNS_PING in the command window but SQL Developer couldn't figure out where tnsnames.ora was.
The issue in my case (Windows 7 - 64 bit - Enterprise ) was that the Oracle installer pointed the Start menu shortcut to the wrong version of SQL Developer. There appear to be three SQL Developer instances that accompany the installer. One is in %ORACLE_HOME%\client_1\sqldeveloper\ and two are in %ORACLE_HOME%\client_1\sqldeveloper\bin\ .
The installer installed a start menu shortcut that pointed at a version in the bin directory that simply did not function. It would ask for a password every time I started SQL Developer, not remember choices I had made and displayed a blank list when I chose TNS as the connection mechanism. It also does not have the TNS Directory field in the Database advanced settings referenced in other posts.
I tossed the old Start shortcut and installed a shortcut to %ORACLE_HOME%\client_1\sqldeveloper\sqldeveloper.exe . That change fixed the problem in my case.
Oracle ORA-12154: TNS: Could not resolve service name Error?
We also had the similar issue. What we found out that we had provided multiple aliases for our connection string in tnsnames.ora, something like:
svc01, svc02=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxx)(port=50))(CONNECT_DATA=(SERVER=DEDICATED)(service_name=yyyysvc.world)))
so when creating a connection using ODBC, when we selected the value for TNS service name, the auto populate was showing 'svc01,' (please note the extra comma there). As soon as we removed the comma, it started working for us.
How can I convert an HTML table to CSV?
Here is an example using pQuery and Spreadsheet::WriteExcel:
use strict;
use warnings;
use Spreadsheet::WriteExcel;
use pQuery;
my $workbook = Spreadsheet::WriteExcel->new( 'data.xls' );
my $sheet = $workbook->add_worksheet;
my $row = 0;
pQuery( 'http://www.blahblah.site' )->find( 'tr' )->each( sub{
my $col = 0;
pQuery( $_ )->find( 'td' )->each( sub{
$sheet->write( $row, $col++, $_->innerHTML );
});
$row++;
});
$workbook->close;
The example simply extracts all tr tags that it finds into an excel file. You can easily tailor it to pick up specific table or even trigger a new excel file per table tag.
Further things to consider:
- You may want to pick up td tags to create excel header(s).
- And you may have issues with rowspan & colspan.
To see if rowspan or colspan is being used you can:
pQuery( $data )->find( 'td' )->each( sub{
my $number_of_cols_spanned = $_->getAttribute( 'colspan' );
});
Django Template Variables and Javascript
I have found we can pass Django variables to javascript functions like this:-
<button type="button" onclick="myJavascriptFunction('{{ my_django_variable }}')"></button>
<script>
myJavascriptFunction(djangoVariable){
alert(djangoVariable);
}
</script>
Explanation of "ClassCastException" in Java
Exception is not a subclass of RuntimeException -> ClassCastException
final Object exception = new Exception();
final Exception data = (RuntimeException)exception ;
System.out.println(data);
Spring Boot + JPA : Column name annotation ignored
If you want to use @Column(...), then use small-case letters always even though your actual DB column is in camel-case.
Example: If your actual DB column name is TestName
then use:
@Column(name="testname") //all small-case
If you don't like that, then simply change the actual DB column name into:
test_name
Quickest way to clear all sheet contents VBA
The .Cells range isn't limited to ones that are being used, so your code is clearing the content of 1,048,576 rows and 16,384 columns - 17,179,869,184 total cells. That's going to take a while. Just clear the UsedRange instead:
Sheets("Zeros").UsedRange.ClearContents
Alternately, you can delete the sheet and re-add it:
Application.DisplayAlerts = False
Sheets("Zeros").Delete
Application.DisplayAlerts = True
Dim sheet As Worksheet
Set sheet = Sheets.Add
sheet.Name = "Zeros"
Multiple SQL joins
It will be something like this:
SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
Books b
JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
JOIN Publishers p ON p._PublisherID = b.PublisherID
JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
JOIN Writer w ON w._WritersID = wb._Writers_WriterID
You use the join
statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b
the Books
table will be referred to as b
in the rest of the query. This makes for less typing.
FYI your naming convention is very strange, I would expect it to be more like this:
Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID
Representational state transfer (REST) and Simple Object Access Protocol (SOAP)
SOAP – "Simple Object Access Protocol"
SOAP is a slight of transferring messages, or little amounts of information over the Internet. SOAP messages are formatted in XML and are typically sent controlling HTTP.
REST – "REpresentational State Transfer"
REST is a rudimentary proceed of eventuality and receiving information between fan and server and it doesn't have unequivocally many standards defined. You can send and accept information as JSON, XML or even plain text. It's light weighted compared to SOAP.
Attach event to dynamic elements in javascript
I've made a simple function for this.
The _case
function allows you to not only get the target, but also get the parent element where you bind the event on.
The callback function returns the event which holds the target (evt.target
) and the parent element matching the selector (this
). Here you can do the stuff you need after the element is clicked.
I've not yet decided which is better, the if-else
or the switch
_x000D_
_x000D_
var _case = function(evt, selector, cb) {_x000D_
var _this = evt.target.closest(selector);_x000D_
if (_this && _this.nodeType) {_x000D_
cb.call(_this, evt);_x000D_
return true;_x000D_
} else { return false; }_x000D_
}_x000D_
_x000D_
document.getElementById('ifelse').addEventListener('click', function(evt) {_x000D_
if (_case(evt, '.parent1', function(evt) {_x000D_
console.log('1: ', this, evt.target);_x000D_
})) return false;_x000D_
_x000D_
if (_case(evt, '.parent2', function(evt) {_x000D_
console.log('2: ', this, evt.target);_x000D_
})) return false;_x000D_
_x000D_
console.log('ifelse: ', this);_x000D_
})_x000D_
_x000D_
_x000D_
document.getElementById('switch').addEventListener('click', function(evt) {_x000D_
switch (true) {_x000D_
case _case(evt, '.parent3', function(evt) {_x000D_
console.log('3: ', this, evt.target);_x000D_
}): break;_x000D_
case _case(evt, '.parent4', function(evt) {_x000D_
console.log('4: ', this, evt.target);_x000D_
}): break;_x000D_
default:_x000D_
console.log('switch: ', this);_x000D_
break;_x000D_
}_x000D_
})
_x000D_
#ifelse {_x000D_
background: red;_x000D_
height: 100px;_x000D_
}_x000D_
#switch {_x000D_
background: yellow;_x000D_
height: 100px;_x000D_
}
_x000D_
<div id="ifelse">_x000D_
<div class="parent1">_x000D_
<div class="child1">Click me 1!</div>_x000D_
</div>_x000D_
<div class="parent2">_x000D_
<div class="child2">Click me 2!</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div id="switch">_x000D_
<div class="parent3">_x000D_
<div class="child3">Click me 3!</div>_x000D_
</div>_x000D_
<div class="parent4">_x000D_
<div class="child4">Click me 4!</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Hope it helps!
Add Expires headers
The easiest way to add these headers is a .htaccess
file that adds some configuration to your server. If the assets are hosted on a server that you don't control, there's nothing you can do about it.
Note that some hosting providers will not let you use .htaccess
files, so check their terms if it doesn't seem to work.
The HTML5Boilerplate project has an excellent .htaccess
file that covers the necessary settings. See the relevant part of the file at their Github repository
These are the important bits
# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------
# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".
<IfModule mod_expires.c>
ExpiresActive on
# Your document html
ExpiresByType text/html "access plus 0 seconds"
# Media: images, video, audio
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
# CSS and JavaScript
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
</IfModule>
They have documented what that file does, the most important bit is that you need to rename your CSS and Javascript files whenever they change, because your visitor's browsers will not check them again for a year, once they are cached.
Handle spring security authentication exceptions with @ExceptionHandler
Update: If you like and prefer to see the code directly, then I have two examples for you, one using standard Spring Security which is what you are looking for, the other one is using the equivalent of Reactive Web and Reactive Security:
- Normal Web + Jwt Security
- Reactive Jwt
The one that I always use for my JSON based endpoints looks like the following:
@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {
@Autowired
ObjectMapper mapper;
private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException e)
throws IOException, ServletException {
// Called when the user tries to access an endpoint which requires to be authenticated
// we just return unauthorizaed
logger.error("Unauthorized error. Message - {}", e.getMessage());
ServletServerHttpResponse res = new ServletServerHttpResponse(response);
res.setStatusCode(HttpStatus.UNAUTHORIZED);
res.getServletResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
res.getBody().write(mapper.writeValueAsString(new ErrorResponse("You must authenticated")).getBytes());
}
}
The object mapper becomes a bean once you add the spring web starter, but I prefer to customize it, so here is my implementation for ObjectMapper:
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.modules(new JavaTimeModule());
// for example: Use created_at instead of createdAt
builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
// skip null fields
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return builder;
}
The default AuthenticationEntryPoint you set in your WebSecurityConfigurerAdapter class:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ............
@Autowired
private JwtAuthEntryPoint unauthorizedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
// .antMatchers("/api/auth**", "/api/login**", "**").permitAll()
.anyRequest().permitAll()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.headers().frameOptions().disable(); // otherwise H2 console is not available
// There are many ways to ways of placing our Filter in a position in the chain
// You can troubleshoot any error enabling debug(see below), it will print the chain of Filters
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
// ..........
}
Clear and refresh jQuery Chosen dropdown list
$("#idofBtn").click(function(){
$('#idofdropdown').empty(); //remove all child nodes
var newOption = $('<option value="1">test</option>');
$('#idofdropdown').append(newOption);
$('#idofdropdown').trigger("chosen:updated");
});
Git merge two local branches
on branchB do $git checkout branchA
to switch to branch A
on branchA do $git merge branchB
That's all you need.
Cannot enqueue Handshake after invoking quit
You can use
debug: false,
Example:
//mysql connection
var dbcon1 = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "node5",
debug: false,
});
Iterating through a golang map
You can make it by one line:
mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
fmt.Println("k:", k, "v:", v)
}
Output is:
k: foo v: map[first:1]
k: boo v: map[second:2]
Making a <button> that's a link in HTML
IMPORTANT: <button>
should never be a descendent of <a>
.
Try <a href="http://stackoverflow.com"><button>Link Text</button></a>
in any html validator like https://validator.w3.org and you'll get an error. There's really no point in using a button if you're not using the button. Just style the <a>
with css to look like a button. If you're using a framework like Bootstrap, you could apply the button style(s) btn
, btn-primary
etc.
jsfiddle : button styled link
_x000D_
_x000D_
.btnStack {_x000D_
font-family: Oswald;_x000D_
background-color: orange;_x000D_
color: white;_x000D_
text-decoration: none;_x000D_
display: inline-block;_x000D_
padding: 6px 12px;_x000D_
margin-bottom: 0;_x000D_
font-size: 14px;_x000D_
font-weight: normal;_x000D_
line-height: 1.428571429;_x000D_
text-align: center;_x000D_
white-space: nowrap;_x000D_
vertical-align: middle;_x000D_
cursor: pointer;_x000D_
border: 1px solid transparent;_x000D_
border-radius: 4px;_x000D_
-webkit-user-select: none;_x000D_
-moz-user-select: none;_x000D_
-ms-user-select: none;_x000D_
-o-user-select: none;_x000D_
user-select: none;_x000D_
}_x000D_
_x000D_
a.btnStack:hover {_x000D_
background-color: #000;_x000D_
}
_x000D_
<link href='https://fonts.googleapis.com/css?family=Oswald:400' rel='stylesheet' type='text/css'>_x000D_
<a href="http://stackoverflow.com" class="btnStack">stackoverflow.com</a>
_x000D_
_x000D_
_x000D_
What does "commercial use" exactly mean?
"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.
Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).
Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.
You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:
- Use it internally as much as you want (see here)
- Run it on your internal servers for external users / clients / customers, or run it on your internal servers for paying clients if you're an ISP / hosting provider. (If Screwturn were licensed under the AGPL instead of the GPL, that might restrict this.)
- Distribute it to others, either free of charge or for a payment that covers the shipping, as long as you're willing to also distribute the source code
- Incorporate it into your product, as long as you're willing to also distribute the source code, and as long as either (a) it remains a separate program that you merely aggregate with your product or (b) you release the source code to your product under an open source license compatible with the GPL
In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.
All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.
How do I return to an older version of our code in Subversion?
This is what I did and worked for me.
I want to undo the changes in multiple commits that I did for certain times and want to go to the previous commit point.
- Go to Team -> Show History.
- Right-click on the or range of revisions you want to ignore.
- Select the "Revert changes" option.
This will run a reverse merge, undoing the changes in your working copy.
Just review the code and commit.
How do I style a <select> dropdown with only CSS?
<select>
tags can be styled through CSS just like any other HTML element on an HTML page rendered in a browser. Below is an (overly simple) example that will position a select element on the page and render the text of the options in blue.
Example HTML file (selectExample.html):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Select Styling</title>
<link href="selectExample.css" rel="stylesheet">
</head>
<body>
<select id="styledSelect" class="blueText">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
Example CSS file (selectExample.css):
/* All select elements on page */
select {
position: relative;
}
/* Style by class. Effects the text of the contained options. */
.blueText {
color: #0000FF;
}
/* Style by id. Effects position of the select drop down. */
#styledSelect {
left: 100px;
}
WCF Service Returning "Method Not Allowed"
Only methods with WebGet can be accessed from browser IE ; you can access other http verbs by just typing address
You can either try Restful service startup kit of codeples or use fiddler to test your other http verbs
How to place div side by side
<div class="container" style="width: 100%;">
<div class="sidebar" style="width: 200px; float: left;">
Sidebar
</div>
<div class="content" style="margin-left: 202px;">
content
</div>
</div>
This will be cross browser compatible. Without the margin-left you will run into issues with content running all the way to the left if you content is longer than your sidebar.
What's the difference between eval, exec, and compile?
exec
is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:
exec('print(5)') # prints 5.
# exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there
exec('print(5)\nprint(6)') # prints 5{newline}6.
exec('if True: print(6)') # prints 6.
exec('5') # does nothing and returns nothing.
eval
is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:
x = eval('5') # x <- 5
x = eval('%d + 6' % x) # x <- 11
x = eval('abs(%d)' % -100) # x <- 100
x = eval('x = 5') # INVALID; assignment is not an expression.
x = eval('if 1: x = 4') # INVALID; if is a statement, not an expression.
compile
is a lower level version of exec
and eval
. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:
compile(string, '', 'eval')
returns the code object that would have been executed had you done eval(string)
. Note that you cannot use statements in this mode; only a (single) expression is valid.
compile(string, '', 'exec')
returns the code object that would have been executed had you done exec(string)
. You can use any number of statements here.
compile(string, '', 'single')
is like the exec
mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')
Invalid argument supplied for foreach()
Personally I find this to be the most clean - not sure if it's the most efficient, mind!
if (is_array($values) || is_object($values))
{
foreach ($values as $value)
{
...
}
}
The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.
SQL Query NOT Between Two Dates
What you are currently doing is checking whether neither the start_date nor the end_date fall within the range of the dates given.
I guess what you are really looking for is a record which does not fit in the date range given. If so, use the query below.
SELECT *
FROM `test_table`
WHERE CAST('2009-12-15' AS DATE) > start_date AND CAST('2010-01-02' AS DATE) < end_date
Querying DynamoDB by date
Approach I followed to solve this problem is by created a Global Secondary Index as below. Not sure if this is the best approach but hopefully if it is useful to someone.
Hash Key | Range Key
------------------------------------
Date value of CreatedAt | CreatedAt
Limitation imposed on the HTTP API user to specify the number of days to retrieve data, defaulted to 24 hr.
This way, I can always specify the HashKey as Current date's day and RangeKey can use > and < operators while retrieving. This way the data is also spread across multiple shards.
Running a simple shell script as a cronjob
The easiest way would be to use a GUI:
For Gnome use gnome-schedule (universe)
sudo apt-get install gnome-schedule
For KDE use kde-config-cron
It should be pre installed on Kubuntu
But if you use a headless linux or don´t want GUI´s you may use:
crontab -e
If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:
* * * * * YOURCOMMAND
- - - - -
| | | | |
| | | | +----- Day in Week (0 to 7) (Sunday is 0 and 7)
| | | +------- Month (1 to 12)
| | +--------- Day in Month (1 to 31)
| +----------- Hour (0 to 23)
+------------- Minute (0 to 59)
There are some shorts, too (if you don´t want the *):
@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year
If you want to use the shorts as cron (because they don´t work or so):
@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *
PHP + MySQL transactions examples
The idea I generally use when working with transactions looks like this (semi-pseudo-code):
try {
// First of all, let's begin a transaction
$db->beginTransaction();
// A set of queries; if one fails, an exception should be thrown
$db->query('first query');
$db->query('second query');
$db->query('third query');
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$db->commit();
} catch (\Throwable $e) {
// An exception has been thrown
// We must rollback the transaction
$db->rollback();
throw $e; // but the error must be handled anyway
}
Note that, with this idea, if a query fails, an Exception must be thrown:
- PDO can do that, depending on how you configure it
- else, with some other API, you might have to test the result of the function used to execute a query, and throw an exception yourself.
Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.
For example, quite often you'll have a couple of queries before the transaction (before the begin
) and another couple of queries after the transaction (after either commit
or rollback
) and you'll want those queries executed no matter what happened (or not) in the transaction.
Bootstrap 4 File Input
Bootstrap 4.4:
Show a choose file
bar. After a file is chosen show the file name along with its extension
<div class="custom-file">
<input type="file" class="custom-file-input" id="idEditUploadVideo"
onchange="$('#idFileName').html(this.files[0].name)">
<label class="custom-file-label" id="idFileName" for="idEditUploadVideo">Choose file</label>
</div>
Check table exist or not before create it in Oracle
-- checks for table in specfic schema:
declare n number(10);
begin
Select count(*) into n from SYS.All_All_Tables where owner = 'MYSCHEMA' and TABLE_NAME = 'EMPLOYEE';
if (n = 0) then
execute immediate
'create table MYSCHEMA.EMPLOYEE ( ID NUMBER(3), NAME VARCHAR2(30) NOT NULL)';
end if;
end;
How to construct a REST API that takes an array of id's for the resources
I find another way of doing the same thing by using @PathParam
. Here is the code sample.
@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
How to call a method after a delay in Android
everybody seems to forget to clean the Handler before posting a new runnable or message on it. Otherway they could potentially accumulate and cause bad behaviour.
handler.removeMessages(int what);
// Remove any pending posts of messages with code 'what' that are in the message queue.
handler.removeCallbacks(Runnable r)
// Remove any pending posts of Runnable r that are in the message queue.
string decode utf-8
A string needs no encoding. It is simply a sequence of Unicode characters.
You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.
Encoding of a String is carried out by:
String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into
You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).
Decoding:
String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded
If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"
How to Insert Double or Single Quotes
Easier steps:
- Highlight the cells you want to add the quotes.
- Go to Format–>Cells–>Custom
- Copy/Paste the following into the Type field: \"@\" or \'@\'
- Done!
Add an incremental number in a field in INSERT INTO SELECT query in SQL Server
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
Transparent color of Bootstrap-3 Navbar
The class is .navbar-default. You need to create a class on your custom css .navbar-default.And follow the css code. Also if you don’t want box-shadow on your menu, you can put on the same class.
.navbar-default {
background-color:transparent !important;
border-color:transparent;
background-image:none;
box-shadow:none;
}
To change font navbar color, the class is to change – .navbar-default .navbar-nav>li>a see the code bellow:
.navbar-default .navbar-nav>li>a {
font-size:20px;
color:#fff;
}
ref : http://twitterbootstrap.org/bootstrap-navbar-background-color-transparent/
Move an item inside a list?
If you don't know the position of the item, you may need to find the index first:
old_index = list1.index(item)
then move it:
list1.insert(new_index, list1.pop(old_index))
or IMHO a cleaner way:
try:
list1.remove(item)
list1.insert(new_index, item)
except ValueError:
pass
How to set DataGrid's row Background, based on a property value using data bindings
The same can be done without DataTrigger
too:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" >
<Setter.Value>
<Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
<Binding.ConverterParameter>
<x:Array Type="SolidColorBrush">
<SolidColorBrush Color="{StaticResource RedColor}"/>
<SolidColorBrush Color="{StaticResource TransparentColor}"/>
</x:Array>
</Binding.ConverterParameter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
Where BooleanToBrushConverter
is the following class:
public class BooleanToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Brushes.Transparent;
Brush[] brushes = parameter as Brush[];
if (brushes == null)
return Brushes.Transparent;
bool isTrue;
bool.TryParse(value.ToString(), out isTrue);
if (isTrue)
{
var brush = (SolidColorBrush)brushes[0];
return brush ?? Brushes.Transparent;
}
else
{
var brush = (SolidColorBrush)brushes[1];
return brush ?? Brushes.Transparent;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Jquery ajax call click event submit button
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
How can I make my own event in C#?
to do it we have to know the three components
- the place responsible for
firing the Event
- the place responsible for
responding to the Event
the Event itself
a. Event
b .EventArgs
c. EventArgs enumeration
now lets create Event that fired when a function is called
but I my order of solving this problem like this: I'm using the class before I create it
the place responsible for responding to the Event
NetLog.OnMessageFired += delegate(object o, MessageEventArgs args)
{
// when the Event Happened I want to Update the UI
// this is WPF Window (WPF Project)
this.Dispatcher.Invoke(() =>
{
LabelFileName.Content = args.ItemUri;
LabelOperation.Content = args.Operation;
LabelStatus.Content = args.Status;
});
};
NetLog is a static class I will Explain it later
the next step is
the place responsible for firing the Event
//this is the sender object, MessageEventArgs Is a class I want to create it and Operation and Status are Event enums
NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
downloadFile = service.DownloadFile(item.Uri);
NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
the third step
- the Event itself
I warped The Event within a class called NetLog
public sealed class NetLog
{
public delegate void MessageEventHandler(object sender, MessageEventArgs args);
public static event MessageEventHandler OnMessageFired;
public static void FireMessage(Object obj,MessageEventArgs eventArgs)
{
if (OnMessageFired != null)
{
OnMessageFired(obj, eventArgs);
}
}
}
public class MessageEventArgs : EventArgs
{
public string ItemUri { get; private set; }
public Operation Operation { get; private set; }
public Status Status { get; private set; }
public MessageEventArgs(string itemUri, Operation operation, Status status)
{
ItemUri = itemUri;
Operation = operation;
Status = status;
}
}
public enum Operation
{
Upload,Download
}
public enum Status
{
Started,Finished
}
this class now contain the Event
, EventArgs
and EventArgs Enums
and the function
responsible for firing the event
sorry for this long answer
Installing Python packages from local file system folder to virtualenv with pip
I've been trying to achieve something really simple and failed miserably, probably I'm stupid.
Anyway, if you have a script/Dockerfile
which download a python package zip file (e.g. from GitHub) and you then want to install it you can use the file:///
prefix to install it as shown in the following example:
$ wget https://example.com/mypackage.zip
$ echo "${MYPACKAGE_MD5} mypackage.zip" | md5sum --check -
$ pip install file:///.mypackage.zip
NOTE: I know you could install the package straight away using pip install https://example.com/mypackage.zip
but in my case I wanted to verify the checksum (never paranoid enough) and I failed miserably when trying to use the various options that pip provides/the #md5
fragment.
It's been surprisingly frustrating to do something so simple directly with pip
. I just wanted to pass a checksum and have pip
verify that the zip was matching before installing it.
I was probably doing something very stupid but in the end I gave up and opted for this. I hope it helps others trying to do something similar.
Read input numbers separated by spaces
You'll want to:
- Read in an entire line from the console
- Tokenize the line, splitting along spaces.
- Place those split pieces into an array or list
- Step through that array/list, performing your prime/perfect/etc tests.
What has your class covered along these lines so far?
C++ convert string to hexadecimal and vice versa
This will convert "Hello World" to "48656c6c6f20576f726c64" and will store this hex value in str1 and also will convert "48656c6c6f20576f726c64" to "Hello World".
#include <iostream>
#include<sstream>
using namespace std;
int hexCharToInt(char);
string hexToString(string);
int main()
{
std::string str;
std::stringstream str1;
str="Hello World";
for(int i=0;i<str.length();i++){
str1 << std::hex << (int)str.at(i);
}
std::cout << str1.str() <<"\n";
string test = "48656c6c6f20576f726c64";
std::cout << hexToString(test) <<"\n";
return 0;
}
string hexToString(string str){
std::stringstream HexString;
for(int i=0;i<str.length();i++){
char a = str.at(i++);
char b = str.at(i);
int x = hexCharToInt(a);
int y = hexCharToInt(b);
HexString << (char)((16*x)+y);
}
return HexString.str();
}
int hexCharToInt(char a){
if(a>='0' && a<='9')
return(a-48);
else if(a>='A' && a<='Z')
return(a-55);
else
return(a-87);
}
When should you NOT use a Rules Engine?
That's certainly a good start. The other thing with rules engines is that some things are well-understood, deterministic, and straight-forward. Payroll withholding is (or use to be) like that. You could express it as rules that would be resolved by a rules engine, but you could express the same rules as a fairly simple table of values.
So, workflow engines are good when you're expressing a longer-term process that will have persistent data. Rules engines can do a similar thing, but you have to do a lot of added complexity.
Rules engines are good when you have complicated knowledge bases and need search. Rules engines can resolve complicated issues, and can be adapted quickly to changing situations, but impose a lot of complexity on the base implementation.
Many decision algorithms are simple enough to express as a simple table-driven program without the complexity implied by a real rules engine.
Docker-Compose can't connect to Docker Daemon
Is there slight possibility you deleted default machine?
But, first check if all files are there (OSX, similar on other systems)
brew install docker docker-compose docker-machine xhyve docker-machine-driver-xhyve
brew link docker docker-compose docker-machine xhyve docker-machine-driver-xhyve
sudo chown root:wheel /usr/local/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
sudo chmod u+s /usr/local/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
Also, install Docker App, as it much easier to maintain containers:
brew cask reinstall docker
ans start Docker app from finder (wait until service is fully started)
Then, check instalation with:
docker-machine ls
if no machines are present in list, create one and start it:
docker-machine create default
docker-machine start default
After this, build, compose and all other commands should work properly.
Visual Studio SignTool.exe Not Found
If you do not care about sign your program when you publish, just right click your project then choose Properties --> Signing --> un-check Sign the ClickOnce manifest . I had the same issue when building my program on another machine which did not have ClickOne.
Submit Button Image
You have to remove the borders and add a background image on the input.
.imgClass {
background-image: url(path to image) no-repeat;
width: 186px;
height: 53px;
border: none;
}
It should be good now, normally.
Changing selection in a select with the Chosen plugin
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
How do I monitor all incoming http requests?
Microsoft Message Analyzer is the successor of the Microsoft Network Monitor 3.4
If your http incoming traffic is going to your web server at 58000 port, start the Analyzer in Administrator mode and click new session:
use filter: tcp.Port = 58000 and HTTP
trace scenario: "Local Network Interfaces (Win 8 and earlier)" or "Local Network Interfaces (Win 8.1 and later)" depends on your OS
Parsing Level: Full
Unsupported operand type(s) for +: 'int' and 'str'
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
return in for loop or outside loop
There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).
This will not mess up garbage collection in any way!!
The better way to do it is to set a boolean value, if you want to listen to him.
boolean flag = false;
for(int i=0; i<array.length; ++i){
if(array[i] == valueToFind) {
flag = true;
break;
}
}
return flag;
css ellipsis on second line
What a shame that you can't get it to work over two lines! Would be awesome if the element was display block and had a height set to 2em or something, and when the text overflowed it would show an ellipsis!
For a single liner you can use:
.show-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
For multiple lines maybe you could use a Polyfill such as jQuery autoellipsis which is on github http://pvdspek.github.com/jquery.autoellipsis/
Return empty cell from formula in Excel
This is how I did it for the dataset I was using. It seems convoluted and stupid, but it was the only alternative to learning how to use the VB solution mentioned above.
- I did a "copy" of all the data, and pasted the data as "values".
- Then I highlighted the pasted data and did a "replace" (Ctrl-H) the empty cells with some letter, I chose
q
since it wasn't anywhere on my data sheet.
- Finally, I did another "replace", and replaced
q
with nothing.
This three step process turned all of the "empty" cells into "blank" cells". I tried merging steps 2 & 3 by simply replacing the blank cell with a blank cell, but that didn't work--I had to replace the blank cell with some kind of actual text, then replace that text with a blank cell.
How to use 'cp' command to exclude a specific directory?
This is a modification of Linus Kleen's answer. His answer didn't work for me because there would be a . added in front of the file path which cp doesn't like (the path would look like source/.destination/file).
This command worked for me:
find . -type f -not -path '*/exlude-path/*' -exec cp --parents '{}' '/destination/' \;
the --parents command preserves the directory structure.
Using grep to search for hex strings in a file
We tried several things before arriving at an acceptable solution:
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
Then found we could get usable results with
xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd
Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
--------------------^^
So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).
The final result seems to be
xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex
0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03 .$.q............
--------------------------------------------^^
Which variable size to use (db, dw, dd) with x86 assembly?
The full list is:
DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)
See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html
They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):
db 0x55 ; just the byte 0x55
db 0x55,0x56,0x57 ; three bytes in succession
db 'a',0x55 ; character constants are OK
db 'hello',13,10,'$' ; so are string constants
dw 0x1234 ; 0x34 0x12
dw 'A' ; 0x41 0x00 (it's just a number)
dw 'AB' ; 0x41 0x42 (character constant)
dw 'ABC' ; 0x41 0x42 0x43 0x00 (string)
dd 0x12345678 ; 0x78 0x56 0x34 0x12
dq 0x1122334455667788 ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
ddq 0x112233445566778899aabbccddeeff00
; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
do 0x112233445566778899aabbccddeeff00 ; same as previous
dd 1.234567e20 ; floating-point constant
dq 1.234567e20 ; double-precision float
dt 1.234567e20 ; extended-precision float
DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.
display Java.util.Date in a specific format
java.time
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM
to obtain 2011?5?31?
. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat
. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date
nor a modern LocalDate
can have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Creating a timer in python
I'd use a timedelta
object.
from datetime import datetime, timedelta
...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
if next_time <= datetime.now():
minutes += 1
next_time += period
Finding non-numeric rows in dataframe in pandas?
Sorry about the confusion, this should be the correct approach. Do you want only to capture 'bad'
only, not things like 'good'
; Or just any non-numerical values?
In[15]:
np.where(np.any(np.isnan(df.convert_objects(convert_numeric=True)), axis=1))
Out[15]:
(array([3]),)
Swift alert view with OK and Cancel: which button tapped?
You may want to consider using SCLAlertView, alternative for UIAlertView or UIAlertController.
UIAlertController only works on iOS 8.x or above, SCLAlertView is a good option to support older version.
github to see the details
example:
let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")
How to check if a string starts with a specified string?
There is also the strncmp()
function and strncasecmp()
function which is perfect for this situation:
if (strncmp($string_n, "http", 4) === 0)
In general:
if (strncmp($string_n, $prefix, strlen($prefix)) === 0)
The advantage over the substr()
approach is that strncmp()
just does what needs to be done, without creating a temporary string.
Angular 5 Scroll to top on every Route click
Here is a solution that only scrolls to top of Component if first time visiting for EACH component (in case you need to do something different per component):
In each Component:
export class MyComponent implements OnInit {
firstLoad: boolean = true;
...
ngOnInit() {
if(this.firstLoad) {
window.scroll(0,0);
this.firstLoad = false;
}
...
}
Android selector & text color
Have you tried setOnFocusChangeListener
? Within the handler, you could change the text appearance.
For instance:
TextView text = (TextView)findViewById(R.id.text);
text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
((TextView)v).setXXXX();
} else {
((TextView)v).setXXXX();
}
}
});
You can then apply whatever changes you want when it's focused or not. You can also use the ViewTreeObserver to listen for Global focus changes.
For instance:
View all = findViewById(R.id.id_of_top_level_view_on_layout);
ViewTreeObserver vto = all.getViewTreeObserver();
vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
public void onGlobalFocusChanged(
View oldFocus, View newFocus) {
// xxxx
}
});
I hope this helps or gives you ideas.
How to free memory in Java?
*"I personally rely on nulling variables as a placeholder for future proper deletion. For example, I take the time to nullify all elements of an array before actually deleting (making null) the array itself."
This is unnecessary. The way the Java GC works is it finds objects that have no reference to them, so if I have an Object x with a reference (=variable) a that points to it, the GC won't delete it, because there is a reference to that object:
a -> x
If you null a than this happens:
a -> null
x
So now x doesn't have a reference pointing to it and will be deleted. The same thing happens when you set a to reference to a different object than x.
So if you have an array arr that references to objects x, y and z and a variable a that references to the array it looks like that:
a -> arr -> x
-> y
-> z
If you null a than this happens:
a -> null
arr -> x
-> y
-> z
So the GC finds arr as having no reference set to it and deletes it, which gives you this structure:
a -> null
x
y
z
Now the GC finds x, y and z and deletes them aswell. Nulling each reference in the array won't make anything better, it will just use up CPU time and space in the code (that said, it won't hurt further than that. The GC will still be able to perform the way it should).
PHP: Return all dates between two dates in an array
Simple but like a charm:
$period = new DatePeriod(new DateTime('2015-01-01'), new DateInterval('P1D'), new DateTime('2015-01-15 +1 day'));
foreach ($period as $date) {
$dates[] = $date->format("Y-m-d");
}
//ONLY SHOWING
echo '<pre>';
var_dump($dates);
echo '</pre>';
exit();
Check whether variable is number or string in JavaScript
Simple and thorough:
function isNumber(x) {
return parseFloat(x) == x
};
Test cases:
console.log('***TRUE CASES***');
console.log(isNumber(0));
console.log(isNumber(-1));
console.log(isNumber(-500));
console.log(isNumber(15000));
console.log(isNumber(0.35));
console.log(isNumber(-10.35));
console.log(isNumber(2.534e25));
console.log(isNumber('2.534e25'));
console.log(isNumber('52334'));
console.log(isNumber('-234'));
console.log(isNumber(Infinity));
console.log(isNumber(-Infinity));
console.log(isNumber('Infinity'));
console.log(isNumber('-Infinity'));
console.log('***FALSE CASES***');
console.log(isNumber(NaN));
console.log(isNumber({}));
console.log(isNumber([]));
console.log(isNumber(''));
console.log(isNumber('one'));
console.log(isNumber(true));
console.log(isNumber(false));
console.log(isNumber());
console.log(isNumber(undefined));
console.log(isNumber(null));
console.log(isNumber('-234aa'));
JSON and XML comparison
The important thing about JSON is to keep data transfer encrypted for security reasons. No doubt that JSON is much much faster then XML. I have seen XML take 100ms where as JSON only took 60ms. JSON data is easy to manipulate.
Global variables in AngularJS
If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:
var myApp = angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x');
Then use it in a controller like this:
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
}]);
The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax.
The other option is to use $rootScope
, but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. It's advised to be used sparingly.
Since all scopes inherit from $rootScope
, if you have a variable $rootScope.data
and someone forgets that data
is already defined and creates $scope.data
in a local scope you will run into problems.
If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference":
myApp.value('clientId', { value: 'a12345654321x' });
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
this.change = function(value) {
clientId.value = 'something else';
}
}];
JSFiddle example
How to cast Object to boolean?
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
Update records in table from CTE
Updates you make to the CTE will be cascaded to the source table.
I have had to guess at your schema slightly, but something like this should work.
;WITH T AS
( SELECT InvoiceNumber,
DocTotal,
SUM(Sale + VAT) OVER(PARTITION BY InvoiceNumber) AS NewDocTotal
FROM PEDI_InvoiceDetail
)
UPDATE T
SET DocTotal = NewDocTotal
Select all occurrences of selected word in VSCode
In my MacOS case for some reason Cmd+Shift+L is not working while pressing the short cut on the keyboard (although it work just fine while clicking on this option in menu: Selection -> Select All Occurences). So for me pressing Cmd+FN+F2 did the trick (FN is for enabling "F2" obviously).
Btw, if you forget this shortcut just do right-click on the selection and see "Change All Occurrences" option
python location on mac osx
Run this in your interactive terminal
import os
os.path
It will give you the folder where python is installed
What do hjust and vjust do when making a plot using ggplot?
Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.
However, it is not quite that simple. hjust
and vjust
as described there are how it works in geom_text
and theme_text
(sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust
of 0.5 and a vjust
of 0.5 center the box on the reference point. Reducing hjust
moves the box right by an amount of the box width times 0.5-hjust
. Thus when hjust=0
, the left edge of the box is at the reference point. Increasing hjust
moves the box left by an amount of the box width times hjust-0.5
. When hjust=1
, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2
, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5
box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].
But, sometimes this doesn't work. For example
DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))
The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider
p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))
The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.
Convert MySQL to SQlite
There are different ways to do this. I also had this problem and I searched a lot and then I got a simple way to convert MySQL to SQLite.
Follow these steps:
First You Need to Install SQLite DB Browser (very small and fast to view Tables and Data)
Open your MySQL File in Notepad or it would be great if you open in Notepad++
Remove First extra Lines Contains Information or Queries and Save it.
Open SQLite DB Browser, Create Database, then Tables, and Same Types as it is in MySQL Database.
In Menu Bar of SQLite DB Browser Select File-> then Import data MySQL File which you saved.
It will easily Convert into SQLite After Warning Dialog.
If error then remove more extra lines if your MySQL file have.
You can also Install MySQL to SQLite Converter Software on trial Basis, but the information I am giving for conversion is life time.
Setting up and using Meld as your git difftool and mergetool
While the other answer is correct, here's the fastest way to just go ahead and configure Meld as your visual diff tool. Just copy/paste this:
git config --global diff.tool meld
git config --global difftool.prompt false
Now run git difftool
in a directory and Meld will be launched for each different file.
Side note: Meld is surprisingly slow at comparing CSV files, and no Linux diff tool I've found is faster than this Windows tool called Compare It! (last updated in 2010).
Check if string is in a pandas dataframe
If there is any chance that you will need to search for empty strings,
a['Names'].str.contains('')
will NOT work, as it will always return True.
Instead, use
if '' in a["Names"].values
to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.
Why do we assign a parent reference to the child object in Java?
This situation happens when you have several implementations.
Let me explain.
Supppose you have several sorting algorithm and you want to choose at runtime the one to implement, or you want to give to someone else the capability to add his implementation.
To solve this problem you usually create an abstract class (Parent) and have different implementation (Child).
If you write:
Child c = new Child();
you bind your implementation to Child class and you can't change it anymore. Otherwise if you use:
Parent p = new Child();
as long as Child extends Parent you can change it in the future without modifying the code.
The same thing can be done using interfaces: Parent isn't anymore a class but a java Interface.
In general you can use this approch in DAO pattern where you want to have several DB dependent implementations.
You can give a look at FactoryPatter or AbstractFactory Pattern.
Hope this can help you.
Android - Start service on boot
Well here is a complete example of an AutoStart Application
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".hello"></activity>
<service android:enabled="true" android:name=".service" />
</application>
</manifest>
autostart.java
public class autostart extends BroadcastReceiver
{
public void onReceive(Context context, Intent arg1)
{
Intent intent = new Intent(context,service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
service.java
public class service extends Service
{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),hello.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
hello.java - This will pop-up everytime you start the device after executing the Applicaton once.
public class hello extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
}
}
'git status' shows changed files, but 'git diff' doesn't
There are a few reasons why git status
might show a difference but git diff
might not.
The mode (permission bits) of the file changed-- for example, from 777 to 700.
The line feed style changed from CRLF (DOS) to LF (UNIX)
The easiest way to find out what happened is to run git format-patch HEAD^
and see what the generated patch says.
How do I connect to a specific Wi-Fi network in Android programmatically?
You need to create WifiConfiguration
instance like this:
String networkSSID = "test";
String networkPass = "pass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes
Then, for WEP network you need to do this:
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
For WPA network you need to add passphrase like this:
conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
And finally, you might need to enable it, so Android connects to it:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.
jQuery click anywhere in the page except on 1 div
See the documentation for jQuery Event Target. Using the target property of the event object, you can detect where the click originated within the #menu_content
element and, if so, terminate the click handler early. You will have to use .closest()
to handle cases where the click originated in a descendant of #menu_content
.
$(document).click(function(e){
// Check if click was triggered on or within #menu_content
if( $(e.target).closest("#menu_content").length > 0 ) {
return false;
}
// Otherwise
// trigger your click function
});
Convert Mercurial project to Git
Some notes of my experience converting Mercurial to Git.
1. hg-fast-export
Using hg-fast-export failed and I needed --force as noted above. Next I got this error:
error: cannot lock ref 'refs/heads/stable': 'refs/heads/stable/sub-branch-name' exists; cannot create 'refs/heads/stable'
Upon completion of the hg-fast-export I ended up with an amputated repo. I think that this repo had a good few orphaned branches and that hg-fast-export needs a somewhat idealised repo. This all seemed a bit rough around the edges, so I moved on to Kiln Harmony (http://blog.fogcreek.com/announcing-kiln-harmony-the-future-of-dvcs/)
2. Kiln
Kiln Harmony does not appear to exist on a free tier account as suggested above. I could choose between Git-only and Mercurial-only repos and there is no option to switch. I raised a support ticket and will share the result if they reply.
3. hg-git
The Hg-Git mercurial plugin (http://hg-git.github.io/) did work for me. FYI on Mac OSX I installed hg-git via macports as follows:
- sudo port install python27
- sudo port select --set python python27
- sudo port install py27-hggit
- vi ~/.hgrc
.hgrc needs these lines:
[ui]
username = Name Surname <[email protected]>
[extensions]
hgext.bookmarks =
hggit =
I then had success with:
hg push git+ssh://[email protected]:myaccount/myrepo.git
4. Caveat: Know your repo
All the above are blunt instruments and I only pushed ahead because it took enough time to get the team to use git properly.
Upon first pushing the project per (3) I ended up with all new changes missing. This is because this line of code must be viewed as a guide only:
$ hg bookmark -r default master # make a bookmark of master for default, so a ref gets created
The theory is that the default branch can be deemed to be master when pushing to git, and in my case I inherited a repo where they used 'stable' as the equivalent of master. Moreover, I also discovered that the tip of the repo was a hotfix not yet merged with the 'stable' branch.
Without properly understanding both Mercurial and the repo to be converted, you are probably better off not doing the conversion.
I did the following in order to get the repo ready for a second conversion attempt:
hg update -C stable
hg merge stable/hotfix-feature
hg ci -m "Merge with stable branch"
hg push git+ssh://[email protected]:myaccount/myrepo.git
After this I had a verifiably equivalent project in git, however all the orphaned branches I mentioned earlier are gone. I don't think that is too serious, but I may well live to regret this as an oversight. Therefore my final thought is to keep the original anyway.
Edit: If you just want the latest commit in git, this is simpler than the above merge:
hg book -r tip master
hg push git+ssh://[email protected]:myaccount/myrepo.git
sed whole word search and replace
\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):
$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment
How to extract IP Address in Spring MVC Controller get call?
Put this method in your BaseController:
@SuppressWarnings("ConstantConditions")
protected String fetchClientIpAddr() {
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
String ip = Optional.ofNullable(request.getHeader("X-FORWARDED-FOR")).orElse(request.getRemoteAddr());
if (ip.equals("0:0:0:0:0:0:0:1")) ip = "127.0.0.1";
Assert.isTrue(ip.chars().filter($ -> $ == '.').count() == 3, "Illegal IP: " + ip);
return ip;
}
Shorter syntax for casting from a List<X> to a List<Y>?
This is not quite the answer to this question, but it may be useful for some: as @SWeko said, thanks to covariance and contravariance, List<X>
can not be cast in List<Y>
, but List<X>
can be cast into IEnumerable<Y>
, and even with implicit cast.
Example:
List<Y> ListOfY = new List<Y>();
List<X> ListOfX = (List<X>)ListOfY; // Compile error
but
List<Y> ListOfY = new List<Y>();
IEnumerable<X> EnumerableOfX = ListOfY; // No issue
The big advantage is that it does not create a new list in memory.
C# Version Of SQL LIKE
public static class StringsEx
{
public static IEnumerable<String> Like(this IEnumerable<String> input, String pattern)
{
var dt = new DataTable();
dt.Columns.Add("Search");
foreach (String str in input)
{
dt.Rows.Add(str);
}
dt.DefaultView.RowFilter = String.Format("Search LIKE '{0}'", pattern);
return dt.DefaultView.ToTable()
.AsEnumerable()
.Select(r => r.Field<String>("Search"));
}
}
The only disadvantage is following: "Wildcard characters are not allowed in the middle of a string. For example, 'te*xt' is not allowed."©
How do you get assembler output from C/C++ source in gcc?
As mentioned before, look at the -S flag.
It's also worth looking at the '-fdump-tree' family of flags, in particular '-fdump-tree-all', which lets you see some of gcc's intermediate forms. These can often be more readable than assembler (at least to me), and let you see how optimisation passes perform.
how to drop database in sqlite?
If you want to delete database programatically you can use deleteDatabase
from Context
class:
deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.
How do you clear your Visual Studio cache on Windows Vista?
The accepted answer gave two locations:
here
C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache
and possibly here
C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache
Did you try those?
Edited to add
On my Windows Vista machine, it's located in
%Temp%\VWDWebCache
and in
%LocalAppData%\Microsoft\WebsiteCache
From your additional information (regarding team edition) this comes from Clear Client TFS Cache:
Clear Client TFS Cache
Visual Studio and Team Explorer
provide a caching mechanism which can
get out of sync. If I have multiple
instances of a single TFS which can be
connected to from a single Visual
Studio client, that client can become
confused.
To solve it..
For Windows Vista delete contents of this folder
%LocalAppData%\Microsoft\Team Foundation\1.0\Cache
Determine a string's encoding in C#
Another option, very late in coming, sorry:
http://www.architectshack.com/TextFileEncodingDetector.ashx
This small C#-only class uses BOMS if present, tries to auto-detect possible unicode encodings otherwise, and falls back if none of the Unicode encodings is possible or likely.
It sounds like UTF8Checker referenced above does something similar, but I think this is slightly broader in scope - instead of just UTF8, it also checks for other possible Unicode encodings (UTF-16 LE or BE) that might be missing a BOM.
Hope this helps someone!
BehaviorSubject vs Observable?
BehaviorSubject
The BehaviorSubject builds on top of the same functionality as our ReplaySubject, subject like, hot, and replays previous value.
The BehaviorSubject adds one more piece of functionality in that you can give the BehaviorSubject an initial value. Let’s go ahead and take a look at that code
import { ReplaySubject } from 'rxjs';
const behaviorSubject = new BehaviorSubject(
'hello initial value from BehaviorSubject'
);
behaviorSubject.subscribe(v => console.log(v));
behaviorSubject.next('hello again from BehaviorSubject');
Observables
To get started we are going to look at the minimal API to create a regular Observable. There are a couple of ways to create an Observable. The way we will create our Observable is by instantiating the class. Other operators can simplify this, but we will want to compare the instantiation step to our different Observable types
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => observer.next('hello from Observable!'), 1000);
});
observable.subscribe(v => console.log(v));
Trying to start a service on boot on Android
After trying all of mentioned answers and tricks, I finally find why the code is not work in my phone. Some Android phones like "Huawei Honor 3C Android 4.2.2" have a Statup Manager menu in their settings and your app must be checked in the list.
:)
Maven parent pom vs modules pom
An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.
If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.
A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.
The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.
Apache CXF is an example the pattern in #2.
change pgsql port
There should be a line in your postgresql.conf
file that says:
port = 1486
Change that.
The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/
On Windows it is C:\Program Files\PostgreSQL\9.3\data
Don't forget to sudo service postgresql restart
for changes to take effect.
R Plotting confidence bands with ggplot
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM
Yes. You just have to use the RAISE_APPLICATION_ERROR
function. If you also want to name your exception, you'll need to use the EXCEPTION_INIT
pragma in order to associate the error number to the named exception. Something like
SQL> ed
Wrote file afiedt.buf
1 declare
2 ex_custom EXCEPTION;
3 PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
4 begin
5 raise_application_error( -20001, 'This is a custom error' );
6 exception
7 when ex_custom
8 then
9 dbms_output.put_line( sqlerrm );
10* end;
SQL> /
ORA-20001: This is a custom error
PL/SQL procedure successfully completed.
Interface/enum listing standard mime-type constants
If you're on android you have multiple choices, where only the first is a kind of "enum":
HTTP
(which has been deprecated in API 22), for example
HTTP.PLAIN_TEXT_TYPE
or
MimeTypeMap
, for example
final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
See also FileProvider.getType()
.
URLConnection
that provides the following methods:
For example
@Override
public String getType(Uri uri) {
return URLConnection.getFileNameMap().getContentTypeFor(
uri.getLastPathSegment());
}
How do I auto-resize an image to fit a 'div' container?
The code below is adapted from previous answers and is tested by me using an image called storm.jpg
.
This is the complete HTML code for a simple page that displays the image. This works perfect and was tested by me with www.resizemybrowser.com. Put the CSS code at the top of your HTML code, underneath your head section. Put the picture code wherever you want the picture.
<html>
<head>
<style type="text/css">
#myDiv
{
height: auto;
width: auto;
}
#myDiv img
{
max-width: 100%;
max-height: 100%;
margin: auto;
display: block;
}
</style>
</head>
<body>
<div id="myDiv">
<img src="images/storm.jpg">
</div>
</body>
</html>
How do I make a matrix from a list of vectors in R?
One option is to use do.call()
:
> do.call(rbind, a)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
Inserting HTML elements with JavaScript
If you want to insert HTML code inside existing page's tag use Jnerator. This tool was created specially for this goal.
Instead of writing next code
var htmlCode = '<ul class=\'menu-countries\'><li
class=\'item\'><img src=\'au.png\'></img><span>Australia </span></li><li
class=\'item\'><img src=\'br.png\'> </img><span>Brazil</span></li><li
class=\'item\'> <img src=\'ca.png\'></img><span>Canada</span></li></ul>';
var element = document.getElementById('myTag');
element.innerHTML = htmlCode;
You can write more understandable structure
var jtag = $j.ul({
class: 'menu-countries',
child: [
$j.li({ class: 'item', child: [
$j.img({ src: 'au.png' }),
$j.span({ child: 'Australia' })
]}),
$j.li({ class: 'item', child: [
$j.img({ src: 'br.png' }),
$j.span({ child: 'Brazil' })
]}),
$j.li({ class: 'item', child: [
$j.img({ src: 'ca.png' }),
$j.span({ child: 'Canada' })
]})
]
});
var htmlCode = jtag.html();
var element = document.getElementById('myTag');
element.innerHTML = htmlCode;
Update MongoDB field using value of another field
Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:
db.person.find().forEach(
function (elem) {
db.person.update(
{
_id: elem._id
},
{
$set: {
name: elem.firstname + ' ' + elem.lastname
}
}
);
}
);
Raw_Input() Is Not Defined
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
Fatal error: Cannot use object of type stdClass as array in
Controller (Example: User.php)
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Users extends CI_controller
{
// Table
protected $table = 'users';
function index()
{
$data['users'] = $this->model->ra_object($this->table);
$this->load->view('users_list', $data);
}
}
View (Example: users_list.php)
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user) : ?>
<tr>
<td><?php echo $user->name; ?></td>
<td><?php echo $user->surname; ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- // User table -->
Handling Enter Key in Vue.js
You forget a '}' before the last line (to close the "methods {...").
This code works :
_x000D_
_x000D_
Vue.config.keyCodes.atsign = 50;_x000D_
_x000D_
new Vue({_x000D_
el: '#myApp',_x000D_
data: {_x000D_
emailAddress: '',_x000D_
log: ''_x000D_
},_x000D_
methods: {_x000D_
_x000D_
onEnterClick: function() {_x000D_
alert('Enter was pressed');_x000D_
},_x000D_
_x000D_
onAtSignClick: function() {_x000D_
alert('@ was pressed');_x000D_
},_x000D_
_x000D_
postEmailAddress: function() {_x000D_
this.log += '\n\nPosting';_x000D_
}_x000D_
}_x000D_
})
_x000D_
html, body, #editor {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://vuejs.org/js/vue.min.js"></script>_x000D_
_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
_x000D_
<input type="text" v-model="emailAddress" v-on:keyup.enter="onEnterClick" v-on:keyup.atsign="onAtSignClick" />_x000D_
_x000D_
<button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
<br /><br />_x000D_
_x000D_
<textarea v-model="log" rows="4"></textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to fix 'sudo: no tty present and no askpass program specified' error?
Other options, not based on NOPASSWD:
- Start Netbeans with root privilege ((sudo netbeans) or similar) which will presumably fork the build process with root and thus sudo will automatically succeed.
- Make the operations you need to do suexec -- make them owned by root, and set mode to 4755. (This will of course let any user on the machine run them.) That way, they don't need sudo at all.
- Creating virtual hard disk files with bootsectors shouldn't need sudo at all. Files are just files, and bootsectors are just data. Even the virtual machine shouldn't necessarily need root, unless you do advanced device forwarding.
VBA Go to last empty row
try this:
Sub test()
With Application.WorksheetFunction
Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With
End Sub
Hope this works for you.
How do I dynamically set HTML5 data- attributes using react?
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.
2 options
Don't use camel case
<Option data-img-src='value' ... />
And then in the component, because of the dashes, you need to refer to the prop in quotes.
// @flow
class Option extends React.Component {
props: {
'data-img-src': string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props['data-img-src']} >...</option>
)
}
}
Or use camel case
<Option dataImgSrc='value' ... />
And then in the component, you need to convert.
// @flow
class Option extends React.Component {
props: {
dataImgSrc: string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props.dataImgSrc} >...</option>
)
}
}
Mainly just realize data-
attributes and aria-
attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.
How do I restart a program based on user input?
This line will unconditionally restart the running program from scratch:
os.execl(sys.executable, sys.executable, *sys.argv)
One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.
This can be useful if, for example, you are modifying its code in another window.
TypeError: ufunc 'add' did not contain a loop with signature matching types
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
How to add a set path only for that batch file executing?
That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:
setx ENV_VAR_NAME "DESIRED_PATH" /m
This will change it permanently and yes you can overwrite it by another batch script.
HTTP Error 500.19 and error code : 0x80070021
I solved this by doing the following:
WebServer(ISS)->WebServer->Application Development
add .NET Extensibility 3.5
add .NET Extensibility 4.5
add ASP.NET 4.5
add ISAPI Extensions
add ISAPI Filters
Programmatically center TextView text
TextView text = new TextView(this);
text.setGravity(Gravity.CENTER);
and
text.setGravity(Gravity.TOP);
and
text.setGravity(Gravity.BOTTOM);
and
text.setGravity(Gravity.LEFT);
and
text.setGravity(Gravity.RIGHT);
and
text.setGravity(Gravity.CENTER_VERTICAL);
and
text.setGravity(Gravity.CENTER_HORIZONTAL);
And More Also Avaliable
R adding days to a date
In addition to the simple addition shown by others, you can also use seq.Date
or seq.POSIXt
to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):
> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"
How to define unidirectional OneToMany relationship in JPA
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
Is it possible to include one CSS file in another?
For whatever reason, @import didn't work for me, but it's not really necessary is it?
Here's what I did instead, within the html:
<link rel="stylesheet" media="print" href="myap-print.css">
<link rel="stylesheet" media="print" href="myap-screen.css">
<link rel="stylesheet" media="screen" href="myap-screen.css">
Notice that media="print" has 2 stylesheets: myap-print.css and myap-screen.css. It's the same effect as including myap-screen.css within myap-print.css.
Filling a List with all enum values in Java
I wouldn't use a List in the first places as an EnumSet is more approriate but you can do
List<Something> somethingList = Arrays.asList(Something.values());
or
List<Something> somethingList =
new ArrayList<Something>(EnumSet.allOf(Something.class));
Converting a list to a set changes element order
Answering your first question, a set is a data structure optimized for set operations. Like a mathematical set, it does not enforce or maintain any particular order of the elements. The abstract concept of a set does not enforce order, so the implementation is not required to. When you create a set from a list, Python has the liberty to change the order of the elements for the needs of the internal implementation it uses for a set, which is able to perform set operations efficiently.
How to get a random value from dictionary?
I found this post by looking for a rather comparable solution. For picking multiple elements out of a dict, this can be used:
idx_picks = np.random.choice(len(d), num_of_picks, replace=False) #(Don't pick the same element twice)
result = dict ()
c_keys = [d.keys()] #not so efficient - unfortunately .keys() returns a non-indexable object because dicts are unordered
for i in idx_picks:
result[c_keys[i]] = d[i]
How to convert HTML to PDF using iTextSharp
I use the following code to create PDF
protected void CreatePDF(Stream stream)
{
using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
{
var writer = PdfWriter.GetInstance(document, stream);
writer.PageEvent = new ITextEvents();
document.Open();
// instantiate custom tag processor and add to `HtmlPipelineContext`.
var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
tagProcessorFactory.AddProcessor(
new TableProcessor(),
new string[] { HTML.Tag.TABLE }
);
//Register Fonts.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
htmlPipelineContext.SetTagFactory(tagProcessorFactory);
var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);
// get an ICssResolver and add the custom CSS
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
cssResolver.AddCss(CSSSource, "utf-8", true);
var cssResolverPipeline = new CssResolverPipeline(
cssResolver, htmlPipeline
);
var worker = new XMLWorker(cssResolverPipeline, true);
var parser = new XMLParser(worker);
using (var stringReader = new StringReader(HTMLSource))
{
parser.Parse(stringReader);
document.Close();
HttpContext.Current.Response.ContentType = "application /pdf";
if (base.View)
HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
else
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.WriteFile(OutputPath);
HttpContext.Current.Response.End();
}
}
}
How to check if a string contains only digits in Java
Try this part of code:
void containsOnlyNumbers(String str)
{
try {
Integer num = Integer.valueOf(str);
System.out.println("is a number");
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("is not a number");
}
}
Get the directory from a file path in java (android)
Yes. First, construct a File
representing the image path:
File file = new File(a);
If you're starting from a relative path:
file = new File(file.getAbsolutePath());
Then, get the parent:
String dir = file.getParent();
Or, if you want the directory as a File
object,
File dirAsFile = file.getParentFile();
List to array conversion to use ravel() function
if variable b has a list then you can simply do the below:
create a new variable "a" as: a=[]
then assign the list to "a" as: a=b
now "a" has all the components of list "b" in array.
so you have successfully converted list to array.
failed to find target with hash string android-23
The problem is caused because the code you are running was created in an older API level, And your present SDK Manager doesn't support running them.
So do try the following;
1.Install the SDK Manager that support API level 23.
Go to >SDK Manager, >Android SDK , then select API 23 and install.
2.second alternative is to update your build.grade app module to change
compileSdkVersion,compile,and other numbers to your currently supported API level.
Note:please ensure to check the API and Revision numbers and change them exactly. otherwise Your project won't synchronize
mongodb: insert if not exists
1. Use Update.
Drawing from Van Nguyen's answer above, use update instead of save. This gives you access to the upsert option.
NOTE: This method overrides the entire document when found (From the docs)
var conditions = { name: 'borne' } , update = { $inc: { visits: 1 }} , options = { multi: true };
Model.update(conditions, update, options, callback);
function callback (err, numAffected) { // numAffected is the number of updated documents })
1.a. Use $set
If you want to update a selection of the document, but not the whole thing, you can use the $set method with update. (again, From the docs)...
So, if you want to set...
var query = { name: 'borne' }; Model.update(query, ***{ name: 'jason borne' }***, options, callback)
Send it as...
Model.update(query, ***{ $set: { name: 'jason borne' }}***, options, callback)
This helps prevent accidentally overwriting all of your document(s) with { name: 'jason borne' }
.
Finding the length of a Character Array in C
Although the earlier answers are OK, here's my contribution.
//returns the size of a character array using a pointer to the first element of the character array
int size(char *ptr)
{
//variable used to access the subsequent array elements.
int offset = 0;
//variable that counts the number of elements in your array
int count = 0;
//While loop that tests whether the end of the array has been reached
while (*(ptr + offset) != '\0')
{
//increment the count variable
++count;
//advance to the next element of the array
++offset;
}
//return the size of the array
return count;
}
In your main function, you call the size function by passing the address of the first element of your array.
For example:
char myArray[] = {'h', 'e', 'l', 'l', 'o'};
printf("The size of my character array is: %d\n", size(&myArray[0]));
Difference between numpy dot() and Python 3.5+ matrix multiplication @
The answer by @ajcr explains how the dot
and matmul
(invoked by the @
symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.
To clarify the differences take a 4x4 array and return the dot
product and matmul
product with a 3x4x2 'stack of matricies' or tensor.
import numpy as np
fourbyfour = np.array([
[1,2,3,4],
[3,2,1,4],
[5,4,6,7],
[11,12,13,14]
])
threebyfourbytwo = np.array([
[[2,3],[11,9],[32,21],[28,17]],
[[2,3],[1,9],[3,21],[28,7]],
[[2,3],[1,9],[3,21],[28,7]],
])
print('4x4*3x4x2 dot:\n {}\n'.format(np.dot(fourbyfour,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))
The products of each operation appear below. Notice how the dot product is,
...a sum product over the last axis of a and the second-to-last of b
and how the matrix product is formed by broadcasting the matrix together.
4x4*3x4x2 dot:
[[[232 152]
[125 112]
[125 112]]
[[172 116]
[123 76]
[123 76]]
[[442 296]
[228 226]
[228 226]]
[[962 652]
[465 512]
[465 512]]]
4x4*3x4x2 matmul:
[[[232 152]
[172 116]
[442 296]
[962 652]]
[[125 112]
[123 76]
[228 226]
[465 512]]
[[125 112]
[123 76]
[228 226]
[465 512]]]
How can I return NULL from a generic method in C#?
Take the recommendation of the error... and either user default(T)
or new T
.
You will have to add in a comparison in your code to ensure that it was a valid match if you go that route.
Otherwise, potentially consider an output parameter for "match found".
How to track down access violation "at address 00000000"
The accepted answer does not tell the entire story.
Yes, whenever you see zeros, a NULL
pointer is involved. That is because NULL
is by definition zero. So calling zero NULL
may not be saying much.
What is interesting about the message you get is the fact that NULL
is mentioned twice. In fact, the message you report looks a little bit like the messages Windows-brand operating systems show the user.
The message says the address NULL
tried to read NULL
. So what does that mean? Specifically, how does an address read itself?
We typically think of the instructions at an address reading and writing from memory at certain addresses. Knowing that allows us to parse the error message. The message is trying to articulate that the instruction at address NULL
tried to read NULL
.
Of course, there is no instruction at address NULL
, that is why we think of NULL
as special in our code. But every instruction can be thought of as commencing with the attempt to read itself. If the CPUs EIP
register is at address NULL
, then the CPU will attempt to read the opcode for an instruction from address 0x00000000 (NULL
). This attempt to read NULL
will fail, and generate the message you have received.
In the debugger, notice that EIP
equals 0x00000000 when you receive this message. This confirms the description I have given you.
The question then becomes, "why does my program attempt to execute the NULL
address." There are three possibilities which spring to mind:
- You have attempt to make a function call via a function pointer which you have declared, assigned to
NULL
, never initialized otherwise, and are dereferencing.
- Similarly, you may be calling an "abstract" C++ method which has a
NULL
entry in the object's vtable. These are created in your code with the syntax virtual function_name()=0
.
- In your code, a stack buffer has been overflowed while writing zeros. The zeros have been written beyond the end of the stack buffer, over the preserved return address. When the function later executes its
ret
instruction, the value 0x00000000 (NULL
) is loaded from the overwritten memory spot. This type of error, stack overflow, is the eponym of our forum.
Since you mention that you are calling a third-party library, I will point out that it may be a situation of the library expecting you to provide a non-NULL
function pointer as input to some API. These are sometimes known as "call back" functions.
You will have to use the debugger to narrow down the cause of your problem further, but the above possiblities should help you solve the riddle.
How to Convert date into MM/DD/YY format in C#
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
Others cultures really are a problem. For example, that code in portugues returns someting like 01-01-01 instead of 01/01/01. I also don't undestand why...
To resolve that problem i do someting like this:
IFormatProvider yyyymmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
return date.ToString("MM/dd/yy", yyyymmddFormat);
Making a mocked method return an argument that was passed to it
You might want to use verify() in combination with the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
verify(mock).myFunction(argument.capture());
assertEquals("the expected value here", argument.getValue());
The argument's value is obviously accessible via the argument.getValue() for further manipulation / checking /whatever.
Confirm Password with jQuery Validate
I'm implementing it in Play Framework and for me it worked like this:
1) Notice that I used data-rule-equalTo in input tag for the id inputPassword1.
The code section of userform in my Modal:
<div class="form-group">
<label for="pass1">@Messages("authentication.password")</label>
<input class="form-control required" id="inputPassword1" placeholder="@Messages("authentication.password")" type="password" name="password" maxlength=10 minlength=5>
</div>
<div class="form-group">
<label for="pass2">@Messages("authentication.password2")</label>
<input class="form-control required" data-rule-equalTo="#inputPassword1" id="inputPassword2" placeholder="@Messages("authentication.password")" type="password" name="password2">
</div>
2)Since I used validator within a Modal
$(document).on("click", ".createUserModal", function () {
$(this).find('#userform').validate({
rules: {
firstName: "required",
lastName: "required",
nationalId: {
required: true,
digits:true
},
email: {
required: true,
email: true
},
optradio: "required",
password :{
required: true,
minlength: 5
},
password2: {
required: true
}
},
highlight: function (element) {
$(element).parent().addClass('error')
},
unhighlight: function (element) {
$(element).parent().removeClass('error')
},
onsubmit: true
});
});
Hope it helps someone :).
How to determine if binary tree is balanced?
RE: @lucky's solution using a BFS to do a level-order traversal.
We traverse the tree and keep a reference to vars min/max-level which describe the minimum level at which a node is a leaf.
I believe that the @lucky solution requires a modification. As suggested by @codaddict, rather than checking if a node is a leaf, we must check if EITHER the left or right children is null (not both). Otherwise, the algorithm would consider this a valid balanced tree:
1
/ \
2 4
\ \
3 1
In Python:
def is_bal(root):
if root is None:
return True
import queue
Q = queue.Queue()
Q.put(root)
level = 0
min_level, max_level = sys.maxsize, sys.minsize
while not Q.empty():
level_size = Q.qsize()
for i in range(level_size):
node = Q.get()
if not node.left or node.right:
min_level, max_level = min(min_level, level), max(max_level, level)
if node.left:
Q.put(node.left)
if node.right:
Q.put(node.right)
level += 1
if abs(max_level - min_level) > 1:
return False
return True
This solution should satisfy all the stipulations provided in the initial question, operating in O(n) time and O(n) space. Memory overflow would be directed to the heap rather than blowing a recursive call-stack.
Alternatively, we could initially traverse the tree to compute + cache max heights for each root subtree iteratively. Then in another iterative run, check if the cached heights of the left and right subtrees for each root never differ by more than one. This would also run in O(n) time and O(n) space but iteratively so as not to cause stack overflow.
Invalid Host Header when ngrok tries to connect to React dev server
I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:
module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
}, }
Require the file in the server.
const configstrp = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;
and connect as such
if (ngrok) {
console.log('If nGronk')
ngrok.connect(
{
addr: configstrp.ngrok.port,
subdomain: configstrp.ngrok.subdomain,
authtoken: configstrp.ngrok.authtoken,
host_header:3000
},
(err, url) => {
if (err) {
} else {
}
}
);
}
Do not pass a subdomain if you do not have a custom domain
How to export all collections in MongoDB?
For lazy people, use mongodump
, it's faster:
mongodump -d <database_name> -o <directory_backup>
And to "restore/import" it (from directory_backup/dump/):
mongorestore -d <database_name> <directory_backup>
This way, you don't need to deal with all collections individually. Just specify the database.
Note that I would recommend against using mongodump
/mongorestore
for big data storages. It is very slow and once you get past 10/20GB of data it can take hours to restore.