Recommended SQL database design for tags or tagging
Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.
Table: Item
Columns: ItemID, Title, Content
Table: Tag
Columns: TagID, Title
Table: ItemTag
Columns: ItemID, TagID
What's the difference between identifying and non-identifying relationships?
Let's say we have those tables:
user
--------
id
name
comments
------------
comment_id
user_id
text
relationship between those two tables will identifiying relationship. Because, comments only can be belong to its owner, not other users. for example. Each user has own comment, and when user is deleted, this user's comments also should be deleted.
Need a good hex editor for Linux
Bless is a high quality, full featured hex editor.
It is written in mono/Gtk# and its primary platform is GNU/Linux. However it should be able to run without problems on every platform that mono and Gtk# run.
Bless currently provides the following features:
- Efficient editing of large data files and block devices.
- Multilevel undo - redo operations.
- Customizable data views.
- Fast data rendering on screen.
- Multiple tabs.
- Fast find and replace operations.
- A data conversion table.
- Advanced copy/paste capabilities.
- Highlighting of selection pattern matches in the file.
- Plugin based architecture.
- Export of data to text and html (others with plugins).
- Bitwise operations on data.
- A comprehensive user manual.
wxHexEditor is another Free Hex Editor, built because there is no good hex editor for Linux system, specially for big files.
- It uses 64 bit file descriptors (supports files or devices up to 2^64 bytes , means some exabytes but tested only 1 PetaByte file (yet). ).
- It does NOT copy whole file to your RAM. That make it FAST and can open files (which sizes are Multi Giga < Tera < Peta < Exabytes)
- Could open your devices on Linux, Windows or MacOSX.
- Memory Usage : Currently ~10 MegaBytes while opened multiple > ~8GB files.
- Could operate thru XOR encryption.
- Written with C++/wxWidgets GUI libs and can be used with other OSes such as Mac OS, Windows as native application.
- You can copy/edit your Disks, HDD Sectors with it.( Usefull for rescue files/partitions by hand. )
- You can delete/insert bytes to file, more than once, without creating temp file.
DHEX is a more than just another hex editor: It includes a diff mode, which can be used to easily and conveniently compare two binary files. Since it is based on ncurses and is themeable, it can run on any number of systems and scenarios. With its utilization of search logs, it is possible to track changes in different iterations of files easily. Wikipedia article
You can sort on Linux to find some more here:
http://en.wikipedia.org/wiki/Comparison_of_hex_editors
What is the function __construct used for?
__construct simply initiates a class. Suppose you have the following code;
Class Person {
function __construct() {
echo 'Hello';
}
}
$person = new Person();
//the result 'Hello' will be shown.
We did not create another function to echo the word 'Hello'. It simply shows that the keyword __construct is quite useful in initiating a class or an object.
Flushing buffers in C
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf()
it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf
something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf()
, so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf()
is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin
), you should not do that. Flushing stdin
is undefined behavior according to the C11 standard §7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush()
, there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge()
on that.
See here for more on fflush()
and fpurge()
How to install latest version of openssl Mac OS X El Capitan
I can't reproduce your issue running El Cap + Homebrew 1.0.x
Upgrade to Homebrew 1.0.x, which was released late in September. Specific changes were made in the way openssl is linked. The project is on a more robust release schedule now that it's hit 1.0.
brew uninstall openssl
brew update && brew upgrade && brew cleanup && brew doctor
You should fix any issues raised by brew doctor
before proceeding.
brew install openssl
Note: Upgrading homebrew will update all your installed packages to their latest versions.
How to do IF NOT EXISTS in SQLite
How about this?
INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received'
(Untested as I don't have SQLite... however this link is quite descriptive.)
Additionally, this should also work:
INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');
Black transparent overlay on image hover with only CSS?
You were close. This will work:
.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }
You needed to put the :hover
on image, and make the .overlay
cover the whole image by adding right:0;
and bottom:0
.
jsfiddle: http://jsfiddle.net/Zf5am/569/
Clear History and Reload Page on Login/Logout Using Ionic Framework
As pointed out by @ezain reload controllers only when its necessary. Another cleaner way of updating data when changing states rather than reloading the controller is using broadcast events and listening to such events in controllers that need to update data on views.
Example: in your login/logout functions you can do something like so:
$scope.login = function(){
//After login logic then send a broadcast
$rootScope.$broadcast("user-logged-in");
$state.go("mainPage");
};
$scope.logout = function(){
//After logout logic then send a broadcast
$rootScope.$broadcast("user-logged-out");
$state.go("mainPage");
};
Now in your mainPage controller trigger the changes in the view by using the $on function to listen to broadcast within the mainPage Controller like so:
$scope.$on("user-logged-in", function(){
//update mainPage view data here eg. $scope.username = 'John';
});
$scope.$on("user-logged-out", function(){
//update mainPage view data here eg. $scope.username = '';
});
How to Set a Custom Font in the ActionBar Title?
From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!
Follow these steps to change the font of Toolbar Title:
- Read Downloadable Fonts & select any font from the list (my recommendation) or load a custom font to
res > font
as per Fonts in XML
In res > values > styles
, paste the following (use your imagination here!)
<style name="TitleBarTextAppearance" parent="android:TextAppearance">
<item name="android:fontFamily">@font/your_desired_font</item>
<item name="android:textSize">23sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@android:color/white</item>
</style>
Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont"
as shown below
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextAppearance="@style/TitleBarTextAppearance"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
Enjoy Custom Actionbar Title font styling!!
How to access a property of an object (stdClass Object) member/element of an array?
You have an array. A PHP array is basically a "list of things". Your array has one thing in it. That thing is a standard class. You need to either remove the thing from your array
$object = array_shift($array);
var_dump($object->id);
Or refer to the thing by its index in the array.
var_dump( $array[0]->id );
Or, if you're not sure how many things are in the array, loop over the array
foreach($array as $key=>$value)
{
var_dump($value->id);
var_dump($array[$key]->id);
}
How to use refs in React with Typescript
class SelfFocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{
ctrls: {
input?: HTMLInputElement;
} = {};
render() {
return (
<input
ref={(input) => this.ctrls.input = input}
value={this.props.value}
onChange={(e) => { this.props.onChange(this.ctrls.input.value) } }
/>
);
}
componentDidMount() {
this.ctrls.input.focus();
}
}
put them in an object
Automatically creating directories with file output
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
what is .subscribe in angular?
A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes of the resource held by the subscription.
import { interval } from 'rxjs';
const observable = interval(1000);
const subscription = observable.subscribe(a=> console.log(a));
/** This cancels the ongoing Observable execution which
was started by calling subscribe with an Observer.*/
subscription.unsubscribe();
A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions.
import { interval } from 'rxjs';
const observable1 = interval(400);
const observable2 = interval(300);
const subscription = observable1.subscribe(x => console.log('first: ' + x));
const childSubscription = observable2.subscribe(x => console.log('second: ' + x));
subscription.add(childSubscription);
setTimeout(() => {
// It unsubscribes BOTH subscription and childSubscription
subscription.unsubscribe();
}, 1000);
According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.
best way to create object
Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.
The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.
My personal preference is to go with a bare constructor and set any properties as part of the declaration.
Person p=new Person()
{
Name = "Han Solo",
Age = 39
};
This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).
What is the difference between JAX-RS and JAX-WS?
Can JAX-RS do Asynchronous Request like JAX-WS?
1) I don't know if the JAX-RS API includes a specific mechanism for asynchronous requests, but this answer could still change based on the client implementation you use.
Can JAX-RS access a web service that is not running on the Java platform, and vice versa?
2) I can't think of any reason it wouldn't be able to.
What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?
3) REST based architectures typically will use a lightweight data format, like JSON, to send data back and forth. This is in contrast to JAX-WS which uses XML. I don't see XML by itself so significantly heavier than JSON (which some people may argue), but with JAX-WS it's how much XML is used that ends up making REST with JSON the lighter option.
What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?
4) As stated in 3, REST architectures often use JSON to send and receive data. JAX-WS uses XML. It's not that JSON is so significantly smaller than XML by itself. It's mostly that JAX-WS specification includes lots overhead in how it communicates.
On the point about WSDL and API definitions, REST will more frequently use the URI structure and HTTP commands to define the API rather than message types, as is done in the JAX-WS. This means that you don't need to publish a WSDL document so that other users of your service can know how to talk to your service. With REST you will still need to provide some documentation to other users about how the REST service is organized and what data and HTTP commands need to be sent.
JQuery - Get select value
val() returns the value of the <select>
element, i.e. the value
attribute of the selected <option>
element.
Since you actually want the inner text of the selected <option>
element, you should match that element and use text() instead:
var nationality = $("#dancerCountry option:selected").text();
How do you get git to always pull from a specific branch?
If you prefer, you can set these options via the commmand line (instead of editing the config file) like so:
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
Or, if you're like me, and want this to be the default across all of your projects, including those you might work on in the future, then add it as a global config setting:
$ git config --global branch.master.remote origin
$ git config --global branch.master.merge refs/heads/master
How to make div fixed after you scroll to that div?
<script>
if($(window).width() >= 1200){
(function($) {
var element = $('.to_move_content'),
originalY = element.offset().top;
// Space between element and top of screen (when scrolling)
var topMargin = 10;
// Should probably be set in CSS; but here just for emphasis
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + topMargin
}, 0);
});
})(jQuery);
}
Try this ! just add class .to_move_content to you div
How to properly seed random number generator
Every time the randint() method is called inside the for loop a different seed is set and a sequence is generated according to the time. But as for loop runs fast in your computer in a small time the seed is almost same and a very similar sequence is generated to the past one due to the time. So setting the seed outside the randint() method is enough.
package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
var r = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
func main() {
fmt.Println(randomString(10))
}
func randomString(l int) string {
var result bytes.Buffer
var temp string
for i := 0; i < l; {
if string(randInt(65, 90)) != temp {
temp = string(randInt(65, 90))
result.WriteString(temp)
i++
}
}
return result.String()
}
func randInt(min int, max int) int {
return min + r.Intn(max-min)
}
How can I give eclipse more memory than 512M?
I don't think you need to change the MaxPermSize to 1024m. This works for me:
-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms256m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m
Stacked Tabs in Bootstrap 3
Left, Right and Below tabs were removed from Bootstrap 3, but you can add custom CSS to achieve this..
.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
border-bottom: 0;
}
.tab-content > .tab-pane,
.pill-content > .pill-pane {
display: none;
}
.tab-content > .active,
.pill-content > .active {
display: block;
}
.tabs-below > .nav-tabs {
border-top: 1px solid #ddd;
}
.tabs-below > .nav-tabs > li {
margin-top: -1px;
margin-bottom: 0;
}
.tabs-below > .nav-tabs > li > a {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px;
}
.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
border-top-color: #ddd;
border-bottom-color: transparent;
}
.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
border-color: transparent #ddd #ddd #ddd;
}
.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
float: none;
}
.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
min-width: 74px;
margin-right: 0;
margin-bottom: 3px;
}
.tabs-left > .nav-tabs {
float: left;
margin-right: 19px;
border-right: 1px solid #ddd;
}
.tabs-left > .nav-tabs > li > a {
margin-right: -1px;
-webkit-border-radius: 4px 0 0 4px;
-moz-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
border-color: #eeeeee #dddddd #eeeeee #eeeeee;
}
.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
border-color: #ddd transparent #ddd #ddd;
*border-right-color: #ffffff;
}
.tabs-right > .nav-tabs {
float: right;
margin-left: 19px;
border-left: 1px solid #ddd;
}
.tabs-right > .nav-tabs > li > a {
margin-left: -1px;
-webkit-border-radius: 0 4px 4px 0;
-moz-border-radius: 0 4px 4px 0;
border-radius: 0 4px 4px 0;
}
.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
border-color: #eeeeee #eeeeee #eeeeee #dddddd;
}
.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
border-color: #ddd #ddd #ddd transparent;
*border-left-color: #ffffff;
}
Working example: http://bootply.com/74926
UPDATE
If you don't need the exact look of a tab (bordered appropriately on the left or right as each tab is activated), you can simple use nav-stacked
, along with Bootstrap col-*
to float the tabs to the left or right...
nav-stacked
demo: http://codeply.com/go/rv3Cvr0lZ4
<ul class="nav nav-pills nav-stacked col-md-3">
<li><a href="#a" data-toggle="tab">1</a></li>
<li><a href="#b" data-toggle="tab">2</a></li>
<li><a href="#c" data-toggle="tab">3</a></li>
</ul>
How to install PIP on Python 3.6?
I have in this moment install the bs4 with python 3.6.3 on Windows.
C:\yourfolderx\yourfoldery>python.exe -m pip install bs4
with the syntax like the user post below:
I just successfully installed a package for excel. After installing the python 3.6, you have to download the desired package, then install. For eg,
python.exe -m pip download openpyxl==2.1.4
python.exe -m pip install openpyxl==2.1.4
Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object
What is the value you're passing to the primary key (presumably "pk_OrderID")? You can set it up to auto increment, and then there should never be a problem with duplicating the value - the DB will take care of that. If you need to specify a value yourself, you'll need to write code to determine what the max value for that field is, and then increment that.
If you have a column named "ID" or such that is not shown in the query, that's fine as long as it is set up to autoincrement - but it's probably not, or you shouldn't get that err msg. Also, you would be better off writing an easier-on-the-eye query and using params. As the lad of nine years hence inferred, you're leaving your database open to SQL injection attacks if you simply plop in user-entered values. For example, you could have a method like this:
internal static int GetItemIDForUnitAndItemCode(string qry, string unit, string itemCode)
{
int itemId;
using (SqlConnection sqlConn = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
{
using (SqlCommand cmd = new SqlCommand(qry, sqlConn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 25).Value = unit;
cmd.Parameters.Add("@ItemCode", SqlDbType.VarChar, 25).Value = itemCode;
sqlConn.Open();
itemId = Convert.ToInt32(cmd.ExecuteScalar());
}
}
return itemId;
}
...that is called like so:
int itemId = SQLDBHelper.GetItemIDForUnitAndItemCode(GetItemIDForUnitAndItemCodeQuery, _unit, itemCode);
You don't have to, but I store the query separately:
public static readonly String GetItemIDForUnitAndItemCodeQuery = "SELECT PoisonToe FROM Platypi WHERE Unit = @Unit AND ItemCode = @ItemCode";
You can verify that you're not about to insert an already-existing value by (pseudocode):
bool alreadyExists = IDAlreadyExists(query, value) > 0;
The query is something like "SELECT COUNT FROM TABLE WHERE BLA = @CANDIDATEIDVAL" and the value is the ID you're potentially about to insert:
if (alreadyExists) // keep inc'ing and checking until false, then use that id value
Justin wants to know if this will work:
string exists = "SELECT 1 from AC_Shipping_Addresses where pk_OrderID = " _Order.OrderNumber; if (exists > 0)...
What seems would work to me is:
string existsQuery = string.format("SELECT 1 from AC_Shipping_Addresses where pk_OrderID = {0}", _Order.OrderNumber);
// Or, better yet:
string existsQuery = "SELECT COUNT(*) from AC_Shipping_Addresses where pk_OrderID = @OrderNumber";
// Now run that query after applying a value to the OrderNumber query param (use code similar to that above); then, if the result is > 0, there is such a record.
tap gesture recognizer - which object was tapped?
Define your target selector(highlightLetter:
) with argument as
UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];
Then you can get view by
- (void)highlightLetter:(UITapGestureRecognizer*)sender {
UIView *view = sender.view;
NSLog(@"%d", view.tag);//By tag, you can find out where you had tapped.
}
How to export data to an excel file using PHPExcel
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel.
Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Why am I getting tree conflicts in Subversion?
In my experience, SVN creates a tree conflict WHENEVER I delete a folder. There appears to be no reason.
I'm the only one working on my code -> delete a directory -> commit -> conflict!
I can't wait to switch to Git.
I should clarify - I use Subclipse. That's probably the problem! Again, I can't wait to switch...
Add one year in current date PYTHON
You can use Python-dateutil's relativedelta
to increment a datetime
object while remaining sensitive to things like leap years and month lengths. Python-dateutil comes packaged with matplotlib if you already have that. You can do the following:
from dateutil.relativedelta import relativedelta
new_date = old_date + relativedelta(years=1)
(This answer was given by @Max to a similar question).
But if your date is a string (i.e. not already a datetime
object) you can convert it using datetime:
from datetime import datetime
from dateutil.relativedelta import relativedelta
your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"
datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + relativedelta(years=1)
new_date_string = datetime.strftime(new_date, format_string).replace(' 0', ' ')
new_date_string
will contain "April 1, 2013".
NB: Unfortunately, datetime
only outputs day values as "decimal numbers" - i.e. with leading zeros if they're single digit numbers. The .replace()
at the end is a workaround to deal with this issue copied from @Alex Martelli (see this question for his and other approaches to this problem).
Hibernate: flush() and commit()
session.flush() is synchronise method means to insert data in to database sequentially.if we use this method data will not store in database but it will store in cache,if any exception will rise in middle we can handle it.
But commit() it will store data in database,if we are storing more amount of data then ,there may be chance to get out Of Memory Exception,As like in JDBC program in Save point topic
How to automatically insert a blank row after a group of data
Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.
Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.
no suitable HttpMessageConverter found for response type
This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.
In Spring 4.0.9, we were able to send this
JSONObject jsonCredential = new JSONObject();
jsonCredential.put(APPLICATION_CREDENTIALS, data);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);
In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.
The way Convertors work is that if you have it in your classpath, they get registered.
Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.
Once we added I could see the converter being registered.
Difference between numeric, float and decimal in SQL Server
Guidelines from MSDN: Using decimal, float, and real Data
The default maximum precision of numeric and decimal data types is 38.
In Transact-SQL, numeric is functionally equivalent to the decimal
data type. Use the decimal data type to store numbers with decimals
when the data values must be stored exactly as specified.
The behavior of float and real follows the
IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact
numeric behavior is required, such as in financial applications, in
operations involving rounding, or in equality checks. Instead, use the
integer, decimal, money, or smallmoney data types. Avoid using float
or real columns in WHERE clause search conditions, especially the =
and <> operators. It is best to limit float and real columns to > or <
comparisons.
Check if element is visible in DOM
The accepted answer did not worked for me.
Year 2020 breakdown.
The (elem.offsetParent !== null)
method works fine in Firefox but not in Chrome. In Chrome position: fixed
will also make offsetParent
return null
even the element if visible in the page.
User Phrogz conducted a large test (2,304 divs) on elements with varying properties to demonstrate the issue. https://stackoverflow.com/a/11639664/4481831 . Run it with multiple browsers to see the differences.
Demo:
_x000D_
_x000D_
//different results in Chrome and Firefox
console.log(document.querySelector('#hidden1').offsetParent); //null Chrome & Firefox
console.log(document.querySelector('#fixed1').offsetParent); //null in Chrome, not null in Firefox
_x000D_
<div id="hidden1" style="display:none;"></div>
<div id="fixed1" style="position:fixed;"></div>
_x000D_
_x000D_
_x000D_
The (getComputedStyle(elem).display !== 'none')
does not work because the element can be invisible because one of the parents display property is set to none, getComputedStyle
will not catch that.
Demo:
_x000D_
_x000D_
var child1 = document.querySelector('#child1');
console.log(getComputedStyle(child1).display);
//child will show "block" instead of "none"
_x000D_
<div id="parent1" style="display:none;">
<div id="child1" style="display:block"></div>
</div>
_x000D_
_x000D_
_x000D_
The (elem.clientHeight !== 0)
. This method is not influenced by position: fixed
and it also check if element parents are not-visible. But it has problems with simple elements that do not have a css layout, see more here
Demo:
_x000D_
_x000D_
console.log(document.querySelector('#div1').clientHeight); //not zero
console.log(document.querySelector('#span1').clientHeight); //zero
_x000D_
<div id="div1">test1 div</div>
<span id="span1">test2 span</span>
_x000D_
_x000D_
_x000D_
The (elem.getClientRects().length !== 0)
may seem to solve the problems of the previous 3 methods. However it has problems with elements that use CSS tricks (other then display: none
) to hide in the page.
Demo
_x000D_
_x000D_
console.log(document.querySelector('#notvisible1').getClientRects().length);
console.log(document.querySelector('#notvisible1').clientHeight);
console.log(document.querySelector('#notvisible2').getClientRects().length);
console.log(document.querySelector('#notvisible2').clientHeight);
console.log(document.querySelector('#notvisible3').getClientRects().length);
console.log(document.querySelector('#notvisible3').clientHeight);
_x000D_
<div id="notvisible1" style="height:0; overflow:hidden; background-color:red;">not visible 1</div>
<div id="notvisible2" style="visibility:hidden; background-color:yellow;">not visible 2</div>
<div id="notvisible3" style="opacity:0; background-color:blue;">not visible 3</div>
_x000D_
_x000D_
_x000D_
Conclusion.
So what I have showed you is that no method is perfect. To make a proper visibility check, you must use a combination of the last 3 methods.
Visual Studio 64 bit?
Is there any 64 bit Visual Studio at all?
Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows
Why not?
Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...
So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:
- Visual Studio will drop 32bit support and become 64bit,
- Visual Studio Code will take it's place instead,
- Visual Studio will have similar functionality like WOW64 for old extensions which is I believe unlikely to happen.
I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,
Exporting functions from a DLL with dllexport
For C++ :
I just faced the same issue and I think it is worth mentioning a problem comes up when one use both __stdcall
(or WINAPI
) and extern "C"
:
As you know extern "C"
removes the decoration so that instead of :
__declspec(dllexport) int Test(void) --> dumpbin : ?Test@@YaHXZ
you obtain a symbol name undecorated:
extern "C" __declspec(dllexport) int Test(void) --> dumpbin : Test
However the _stdcall
( = macro WINAPI, that changes the calling convention) also decorates names so that if we use both we obtain :
extern "C" __declspec(dllexport) int WINAPI Test(void) --> dumpbin : _Test@0
and the benefit of extern "C"
is lost because the symbol is decorated (with _ @bytes)
Note that this only occurs for x86 architecture because
the __stdcall
convention is ignored on x64 (msdn : on x64 architectures, by convention, arguments are passed in registers when possible, and subsequent arguments are passed on the stack.).
This is particularly tricky if you are targeting both x86 and x64 platforms.
Two solutions
Use a definition file. But this forces you to maintain the state of the def file.
the simplest way : define the macro (see msdn) :
#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "="
__FUNCDNAME__)
and then include the following pragma in the function body:
#pragma EXPORT
Full Example :
int WINAPI Test(void)
{
#pragma EXPORT
return 1;
}
This will export the function undecorated for both x86 and x64 targets while preserving the __stdcall
convention for x86. The __declspec(dllexport)
is not required in this case.
Pass array to MySQL stored routine
I've come up with an awkward but functional solution for my problem. It works for a one-dimensional array (more dimensions would be tricky) and input that fits into a varchar
:
declare pos int; -- Keeping track of the next item's position
declare item varchar(100); -- A single item of the input
declare breaker int; -- Safeguard for while loop
-- The string must end with the delimiter
if right(inputString, 1) <> '|' then
set inputString = concat(inputString, '|');
end if;
DROP TABLE IF EXISTS MyTemporaryTable;
CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
set breaker = 0;
while (breaker < 2000) && (length(inputString) > 1) do
-- Iterate looking for the delimiter, add rows to temporary table.
set breaker = breaker + 1;
set pos = INSTR(inputString, '|');
set item = LEFT(inputString, pos - 1);
set inputString = substring(inputString, pos + 1);
insert into MyTemporaryTable values(item);
end while;
For example, input for this code could be the string Apple|Banana|Orange
. MyTemporaryTable
will be populated with three rows containing the strings Apple
, Banana
, and Orange
respectively.
I thought the slow speed of string handling would render this approach useless, but it was quick enough (only a fraction of a second for a 1,000 entries array).
Hope this helps somebody.
Android: Internet connectivity change listener
Here's the Java code using registerDefaultNetworkCallback
(and registerNetworkCallback
for API < 24):
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
// network available
}
@Override
public void onLost(Network network) {
// network unavailable
}
};
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.registerNetworkCallback(request, networkCallback);
}
How to initialize weights in PyTorch?
We compare different mode of weight-initialization using the same neural-network(NN) architecture.
All Zeros or Ones
If you follow the principle of Occam's razor, you might think setting all the weights to 0 or 1 would be the best solution. This is not the case.
With every weight the same, all the neurons at each layer are producing the same output. This makes it hard to decide which weights to adjust.
# initialize two NN's with 0 and 1 constant weights
model_0 = Net(constant_weight=0)
model_1 = Net(constant_weight=1)
Validation Accuracy
9.625% -- All Zeros
10.050% -- All Ones
Training Loss
2.304 -- All Zeros
1552.281 -- All Ones
Uniform Initialization
A uniform distribution has the equal probability of picking any number from a set of numbers.
Let's see how well the neural network trains using a uniform weight initialization, where low=0.0
and high=1.0
.
Below, we'll see another way (besides in the Net class code) to initialize the weights of a network. To define weights outside of the model definition, we can:
- Define a function that assigns weights by the type of network layer, then
- Apply those weights to an initialized model using
model.apply(fn)
, which applies a function to each model layer.
# takes in a module and applies the specified weight initialization
def weights_init_uniform(m):
classname = m.__class__.__name__
# for every Linear layer in a model..
if classname.find('Linear') != -1:
# apply a uniform distribution to the weights and a bias=0
m.weight.data.uniform_(0.0, 1.0)
m.bias.data.fill_(0)
model_uniform = Net()
model_uniform.apply(weights_init_uniform)
Validation Accuracy
36.667% -- Uniform Weights
Training Loss
3.208 -- Uniform Weights
General rule for setting weights
The general rule for setting the weights in a neural network is to set them to be close to zero without being too small.
Good practice is to start your weights in the range of [-y, y] where y=1/sqrt(n)
(n is the number of inputs to a given neuron).
# takes in a module and applies the specified weight initialization
def weights_init_uniform_rule(m):
classname = m.__class__.__name__
# for every Linear layer in a model..
if classname.find('Linear') != -1:
# get the number of the inputs
n = m.in_features
y = 1.0/np.sqrt(n)
m.weight.data.uniform_(-y, y)
m.bias.data.fill_(0)
# create a new model with these weights
model_rule = Net()
model_rule.apply(weights_init_uniform_rule)
below we compare performance of NN, weights initialized with uniform distribution [-0.5,0.5) versus the one whose weight is initialized using general rule
Validation Accuracy
75.817% -- Centered Weights [-0.5, 0.5)
85.208% -- General Rule [-y, y)
Training Loss
0.705 -- Centered Weights [-0.5, 0.5)
0.469 -- General Rule [-y, y)
normal distribution to initialize the weights
The normal distribution should have a mean of 0 and a standard deviation of y=1/sqrt(n)
, where n is the number of inputs to NN
## takes in a module and applies the specified weight initialization
def weights_init_normal(m):
'''Takes in a module and initializes all linear layers with weight
values taken from a normal distribution.'''
classname = m.__class__.__name__
# for every Linear layer in a model
if classname.find('Linear') != -1:
y = m.in_features
# m.weight.data shoud be taken from a normal distribution
m.weight.data.normal_(0.0,1/np.sqrt(y))
# m.bias.data should be 0
m.bias.data.fill_(0)
below we show the performance of two NN one initialized using uniform-distribution and the other using normal-distribution
Validation Accuracy
85.775% -- Uniform Rule [-y, y)
84.717% -- Normal Distribution
Training Loss
0.329 -- Uniform Rule [-y, y)
0.443 -- Normal Distribution
What is the @Html.DisplayFor syntax for?
After looking for an answer for myself for some time, i could find something.
in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML
Below is generated HTML for example, when i want to display only Name property for my class
<td>
myClassNameProperty
</td>
<td>
myClassNameProperty, This is direct from Item
</td>
This is the generated HTML from below code
<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)
</td>
<td>
@item.Genre.Name, This is direct from Item
</td>
At the same time now if i want to display all properties in one statement for my class "Genre" in this case,
i can use @Html.DisplayFor() to save on my typing, for least
i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below
@item.Genre.Name
@item.Genre.Id
@item.Genre.Description
and so on depending on number of properties.
SELECT INTO Variable in MySQL DECLARE causes syntax error?
It is worth noting that despite the fact that you can SELECT INTO
global variables like:
SELECT ... INTO @XYZ ...
You can NOT use FETCH INTO
global variables like:
FETCH ... INTO @XYZ
Looks like it's not a bug. I hope it will be helpful to someone...
Is it a good practice to place C++ definitions in header files?
I think your co-worker is smart and you are also correct.
The useful things I found that putting everything into the headers is that:
No need for writing & sync headers and sources.
The structure is plain and no circular dependencies force the coder to make a "better" structure.
Portable, easy to embedded to a new project.
I do agree with the compiling time problem, but I think we should notice that:
The change of source file are very likely to change the header files which leads to the whole project be recompiled again.
Compiling speed is much faster than before. And if you have a project to be built with a long time and high frequency, it may indicates that your project design has flaws. Seperate the tasks into different projects and module can avoid this problem.
Lastly I just wanna support your co-worker, just in my personal view.
How to create Custom Ratings bar in Android
You can use @erdomester 's given solution for this. But if you are facing issues with rating bar height then you can use ratingbar's icons height programmatically.
In Kotlin,
val drawable = ContextCompat.getDrawable(context, R.drawable.rating_filled)
val drawableHeight = drawable.intrinsicHeight
rating_bar.layoutParams.height = drawableHeight
Switch to selected tab by name in Jquery-UI Tabs
The only practical way to get the zero-based index of your tabs is to step through each of the elements that make the tabset (the LI>A s) and match on their inner text. It can probably be done in a cleaner way, but here's how I did it.
$('#tabs ul li a').each(function(i) {
if (this.text == 'Two') {$('#reqTab').val(i)}
});
$("#tabs").tabs({
selected: $('#reqTab').val()
});
You can see that I used a hidden <input id="reqTab"> field in the page to make sure the variable moved from one function to the other.
NOTE: There is a little bit of a gotcha -- selecting tabs after the tabset is activated doesn't seem to work as advertised in jQuery UI 1.8, which is why I used the identified index from my first pass in order to initialize the tabset with the desired tab selected.
ASP.NET Web Application Message Box
not really. Server side code is happening on the server--- you can use javascript to display something to the user on the client side, but it obviously will only execute on the client side. This is the nature of a client server web technology. You're basically disconnected from the server when you get your response.
iPhone App Icons - Exact Radius?
As others have said, you don't want to round your corners. You want to ship flat (no layers or alpha) square graphics. Apple changed the mask they use for rounding your corners in iOS7 and then again in iOS8. You can find these masks inside your Xcode application bundle. The path changes with every new SDK version they release. So, I'll show you how you can always find it.
find /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs -name 'MobileIcons.framework'
At this very moment, the path found by that command is /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/MobileIcons.framework
but don't trust that. Use the command to find it yourself.
That path points to a directory with these files (again, at the time of this post)
./AppFolderBadgeIconMask-128_1only_.png
./AppFolderBadgeIconMask-16_1only_.png
./AppFolderBadgeIconMask-256_1only_.png
./AppFolderBadgeIconMask-32_1only_.png
./AppFolderBadgeIconMask-512_1only_.png
./AppFolderBadgeIconOverlay-128_1only_.png
./AppFolderBadgeIconOverlay-16_1only_.png
./AppFolderBadgeIconOverlay-256_1only_.png
./AppFolderBadgeIconOverlay-32_1only_.png
./AppFolderBadgeIconOverlay-512_1only_.png
./AppFolderBadgeIconShadow-128_1only_.png
./AppFolderBadgeIconShadow-16_1only_.png
./AppFolderBadgeIconShadow-256_1only_.png
./AppFolderBadgeIconShadow-32_1only_.png
./AppFolderBadgeIconShadow-512_1only_.png
./AppIconMask@2x~ipad.png
./AppIconMask@2x~iphone.png
./AppIconMask@3x~iphone.png
./AppIconMask~ipad.png
./AppIconMask~iphone.png
./CarAppIconMask.png
./CarNotificationAppIconMask.png
./DefaultIcon-20.png
./[email protected]
./[email protected]
./DefaultIcon-29.png
./[email protected]
./[email protected]
./DefaultIcon-40.png
./[email protected]
./[email protected]
./DefaultIcon-60@2x~iphone.png
./DefaultIcon-60@3x~iphone.png
./DefaultIcon-76@2x~ipad.png
./DefaultIcon-76~ipad.png
./DocumentBadgeMask-145.png
./[email protected]
./DocumentBadgeMask-20.png
./[email protected]
./[email protected]
./DocumentBase-320@2x~ipad.png
./DocumentBase-320~ipad.png
./DocumentBase-48.png
./[email protected]
./[email protected]
./DocumentMask-320@2x~ipad.png
./DocumentMask-320~ipad.png
./DocumentMask-48.png
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./NewsstandDefaultMagazine_1only_.png
./NewsstandDefaultNewspaper_1only_.png
./NewsstandMagazineGradientLeft@2x~ipad.png
./NewsstandMagazineGradientLeft@2x~iphone.png
./NewsstandMagazineGradientLeft~ipad.png
./NewsstandMagazineGradientLeft~iphone.png
./NewsstandMagazineGradientRight@2x~ipad.png
./NewsstandMagazineGradientRight@2x~iphone.png
./NewsstandMagazineGradientRight~ipad.png
./NewsstandMagazineGradientRight~iphone.png
./NewsstandMagazineSwitcherGradientLeft.png
./[email protected]
./NewsstandNewspaperGradientBottom@2x~ipad.png
./NewsstandNewspaperGradientBottom@2x~iphone.png
./NewsstandNewspaperGradientBottom~ipad.png
./NewsstandNewspaperGradientBottom~iphone.png
./NewsstandNewspaperGradientLeft@2x~ipad.png
./NewsstandNewspaperGradientLeft@2x~iphone.png
./NewsstandNewspaperGradientLeft~ipad.png
./NewsstandNewspaperGradientLeft~iphone.png
./NewsstandNewspaperGradientRight@2x~ipad.png
./NewsstandNewspaperGradientRight@2x~iphone.png
./NewsstandNewspaperGradientRight~ipad.png
./NewsstandNewspaperGradientRight~iphone.png
./NewsstandNewspaperSwitcherGradientBottom.png
./[email protected]
./NewsstandNewspaperSwitcherGradientLeft.png
./[email protected]
./NewsstandNewspaperSwitcherGradientRight.png
./[email protected]
./NewsstandThumbnailShadow@2x~ipad.png
./NewsstandThumbnailShadow@2x~iphone.png
./NewsstandThumbnailShadow~ipad.png
./NewsstandThumbnailShadow~iphone.png
./NotificationAppIconMask.png
./[email protected]
./[email protected]
./SpotlightAppIconMask.png
./[email protected]
./[email protected]
./TableIconMask.png
./[email protected]
./[email protected]
./TableIconOutline.png
./[email protected]
./[email protected]
As you can see, there are a lot of different masks, but they are named pretty clearly. Here is the AppIconMask@3x~iphone.png
image:
You can use that to test your icon to see if it will look okay after it is masked. But, don't round your corners. If you do, when Apple changes those masks again, you will have artifacts.
How to load data to hive from HDFS without removing the source file?
from your question I assume that you already have your data in hdfs.
So you don't need to LOAD DATA
, which moves the files to the default hive location /user/hive/warehouse
. You can simply define the table using the external
keyword, which leaves the files in place, but creates the table definition in the hive metastore. See here:
Create Table DDL
eg.:
create external table table_name (
id int,
myfields string
)
location '/my/location/in/hdfs';
Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:
row format delimited fields terminated by ','
Key Presses in Python
There's a solution:
import pyautogui
for i in range(1000):
pyautogui.typewrite("a")
Calculating a directory's size using Python?
Chris' answer is good but could be made more idiomatic by using a set to check for seen directories, which also avoids using an exception for control flow:
def directory_size(path):
total_size = 0
seen = set()
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
try:
stat = os.stat(fp)
except OSError:
continue
if stat.st_ino in seen:
continue
seen.add(stat.st_ino)
total_size += stat.st_size
return total_size # size in bytes
Django request get parameters
You may also use:
request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137]
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]
Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).
Border around each cell in a range
You can also include this task within another macro, without opening a new one:
I don't put Sub and end Sub, because the macro contains much longer code, as per picture below
With Sheets("1_PL").Range("EF1631:JJ1897")
With .Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
[![enter image description here][1]][1]End With
How do you easily horizontally center a <div> using CSS?
Using jQuery:
$(document).ready(function() {
$(".myElement").wrap( '<span class="myElement_container_new"></span>' ); // for IE6
$(".myElement_container_new").css({// for IE6
"display" : "block",
"position" : "relative",
"margin" : "0",
"padding" : "0",
"border" : "none",
"background-color" : "transparent",
"clear" : "both",
"text-align" : "center"
});
$(".myElement").css({
"display" : "block",
"position" : "relative",
"max-width" : "75%", // for example
"margin-left" : "auto",
"margin-right" : "auto",
"clear" : "both",
"text-align" : "left"
});
});
or, if you want to center every element with class ".myElement":
$(document).ready(function() {
$(".myElement").each(function() {
$(this).wrap( '<span class="myElement_container_new"></span>' ); // for IE6
$(".myElement_container_new").css({// for IE6
"display" : "block",
"position" : "relative",
"margin" : "0",
"padding" : "0",
"border" : "none",
"background-color" : "transparent",
"clear" : "both",
"text-align" : "center"
});
$(this).css({
"display" : "block",
"position" : "relative",
"max-width" : "75%",
"margin-left" : "auto",
"margin-right" : "auto",
"clear" : "both",
"text-align" : "left"
});
});
});
Bootstrap 3 Collapse show state with Chevron icon
Improvement on Bludream's answer:
You can definitely use FontAwesome!
Make sure to include "collapsed" along with "panel-heading" class. The "collapsed" class is not included until you click on the panel so you want to include the "collapsed" class in order to display the correct chevron (i.e., chevron-right is displayed when collapsed and chevron-down when open).
HTML
<div class="panel panel-default">
<div class="panel-heading collapsed" data-toggle="collapse" data-target="#collapseOrderItems1">Products 1 <i class="chevron fa fa-fw" ></i></div>
<div class="collapse" id="collapseOrderItems1">
<p>Lorem ipsum...</p>
</div>
</div>
CSS
.panel-heading .chevron:after {
content: "\f078";
}
.panel-heading.collapsed .chevron:after {
content: "\f054";
}
Also, it is a good practice to create a new class instead of using an existing class.
See Codepen for example: http://codepen.io/anon/pen/PPxOJX
What exactly is LLVM?
LLVM is a library that is used to construct, optimize and produce intermediate and/or binary machine code.
LLVM can be used as a compiler framework, where you provide the "front end" (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code).
LLVM can also act as a JIT compiler - it has support for x86/x86_64 and PPC/PPC64 assembly generation with fast code optimizations aimed for compilation speed.
Unfortunately disabled since 2013, there was the ability to play with LLVM's machine code generated from C or C++ code at the demo page.
How do I find an element position in std::vector?
Take a look at the answers provided for this question: Invalid value for size_t?. Also you can use std::find_if with std::distance to get the index.
std::vector<type>::iterator iter = std::find_if(vec.begin(), vec.end(), comparisonFunc);
size_t index = std::distance(vec.begin(), iter);
if(index == vec.size())
{
//invalid
}
Plotting histograms from grouped data in a pandas DataFrame
I write this answer because I was looking for a way to plot together the histograms of different groups. What follows is not very smart, but it works fine for me. I use Numpy to compute the histogram and Bokeh for plotting. I think it is self-explanatory, but feel free to ask for clarifications and I'll be happy to add details (and write it better).
figures = {
'Transit': figure(title='Transit', x_axis_label='speed [km/h]', y_axis_label='frequency'),
'Driving': figure(title='Driving', x_axis_label='speed [km/h]', y_axis_label='frequency')
}
cols = {'Vienna': 'red', 'Turin': 'blue', 'Rome': 'Orange'}
for gr in df_trips.groupby(['locality', 'means']):
locality = gr[0][0]
means = gr[0][1]
fig = figures[means]
h, b = np.histogram(pd.DataFrame(gr[1]).speed.values)
fig.vbar(x=b[1:], top=h, width=(b[1]-b[0]), legend_label=locality, fill_color=cols[locality], alpha=0.5)
show(gridplot([
[figures['Transit']],
[figures['Driving']],
]))
LaTeX table too wide. How to make it fit?
Use p{width}
column specifier: e.g. \begin{tabular}{ l p{10cm} }
will put column's content into 10cm-wide parbox, and the text will be properly broken to several lines, like in normal paragraph.
You can also use tabular*
environment to specify width for the entire table.
Select a random sample of results from a query result
We were given and assignment to select only two records from the list of agents..i.e 2 random records for each agent over the span of a week etc.... and below is what we got and it works
with summary as (
Select Dbms_Random.Random As Ran_Number,
colmn1,
colm2,
colm3
Row_Number() Over(Partition By col2 Order By Dbms_Random.Random) As Rank
From table1, table2
Where Table1.Id = Table2.Id
Order By Dbms_Random.Random Asc)
Select tab1.col2,
tab1.col4,
tab1.col5,
From Summary s
Where s.Rank <= 2;
How do you use the Immediate Window in Visual Studio?
One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.
For example, if you had a static method that returns the sum of two numbers such as:
private static int GetSum(int a, int b)
{
return a + b;
}
Then in the Immediate Window you can type the following:
? GetSum(2, 4)
6
As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.
For example, let’s say this is what your class looks like:
private class Foo
{
public string GetMessage()
{
return "hello";
}
}
If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):
? foo.GetMessage(); // object ‘foo’ already exists
"hello"
In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:
? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"
You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:
? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"
Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:
? new Foo().GetMessage()
"hello"
A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.
Along with inspecting methods, you can do simple math equations:
? 5 * 6
30
or compare values:
? 5==6
false
? 6==6
true
The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.
Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.
Unfortunately, another drawback of the Immediate Window is that it does not support loops.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Speed up rsync with Simultaneous/Concurrent File Transfers?
I've developed a python package called: parallel_sync
https://pythonhosted.org/parallel_sync/pages/examples.html
Here is a sample code how to use it:
from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds)
parallelism by default is 10; you can increase it:
from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds, parallelism=20)
however note that ssh typically has the MaxSessions by default set to 10 so to increase it beyond 10, you'll have to modify your ssh settings.
dismissModalViewControllerAnimated deprecated
The new method is:
[self dismissViewControllerAnimated:NO completion:nil];
The word modal has been removed; As it has been for the presenting API call:
[self presentViewController:vc animated:NO completion:nil];
The reasons were discussed in the 2012 WWDC Session 236 - The Evolution of View Controllers on iOS Video. Essentially, view controllers presented by this API are no longer always modal, and since they were adding a completion handler it was a good time to rename it.
In response to comment from Marc:
What's the best way to support all devices 4.3 and above? The new
method doesn't work in iOS4, yet the old method is deprecated in iOS6.
I realize that this is almost a separate question, but I think it's worth a mention since not everyone has the money to upgrade all their devices every 3 years so many of us have some older (pre 5.0) devices. Still, as much as it pains me to say it, you need to consider if it is worth targeting below 5.0. There are many new and cool APIs not available below 5.0. And Apple is continually making it harder to target them; armv6 support is dropped from Xcode 4.5, for example.
To target below 5.0 (as long as the completion block is nil) just use the handy respondsToSelector
: method.
if ([self respondsToSelector:@selector(presentViewController:animated:completion:)]){
[self presentViewController:test animated:YES completion:nil];
} else {
[self presentModalViewController:test animated:YES];
}
In response to another comment from Marc:
That could be quite a lot of If statements in my application!...I was
thinking of creating a category that encapsulated this code, would
creating a category on UIViewControler get me rejected?
and one from Full Decent:
...is there a way to manually cause that to not present a compiler warning?
Firstly, no, creating a category on UIViewController
in and of itself will not get your app rejected; unless that category method called private APIs or something similar.
A category method is an exceedingly good place for such code. Also, since there would be only one call to the deprecated API, there would be only one compiler warning.
To address Full Decent's comment(question), yes you can suppress compiler warnings manually. Here is a link to an answer on SO on that very subject. A category method is also a great place to suppress a compiler warning, since you're only suppressing the warning in one place. You certainly don't want to go around silencing the compiler willy-nilly.
If I was to write a simple category method for this it might be something like this:
@implementation UIViewController (NJ_ModalPresentation)
-(void)nj_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion{
NSAssert(completion == nil, @"You called %@ with a non-nil completion. Don't do that!",NSStringFromSelector(_cmd));
if ([self respondsToSelector:@selector(presentViewController:animated:completion:)]){
[self presentViewController:viewControllerToPresent animated:flag completion:completion];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[self presentModalViewController:viewControllerToPresent animated:flag];
#pragma clang diagnostic pop
}
}
@end
iPhone Safari Web App opens links in new window
This code works for iOS 5 (it worked for me):
In the head tag:
<script type="text/javascript">
function OpenLink(theLink){
window.location.href = theLink.href;
}
</script>
In the link that you want to be opened in the same window:
<a href="(your website here)" onclick="OpenLink(this); return false"> Link </a>
I got this code from this comment: iphone web app meta tags
How to check if a file exists in Go?
The first thing to consider is that it is rare that you would only want to check whether or not a file exists. In most situations, you're trying to do something with the file if it exists. In Go, any time you try to perform some operation on a file that doesn't exist, the result should be a specific error (os.ErrNotExist
) and the best thing to do is check whether the return err
value (e.g. when calling a function like os.OpenFile(...)
) is os.ErrNotExist
.
The recommended way to do this used to be:
file, err := os.OpenFile(...)
if os.IsNotExist(err) {
// handle the case where the file doesn't exist
}
However, since the addition of errors.Is
in Go 1.13 (released in late 2019), the new recommendation is to use errors.Is
:
file, err := os.OpenFile(...)
if errors.Is(err, os.ErrNotExist) {
// handle the case where the file doesn't exist
}
It's usually best to avoid using os.Stat
to check for the existence of a file before you attempt to do something with it, because it will always be possible for the file to be renamed, deleted, etc. in the window of time before you do something with it.
However, if you're OK with this caveat and you really, truly just want to check whether a file exists without then proceeding to do something useful with it (as a contrived example, let's say that you're writing a pointless CLI tool that tells you whether or not a file exists and then exits ¯\_(?)_/¯
), then the recommended way to do it would be:
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
// file does not exist
} else {
// file exists
}
Linux cmd to search for a class file among jars irrespective of jar path
Linux, Walkthrough to find a class file among many jars.
Go to the directory that contains the jars underneath.
eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ ls
blah.txt metrics-core-2.2.0.jar
jopt-simple-3.2.jar scala-library-2.10.1.jar
kafka_2.10-0.8.1.1-sources.jar zkclient-0.3.jar
kafka_2.10-0.8.1.1-sources.jar.asc zookeeper-3.3.4.jar
log4j-1.2.15.jar
I'm looking for which jar provides for the Producer class.
Understand how the for loop works:
eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `seq 1 3`; do
> echo $i
> done
1
2
3
Understand why find this works:
eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ find . -name "*.jar"
./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./slf4j-1.7.7/osgi-over-slf4j-1.7.7-sources.jar
You can pump all the jars underneath into the for loop:
eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `find . -name "*.jar"`; do
> echo $i
> done
./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./kafka_2.10-0.8.1.1-sources.jar
Now we can operate on each one:
Do a jar tf
on every jar and cram it into blah.txt:
for i in `find . -name "*.jar"`; do echo $i; jar tf $i; done > blah.txt
Inspect blah.txt, it's a list of all the classes in all the jars. You can search that file for the class you want, then look for the jar that came before it, that's the one you want.
Rails 4 - passing variable to partial
Don't use locals
in Rails 4.2+
In Rails 4.2 I had to remove the locals
part and just use size: 30
instead. Otherwise, it wouldn't pass the local variable correctly.
For example, use this:
<%= render @users, size: 30 %>
Bootstrap 3 grid with no gap
You'd need to override the negative margins from the .row
in large screens either directly or with a custom class
@media (min-width: 768px){
.row {
margin-right: 0;
margin-left: 0;
}
}
Updated fiddle
Get an element by index in jQuery
You could skip the jquery and just use CSS style tagging:
<ul>
<li>India</li>
<li>Indonesia</li>
<li style="background-color:#343434;">China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>
Encrypt and decrypt a string in C#?
This is the class that was placed here by Brett. However I made a slight edit since I was receiving the error 'Invalid length for a Base-64 char array' when using it for URL strings to encrypt and decrypt.
public class CryptoURL
{
private static byte[] _salt = Encoding.ASCII.GetBytes("Catto_Salt_Enter_Any_Value99");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// The SharedSecret for the Password Reset that is used is in the next line
/// string sharedSecret = "OneUpSharedSecret9";
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptString(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = HttpServerUtility.UrlTokenEncode(msEncrypt.ToArray());
//outStr = Convert.ToBase64String(msEncrypt.ToArray());
// you may need to add a reference. right click reference in solution explorer => "add Reference" => .NET tab => select "System.Web"
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptString(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
byte[] inputByteArray;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
//byte[] bytes = Convert.FromBase64String(cipherText);
inputByteArray = HttpServerUtility.UrlTokenDecode(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(inputByteArray))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
catch (System.Exception ex)
{
return "ERROR";
//throw ex;
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
static string ConvertStringArrayToString(string[] array)
{
//
// Concatenate all the elements into a StringBuilder.
//
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
builder.Append(value);
builder.Append('.');
}
return builder.ToString();
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
creating a random number using MYSQL
This should give what you want:
FLOOR(RAND() * 401) + 100
Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min>
generates a number between <min
> and <max>
inclusive.
Update
This full statement should work:
SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number`
FROM users
Update UI from Thread in Android
If you use Handler
(I see you do and hopefully you created its instance on the UI thread), then don't use runOnUiThread()
inside of your runnable
. runOnUiThread()
is used when you do smth from a non-UI thread, however Handler
will already execute your runnable
on UI thread.
Try to do smth like this:
private Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameone);
res = getResources();
// pB.setProgressDrawable(getResources().getDrawable(R.drawable.green)); **//Works**
mHandler.postDelayed(runnable, 1);
}
private Runnable runnable = new Runnable() {
public void run() {
pB.setProgressDrawable(getResources().getDrawable(R.drawable.green));
pB.invalidate(); // maybe this will even not needed - try to comment out
}
};
How can I use the apply() function for a single column?
You don't need a function at all. You can work on a whole column directly.
Example data:
>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})
>>> df
a b c
0 100 200 300
1 1000 2000 3000
Half all the values in column a
:
>>> df.a = df.a / 2
>>> df
a b c
0 50 200 300
1 500 2000 3000
Visual Studio 2015 is very slow
This answer might seem silly but I had my laptop's power plan set to something other than High performance (in Windows). I would constantly get out of memory warnings in Visual Studio and things would run a bit slow. After I changed the power setting to High performance, I no longer see any problem.
Importing larger sql files into MySQL
Had a similar problem, but in Windows. I was trying to figure out how to open a large MySql sql file in Windows, and these are the steps I had to take:
- Go to the download website (http://dev.mysql.com/downloads/).
- Download the MySQL Community Server and install it (select the developer or full install, so it will install client and server tools).
- Open MySql Command Line Client from the Start menu.
- Enter your password used in install.
In the prompt, mysql>, enter:
CREATE DATABASE database_name;
USE database_name;
SOURCE myfile.sql
That should import your large file.
Gradle, Android and the ANDROID_HOME SDK location
In my case settings.gradle
was missing.
Save the file and put it at the top level folder in your project, even you can copy from another project too.
Screenshot reference:
Hope this would save your time.
Replace given value in vector
A simple way to do this is using ifelse
, which is vectorized. If the condition is satisfied, we use a replacement value, otherwise we use the original value.
v <- c(3, 2, 1, 0, 4, 0)
ifelse(v == 0, 1, v)
We can avoid a named variable by using a pipe.
c(3, 2, 1, 0, 4, 0) %>% ifelse(. == 0, 1, .)
A common task is to do multiple replacements. Instead of nested ifelse
statements, we can use case_when
from dplyr:
case_when(v == 0 ~ 1,
v == 1 ~ 2,
TRUE ~ v)
Old answer:
For factor or character vectors, we can use revalue
from plyr
:
> revalue(c("a", "b", "c"), c("b" = "B"))
[1] "a" "B" "c"
This has the advantage of only specifying the input vector once, so we can use a pipe like
x %>% revalue(c("b" = "B"))
-didSelectRowAtIndexPath: not being called
In my case the problem was I had a UITableViewCell
subclass and I'd implemented these two methods:
touchesBegan:withEvent:
& touchesEnded:withEvent
to handle a fancy animation on touch.
But I'd forgotten to add the [super touchesBegan:touches withEvent:event];
method ad [super touchesEnded:touches withEvent:event];
to also inform the parent of cell of the touch.
So changing the code to following solved my problem:
-(void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
[super touchesBegan:touches withEvent:event];
//blah blah blah
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
//rest of the code
}
Why can't Visual Studio find my DLL?
Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.
Placing the DLL file into the same folder as the executable is by far the simplest solution. That's the default search path for dependencies, so you won't need to do anything special if you go that route.
To avoid having to do this manually each time, you can create a Post-Build Event for your project that will automatically copy the DLL into the appropriate directory after a build completes.
Alternatively, you could deploy the DLL to the Windows side-by-side cache, and add a manifest to your application that specifies the location.
The type or namespace name 'System' could not be found
You can check the framework on which system was created and developed, and then changes the framework of your current solution to the old framework. You can do this by right click on the solution and then choose properties. In Application section you can change the framework.
how to change language for DataTable
//Spanish
$('#TableName').DataTable({
"language": {
"sProcessing": "Procesando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending": ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
}
}
});
Also using a cdn:
//cdn.datatables.net/plug-ins/a5734b29083/i18n/Spanish.json
More options: http://www.datatables.net/plug-ins/i18n/English [| Spanish | etc]
How do I modify the URL without reloading the page?
As pointed out by Thomas Stjernegaard Jeppesen, you could use History.js to modify URL parameters whilst the user navigates through your Ajax links and apps.
Almost an year has passed since that answer, and History.js grew and became more stable and cross-browser. Now it can be used to manage history states in HTML5-compliant as well as in many HTML4-only browsers. In this demo You can see an example of how it works (as well as being able to try its functionalities and limits.
Should you need any help in how to use and implement this library, i suggest you to take a look at the source code of the demo page: you will see it's very easy to do.
Finally, for a comprehensive explanation of what can be the issues about using hashes (and hashbangs), check out this link by Benjamin Lupton.
Converting Python dict to kwargs?
**
operator would be helpful here.
**
operator will unpack the dict elements and thus **{'type':'Event'}
would be treated as type='Event'
func(**{'type':'Event'})
is same as func(type='Event')
i.e the dict elements would be converted to the keyword arguments
.
FYI
*
will unpack the list elements and they would be treated as positional arguments
.
func(*['one', 'two'])
is same as func('one', 'two')
Edit seaborn legend
Took me a while to read through the above. This was the answer for me:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=False
)
plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)
Reference this for more arguments: matplotlib.pyplot.legend
Django: Display Choice Value
Others have pointed out that a get_FOO_display method is what you need.
I'm using this:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
which iterates over all of the choices that a particular item has until it finds the one that matches the items type
How to avoid Sql Query Timeout
Your query is probably fine. "The semaphore timeout period has expired" is a Network error, not a SQL Server timeout.
There is apparently some sort of network problem between you and the SQL Server.
edit: However, apparently the query runs for 15-20 min before giving the network error. That is a very long time, so perhaps the network error could be related to the long execution time. Optimization of the underlying View might help.
If [MyTable] in your example is a View, can you post the View Definition so that we can have a go at optimizing it?
How to initialize a variable of date type in java?
java.util.Date constructor with parameters like
new Date(int year, int month, int date, int hrs, int min).
is deprecated and preferably do not use it any more. Oracle docs prefers the way over java.util.Calendar. So you can set any date and instantiate Date object through the getTime() method.
Calendar calendar = Calendar.getInstance();
calendar.set(2018, 11, 31, 59, 59, 59);
Date happyNewYearDate = calendar.getTime();
Notice that month number starts from 0
What is the difference between an interface and abstract class?
I am constructing a building of 300 floors
The building's blueprint interface
Building constructed up to 200 floors - partially completed---abstract
- Partial implementation, for example, generic and HTTP servlet
Building construction completed-concrete
- Full implementation, for example, own servlet
Interface
- We don't know anything about implementation, just requirements. We can
go for an interface.
- Every method is public and abstract by default
- It is a 100% pure abstract class
- If we declare public we cannot declare private and protected
- If we declare abstract we cannot declare final, static, synchronized, strictfp and native
- Every interface has public, static and final
- Serialization and transient is not applicable, because we can't create an instance for in interface
- Non-volatile because it is final
- Every variable is static
- When we declare a variable inside an interface we need to initialize variables while declaring
- Instance and static block not allowed
Abstract
- Partial implementation
- It has an abstract method. An addition, it uses concrete
- No restriction for abstract class method modifiers
- No restriction for abstract class variable modifiers
- We cannot declare other modifiers except abstract
- No restriction to initialize variables
Taken from DurgaJobs Website
This app won't run unless you update Google Play Services (via Bazaar)
UPDATE
The Google maps API v2 is now installed on the latest Google system images (api:19 ARM or x86).
So your application should just work with the new images. There is no need to install these files.
I've been trying to run an Android Google Maps V2 application under an emulator and once I finally got Google Play Services running, I updated my SDK to Google Play Services revision 4, and my emulator wouldn't run my application any more.
I have now worked out how to update my emulator from my transformer tablet. (You won't need a tablet as you can download the files below.)
I used Titanium Backup to backup my Asus Eee Pad Transformer (TF101) and then grabbed the com.android.vending and the com.google.android.gms APK files from the backup.
I installed these on an emulator configured with platform: 4.1.2, API Level: 16, CPU Intel/Atom x86) and my Google Maps V2 application works again.
That was all .. none of the other steps regarding /system/app were required.
My application only uses the Google Maps API, no doubt, more steps are required if you use other Google Play services.
New files for latest Google Play services:
Same instructions as before: Create a new emulator with any CPU/ABI, a non-Google API target (versions 10-19 work) and GPU emulation on or off, and then install the files:
adb install com.android.vending-20140218.apk
adb install com.google.android.gms-20140218.apk
If you are upgrading an existing emulator then you might need to uninstall previous versions by:
adb uninstall com.android.vending
adb uninstall com.google.android.gms
That's all.
include antiforgerytoken in ajax post ASP.NET MVC
In Asp.Net Core you can request the token directly, as documented:
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
And use it in javascript:
function DoSomething(id) {
$.post("/something/todo/"+id,
{ "__RequestVerificationToken": '@GetAntiXsrfRequestToken()' });
}
You can add the recommended global filter, as documented:
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
})
Update
The above solution works in scripts that are part of the .cshtml. If this is not the case then you can't use this directly. My solution was to use a hidden field to store the value first.
My workaround, still using GetAntiXsrfRequestToken
:
When there is no form:
<input type="hidden" id="RequestVerificationToken" value="@GetAntiXsrfRequestToken()">
The name
attribute can be omitted since I use the id
attribute.
Each form includes this token. So instead of adding yet another copy of the same token in a hidden field, you can also search for an existing field by name
. Please note: there can be multiple forms inside a document, so name
is in that case not unique. Unlike an id
attribute that should be unique.
In the script, find by id:
function DoSomething(id) {
$.post("/something/todo/"+id,
{ "__RequestVerificationToken": $('#RequestVerificationToken').val() });
}
An alternative, without having to reference the token, is to submit the form with script.
Sample form:
<form id="my_form" action="/something/todo/create" method="post">
</form>
The token is automatically added to the form as a hidden field:
<form id="my_form" action="/something/todo/create" method="post">
<input name="__RequestVerificationToken" type="hidden" value="Cf..." /></form>
And submit in the script:
function DoSomething() {
$('#my_form').submit();
}
Or using a post method:
function DoSomething() {
var form = $('#my_form');
$.post("/something/todo/create", form.serialize());
}
Using multiple parameters in URL in express
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
How do I call Objective-C code from Swift?
You can read the nice post Swift & Cocoapods. Basically, we need to create a bridging header file and put all Objective-C headers there. And then we need to reference it from our build settings. After that, we can use the Objective-C code.
let manager = AFHTTPRequestOperationManager()
manager.GET(
"http://example.com/resources.json",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
Also have a look at Apple's document Using Swift with Cocoa and Objective-C as well.
Test if number is odd or even
Another option is to check if the last digit is an even number :
$value = "1024";// A Number
$even = array(0, 2, 4, 6, 8);
if(in_array(substr($value, -1),$even)){
// Even Number
}else{
// Odd Number
}
Or to make it faster, use isset()
instead of array_search
:
$value = "1024";// A Number
$even = array(0 => 1, 2 => 1, 4 => 1, 6 => 1, 8 => 1);
if(isset($even[substr($value, -1)]){
// Even Number
}else{
// Odd Number
}
Or to make it more faster (beats mod operator
at times) :
$even = array(0, 2, 4, 6, 8);
if(in_array(substr($number, -1),$even)){
// Even Number
}else{
// Odd Number
}
Here is the time test as a proof to my findings.
How many bits or bytes are there in a character?
There are 8 bits in a byte (normally speaking in Windows).
However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.
In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.
EDITED
Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.
How do I add all new files to SVN
svn status | grep "^\?" | awk '{ printf("\""); for (f=2; f <= NF; f++) { printf("%s", $f); if (f<NF) printf(" "); } printf("\"\n");}' | xargs svn add
This was based on markb's answer... and a little hunting on the internet. It looks ugly, but it seems to work for me on OS X (including files with spaces).
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
I have faced the same issue. Here is how I have fixed it.
Step 1: Remove mysql using command:
brew uninstall --force mysql
Step 2: Run command brew doctor
which will give you some hint related to your brew packages.
Step 3: Cleanup brew packages using command:
brew cleanup
Step 4: Move/delete previously installed mysql data using command:
mv /usr/local/var/mysql/ /usr/local/var/old_mysql
Step 5: Finally install mysql again using command:
brew install mysql
Difference Between Cohesion and Coupling
Theory Difference
Cohesion
- Cohesion is an indication of relative functional strength of module.
- A cohesive module performs a single task, requiring little interaction with other
components in other parts of program.
- A module having high cohesion and low coupling is said to be functionally independent
of other module.
Classification of Cohesion
1.Coincidental 2.Logical 3.Temporal 4.Procedural 5.Communication 6.Sequential 7.Functional
Coupling
- Coupling is indication of relative interdependence among modules.
- Degree of coupling between two modules depends on their interface complexity.
MongoDB SELECT COUNT GROUP BY
Additionally if you need to restrict the grouping you can use:
db.events.aggregate(
{$match: {province: "ON"}},
{$group: {_id: "$date", number: {$sum: 1}}}
)
For div to extend full height
This might be of some help: http://www.webmasterworld.com/forum83/200.htm
A relevant quote:
Most attempts to accomplish this were made by assigning the property and value:
div{height:100%} - this alone will not work. The reason is that without a parent defined
height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a
value of div{height:auto;} - auto is an "as needed value" which is governed by the actual
content, so that the div{height:100%} will a=only extend as far as the content demands.
The solution to the problem is found by assigning a height value to the parent container,
in this case, the body element. Writing your body stlye to include height 100% supplies
the needed value.
html, body {
margin:0;
padding:0;
height:100%;
}
Send attachments with PHP Mail()?
Swiftmailer is another easy-to-use script that automatically protects against email injection and makes attachments a breeze. I also strongly discourage using PHP's built-in mail()
function.
To use:
- Download Swiftmailer, and place the
lib
folder in your project
- Include the main file using
require_once 'lib/swift_required.php';
Now add the code when you need to mail:
// Create the message
$message = Swift_Message::newInstance()
->setSubject('Your subject')
->setFrom(array('[email protected]' => 'Web Master'))
->setTo(array('[email protected]'))
->setBody('Here is the message itself')
->attach(Swift_Attachment::fromPath('myPDF.pdf'));
//send the message
$mailer->send($message);
More information and options can be found in the Swiftmailer Docs.
How to redirect Valgrind's output to a file?
In addition to the other answers (particularly by Lekakis), some string replacements can also be used in the option --log-file=
as elaborated in the Valgrind's user manual.
Four replacements were available at the time of writing:
%p
: Prints the current process ID
valgrind --log-file="myFile-%p.dat" <application-name>
%n
: Prints file sequence number unique for the current process
valgrind --log-file="myFile-%p-%n.dat" <application-name>
%q{ENV}
: Prints contents of the environment variable ENV
valgrind --log-file="myFile-%q{HOME}.dat" <application-name>
%%
: Prints %
valgrind --log-file="myFile-%%.dat" <application-name>
phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)
Might be late to the party - also, this answer is for LAMP users who got to this thread from google, like me.
Basically, the problem is PMA is trying to connect to SQL with a user that doesn't exist.
At /etc/phpmyadmin/config-db.php, you will find 2 variables: $dbuser, and $dbpass.
Those specify the MySQL user and Password that PMA is trying to connect with.
Now, connect with some username/password that work (or just "root" if you are connecting from localhost), create a new user with global priviliges (e.g - %PMA User% with password %Some Random Password%), then in the above mentioned file set:
$dbuser = %PMA User% ;
$dbpass = %Some Random Password%;
You might also change other stuff there, like the server address ($dbserver), the port ($dbport, which might not be the default one on your machine), and more.
How to remove leading whitespace from each line in a file
For this specific problem, something like this would work:
$ sed 's/^ *//g' < input.txt > output.txt
It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:
$ sed 's/^[ \t]+//g' < input.txt > output.txt
The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.
Finally, instead of < input.txt > output.txt
you can use the -i
option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.
How to add a color overlay to a background image?
background-image
takes multiple values.
so a combination of just 1 color linear-gradient and css blend modes
will do the trick.
.testclass {
background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
background-blend-mode: overlay;
}
note that there is no support on IE/Edge for CSS blend-modes at all.
"message failed to fetch from registry" while trying to install any module
I had this issue with npm v1.1.4
(and node v0.6.12
), which are the Ubuntu 12.04
repository versions.
It looks like that version of npm
isn't supported any more, updating node (and npm with it) resolved the issue.
First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).
sudo apt-get purge nodejs npm
Then enable nodesource's repo and install:
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs
Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:
From: here
Check whether a path is valid
You can try this code:
try
{
Path.GetDirectoryName(myPath);
}
catch
{
// Path is not valid
}
I'm not sure it covers all the cases...
maxlength ignored for input type="number" in Chrome
I have two ways for you do that
First: Use type="tel"
, it'll work like type="number"
in mobile, and accept maxlength:
<input type="tel" />
Second: Use a little bit of JavaScript:
<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />
Wait until all promises complete even if some rejected
I would do:
var err = [fetch('index.html').then((success) => { return Promise.resolve(success); }).catch((e) => { return Promise.resolve(e); }),
fetch('http://does-not-exist').then((success) => { return Promise.resolve(success); }).catch((e) => { return Promise.resolve(e); })];
Promise.all(err)
.then(function (res) { console.log('success', res) })
.catch(function (err) { console.log('error', err) }) //never executed
Stored Procedure error ORA-06550
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
Convert SVG to image (JPEG, PNG, etc.) in the browser
I wrote this ES6 Class which does the Job.
class SvgToPngConverter {
constructor() {
this._init = this._init.bind(this);
this._cleanUp = this._cleanUp.bind(this);
this.convertFromInput = this.convertFromInput.bind(this);
}
_init() {
this.canvas = document.createElement("canvas");
this.imgPreview = document.createElement("img");
this.imgPreview.style = "position: absolute; top: -9999px";
document.body.appendChild(this.imgPreview);
this.canvasCtx = this.canvas.getContext("2d");
}
_cleanUp() {
document.body.removeChild(this.imgPreview);
}
convertFromInput(input, callback) {
this._init();
let _this = this;
this.imgPreview.onload = function() {
const img = new Image();
_this.canvas.width = _this.imgPreview.clientWidth;
_this.canvas.height = _this.imgPreview.clientHeight;
img.crossOrigin = "anonymous";
img.src = _this.imgPreview.src;
img.onload = function() {
_this.canvasCtx.drawImage(img, 0, 0);
let imgData = _this.canvas.toDataURL("image/png");
if(typeof callback == "function"){
callback(imgData)
}
_this._cleanUp();
};
};
this.imgPreview.src = input;
}
}
Here is how you use it
let input = "https://restcountries.eu/data/afg.svg"
new SvgToPngConverter().convertFromInput(input, function(imgData){
// You now have your png data in base64 (imgData).
// Do what ever you wish with it here.
});
If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.
Regex allow digits and a single dot
\d*\.\d*
Explanation:
\d* - any number of digits
\. - a dot
\d* - more digits.
This will match 123.456
, .123
, 123.
, but not 123
If you want the dot to be optional, in most languages (don't know about jquery) you can use
\d*\.?\d*
Singleton: How should it be used
One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.
Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.
Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.
It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.
REST vs JSON-RPC?
Great answers - just wanted to clarify on a some of the comments. JSON-RPC is quick and easy to consume, but as mentioned resources and parameters are tightly coupled and it tends to rely on verbs (api/deleteUser, api/addUser) using GET/ POST where-as REST provides loosely coupled resources (api/users) that in a HTTP REST API relies on several HTTP methods (GET, POST, PUT, PATCH, DELETE). REST is slightly harder for inexperienced developers to implement, but the style has become fairly common place now and it provides much more flexibility in the long-run (giving your API a longer life).
Along with not having tightly coupled resources, REST also allows you to avoid being committed to a single content-type- this means if your client needs to receive the data in XML, or JSON, or even YAML - if built into your system you could return any of those using the content-type/ accept headers.
This lets you keep your API flexible enough to support new content types OR client requirements.
But what truly separates REST from JSON-RPC is that it follows a series of carefully thought out constraints- ensuring architectural flexibility. These constraints include ensuring that the client and server are able to evolve independently of each other (you can make changes without messing up your client's application), the calls are stateless (state is represented through hypermedia), a uniform interface is provided for interactions, the API is developed on a layered system, and the response is cacheable by the client. There's also an optional constraint for providing code on demand.
However, with all of this said - MOST APIs are not RESTful (according to Fielding) as they do not incorporate hypermedia (embedded hypertext links in the response that help navigate the API). Most APIs you will find out there are REST-like in that they follow most of the concepts of REST, but ignore this constraint. However, more and more APIs are implementing this and it is becoming more of a main-stream practice.
This also gives you some flexibility as hypermedia driven APIs (such as Stormpath) direct the client to the URIs (meaning if something changes, in certain cases you can modify the URI without negative impact), where-as with RPC URIs are required to be static. With RPC, you will also need to extensively document these different URIs and explain how they work in relation to each other.
In general, I would say REST is the way to go if you want to build an extensible, flexible API that will be long-lived. For that reason, I would say it's the route to go 99% of the time.
Good luck,
Mike
Get current index from foreach loop
You have two options here, 1. Use for
instead for foreach
for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:
int i = 0; // for index
foreach (var row in list)
{
bool IsChecked;// assign value to this variable
if (IsChecked)
{
// use i value here
}
i++; // will increment i in each iteration
}
Sprintf equivalent in Java
Strings are immutable types. You cannot modify them, only return new string instances.
Because of that, formatting with an instance method makes little sense, as it would have to be called like:
String formatted = "%s: %s".format(key, value);
The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.
Here is an example of why format()
would be dumb as an instance method. In .NET (and probably in Java), Replace()
is an instance method.
You can do this:
"I Like Wine".Replace("Wine","Beer");
However, nothing happens, because strings are immutable. Replace()
tries to return a new string, but it is assigned to nothing.
This causes lots of common rookie mistakes like:
inputText.Replace(" ", "%20");
Again, nothing happens, instead you have to do:
inputText = inputText.Replace(" ","%20");
Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for Replace()
would be where format()
is, as a static method of String
:
inputText = String.Replace(inputText, " ", "%20");
Now there is no question as to what's going on.
The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.
Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).
Of course there are some methods that are perfect as instance methods, take String.Length()
int length = "123".Length();
In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.
My simple rules for Instance Methods on Immutable Objects:
- If you need to return a new instance of the same type, use a static method.
- Otherwise, use an instance method.
MySQL equivalent of DECODE function in Oracle
Try this:
Select Name, ELT(Age-12,'Thirteen','Fourteen','Fifteen','Sixteen',
'Seventeen','Eighteen','Nineteen','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult') AS AgeBracket FROM Person
Filter Extensions in HTML form upload
The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.
Additionally, it appears that most browsers may not honor this attribute.
The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.
Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.
How can I programmatically get the MAC address of an iphone
It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift.
As Apple stated:
In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)
android get all contacts
public class MyActivity extends Activity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int CONTACTS_LOADER_ID = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(CONTACTS_LOADER_ID,
null,
this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created.
if (id == CONTACTS_LOADER_ID) {
return contactsLoader();
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
//The framework will take care of closing the
// old cursor once we return.
List<String> contacts = contactsFromCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
}
private Loader<Cursor> contactsLoader() {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts
String[] projection = { // The columns to return for each row
ContactsContract.Contacts.DISPLAY_NAME
} ;
String selection = null; //Selection criteria
String[] selectionArgs = {}; //Selection criteria
String sortOrder = null; //The sort order for the returned rows
return new CursorLoader(
getApplicationContext(),
contactsUri,
projection,
selection,
selectionArgs,
sortOrder);
}
private List<String> contactsFromCursor(Cursor cursor) {
List<String> contacts = new ArrayList<String>();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contacts.add(name);
} while (cursor.moveToNext());
}
return contacts;
}
}
and do not forget
<uses-permission android:name="android.permission.READ_CONTACTS" />
Display help message with python argparse when script is called without any arguments
There are a pair of one-liners with sys.argv[1:]
(a very common Python's idiom to refer the command line arguments, being sys.argv[0]
the script's name) that can do the job.
The first one is self-explanatory, clean and pythonic:
args = parser.parse_args(None if sys.argv[1:] else ['-h'])
The second one is a little hackier. Combining the previously evaluated fact that an empty list is False
with the True == 1
and False == 0
equivalences you get this:
args = parser.parse_args([None, ['-h']][not sys.argv[1:]])
Maybe too many brackets, but pretty clear if a previous argument selection was made.
_, *av = sys.argv
args = parser.parse_args([None, ['-h']][not av])
Count indexes using "for" in Python
The most simple way I would be going for is;
i = -1
for step in my_list:
i += 1
print(i)
#OR - WE CAN CHANGE THE ORDER OF EXECUTION - SEEMS MORE REASONABLE
i = 0
for step in my_list:
print(i) #DO SOMETHING THEN INCREASE "i"
i += 1
Jquery function BEFORE form submission
Just because I made this mistake every time when using the submit function.
This is the full code you need:
Add the id "yourid" to the HTML form tag.
<form id="yourid" action='XXX' name='form' method='POST' accept-charset='UTF-8' enctype='multipart/form-data'>
the jQuery code:
$('#yourid').submit(function() {
// do something
});
Objective-C ARC: strong vs retain and weak vs assign
Strong:
- Property will not Destroy but Only once you set the property to nil will the object get destroyed
- By default all instance variables and local variables are strong pointers.
- You use strong only if you need to retain the object.
- We generally use strong for UIViewControllers (UI item's parents)
- IOS 4 (non-ARC) We Can Use Retain KeyWord
- IOS 5(ARC) We Can Use Strong Keyword
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
Weak
By Default automatically get and set to nil
- We generally use weak for IBOutlets (UIViewController's Childs) and delegate
- the same thing as assign, no retain or release
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
Call a global variable inside module
If You want to have a reference to this variable across the whole project, create somewhere d.ts
file, e.g. globals.d.ts
. Fill it with your global variables declarations, e.g.:
declare const BootBox: 'boot' | 'box';
Now you can reference it anywhere across the project, just like that:
const bootbox = BootBox;
Here's an example.
SQL Server stored procedure creating temp table and inserting value
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
Get index of selected option with jQuery
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
How to bind a List<string> to a DataGridView control?
Try this :
//i have a
List<string> g_list = new List<string>();
//i put manually the values... (for this example)
g_list.Add("aaa");
g_list.Add("bbb");
g_list.Add("ccc");
//for each string add a row in dataGridView and put the l_str value...
foreach (string l_str in g_list)
{
dataGridView1.Rows.Add(l_str);
}
Difference between IISRESET and IIS Stop-Start command
I know this is quite an old post, but I would like to point out the following for people who will read it in the future:
As per MS:
Do not use the IISReset.exe tool to restart the IIS services. Instead,
use the NET STOP and NET START commands. For example, to stop and
start the World Wide Web Publishing Service, run the following
commands:
- NET STOP iisadmin /y
- NET START w3svc
There are two benefits to using the NET STOP/NET START commands to
restart the IIS Services as opposed to using the IISReset.exe tool.
First, it is possible for IIS configuration changes that are in the
process of being saved when the IISReset.exe command is run to be
lost. Second, using IISReset.exe can make it difficult to identify
which dependent service or services failed to stop when this problem
occurs. Using the NET STOP commands to stop each individual dependent
service will allow you to identify which service fails to stop, so you
can then troubleshoot its failure accordingly.
KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result
Find p-value (significance) in scikit-learn LinearRegression
scikit-learn's LinearRegression doesn't calculate this information but you can easily extend the class to do it:
from sklearn import linear_model
from scipy import stats
import numpy as np
class LinearRegression(linear_model.LinearRegression):
"""
LinearRegression class after sklearn's, but calculate t-statistics
and p-values for model coefficients (betas).
Additional attributes available after .fit()
are `t` and `p` which are of the shape (y.shape[1], X.shape[1])
which is (n_features, n_coefs)
This class sets the intercept to 0 by default, since usually we include it
in X.
"""
def __init__(self, *args, **kwargs):
if not "fit_intercept" in kwargs:
kwargs['fit_intercept'] = False
super(LinearRegression, self)\
.__init__(*args, **kwargs)
def fit(self, X, y, n_jobs=1):
self = super(LinearRegression, self).fit(X, y, n_jobs)
sse = np.sum((self.predict(X) - y) ** 2, axis=0) / float(X.shape[0] - X.shape[1])
se = np.array([
np.sqrt(np.diagonal(sse[i] * np.linalg.inv(np.dot(X.T, X))))
for i in range(sse.shape[0])
])
self.t = self.coef_ / se
self.p = 2 * (1 - stats.t.cdf(np.abs(self.t), y.shape[0] - X.shape[1]))
return self
Stolen from here.
You should take a look at statsmodels for this kind of statistical analysis in Python.
What is a mixin, and why are they useful?
I'd advise against mix-ins in new Python code, if you can find any other way around it (such as composition-instead-of-inheritance, or just monkey-patching methods into your own classes) that isn't much more effort.
In old-style classes you could use mix-ins as a way of grabbing a few methods from another class. But in the new-style world everything, even the mix-in, inherits from object
. That means that any use of multiple inheritance naturally introduces MRO issues.
There are ways to make multiple-inheritance MRO work in Python, most notably the super() function, but it means you have to do your whole class hierarchy using super(), and it's considerably more difficult to understand the flow of control.
Can't specify the 'async' modifier on the 'Main' method of a console app
In my case I had a list of jobs that I wanted to run in async from my main method, have been using this in production for quite sometime and works fine.
static void Main(string[] args)
{
Task.Run(async () => { await Task.WhenAll(jobslist.Select(nl => RunMulti(nl))); }).GetAwaiter().GetResult();
}
private static async Task RunMulti(List<string> joblist)
{
await ...
}
How to set an image as a background for Frame in Swing GUI of java?
Here is another quick approach without using additional panel.
JFrame f = new JFrame("stackoverflow") {
private Image backgroundImage = ImageIO.read(new File("background.jpg"));
public void paint( Graphics g ) {
super.paint(g);
g.drawImage(backgroundImage, 0, 0, null);
}
};
Select entries between dates in doctrine 2
EDIT: See the other answers for better solutions
The original newbie approaches that I offered were (opt1):
$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");
And (opt2):
$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");
That was quick and easy and got the original poster going immediately.
Hence the accepted answer.
As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"
Bash Shell Script - Check for a flag and grab its value
Use $#
to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:
if [ $# -ne 2 ]; then
usage;
fi
Next, check if $1
equals -t
, otherwise an unknown flag was used:
if [ "$1" != "-t" ]; then
usage;
fi
Finally store $2
in FLAG
:
FLAG=$2
Note: usage()
is some function showing the syntax. For example:
function usage {
cat << EOF
Usage: script.sh -t <application>
Performs some activity
EOF
exit 1
}