jQuery Scroll to bottom of page/iframe
scrollTop() returns the number of pixels that are hidden from view from the scrollable area, so giving it:
$(document).height()
will actually overshoot the bottom of the page. For the scroll to actually 'stop' at the bottom of the page, the current height of the browser window needs subtracting. This will allow the use of easing if required, so it becomes:
$('html, body').animate({
scrollTop: $(document).height()-$(window).height()},
1400,
"easeOutQuint"
);
How can I update window.location.hash without jumping the document?
This solution worked for me
// store the currently selected tab in the hash value
if(history.pushState) {
window.history.pushState(null, null, '#' + id);
}
else {
window.location.hash = id;
}
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');
And my full js code is
$('#myTab a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href").substr(1);
if(history.pushState) {
window.history.pushState(null, null, '#' + id);
}
else {
window.location.hash = id;
}
// window.location.hash = '#!' + id;
});
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
// console.log(hash);
$('#myTab a[href="' + hash + '"]').tab('show');
How can I scroll to a specific location on the page using jquery?
Yep, even in plain JavaScript it's pretty easy. You give an element an id and then you can use that as a "bookmark":
<div id="here">here</div>
If you want it to scroll there when a user clicks a link, you can just use the tried-and-true method:
<a href="#here">scroll to over there</a>
To do it programmatically, use scrollIntoView()
document.getElementById("here").scrollIntoView()
Trigger event when user scroll to specific element - with jQuery
Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page
var element_position = $('#scroll-to').offset().top;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
UPDATE
I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.
var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}
});
How to remove application from app listings on Android Developer Console
The one exception worth noting is that while you can't delete apps, the folks over at Google Play Developer Support are able to on their end if the app is both unpublished and has 0 lifetime installs. So if your app has 0 lifetime installs, you might be in luck.
First you will need unpublish the app and wait 24 hours (to allow global stats to update and ensure that no last-minute installs happened). Assuming no last-minute installs happen over those 24 hours, you can contact Google Play Developer Support and check to see if they can delete it.
Please note that their requirement for 0 installs is a hard requirement. No exceptions can be made (not even if you installed the app yourself for testing purposes).
MySQL SELECT only not null values
You should use IS NOT NULL
. (The comparison operators =
and <>
both give UNKNOWN
with NULL
on either side of the expression.)
SELECT *
FROM table
WHERE YourColumn IS NOT NULL;
Just for completeness I'll mention that in MySQL you can also negate the null safe equality operator but this is not standard SQL.
SELECT *
FROM table
WHERE NOT (YourColumn <=> NULL);
Edited to reflect comments. It sounds like your table may not be in first normal form in which case changing the structure may make your task easier. A couple of other ways of doing it though...
SELECT val1 AS val
FROM your_table
WHERE val1 IS NOT NULL
UNION ALL
SELECT val2
FROM your_table
WHERE val2 IS NOT NULL
/*And so on for all your columns*/
The disadvantage of the above is that it scans the table multiple times once for each column. That may possibly be avoided by the below but I haven't tested this in MySQL.
SELECT CASE idx
WHEN 1 THEN val1
WHEN 2 THEN val2
END AS val
FROM your_table
/*CROSS JOIN*/
JOIN (SELECT 1 AS idx
UNION ALL
SELECT 2) t
HAVING val IS NOT NULL /*Can reference alias in Having in MySQL*/
What does 'super' do in Python?
Doesn't all of this assume that the base class is a new-style class?
class A:
def __init__(self):
print("A.__init__()")
class B(A):
def __init__(self):
print("B.__init__()")
super(B, self).__init__()
Will not work in Python 2. class A
must be new-style, i.e: class A(object)
Creating a timer in python
import time
mintt=input("How many seconds you want to time?:")
timer=int(mintt)
while (timer != 0 ):
timer=timer-1
time.sleep(1)
print(timer)
This work very good to time seconds.
How can I insert binary file data into a binary SQL field using a simple insert statement?
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.
PostgreSQL JOIN data from 3 tables
Maybe the following is what you are looking for:
SELECT name, pathfilename
FROM table1
NATURAL JOIN table2
NATURAL JOIN table3
WHERE name = 'John';
How to get the number of columns from a JDBC ResultSet?
Number of a columns in the result set you can get with code (as DB is used PostgreSQL):
//load the driver for PostgreSQL
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","mydbuser");
props.setProperty("password","mydbpass");
Connection conn = DriverManager.getConnection(url, props);
//create statement
Statement stat = conn.createStatement();
//obtain a result set
ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");
//from result set give metadata
ResultSetMetaData rsmd = rs.getMetaData();
//columns count from metadata object
int numOfCols = rsmd.getColumnCount();
But you can get more meta-informations about columns:
for(int i = 1; i <= numOfCols; i++)
{
System.out.println(rsmd.getColumnName(i));
}
And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.
Switch in Laravel 5 - Blade
IN LARAVEL 5.2 AND UP:
Write your usual code between the opening and closing PHP statements.
@php
switch (x) {
case 1:
//code to be executed
break;
default:
//code to be executed
}
@endphp
What's the difference between Unicode and UTF-8?
most editors support save as ‘Unicode’ encoding actually.
This is an unfortunate misnaming perpetrated by Windows.
Because Windows uses UTF-16LE encoding internally as the memory storage format for Unicode strings, it considers this to be the natural encoding of Unicode text. In the Windows world, there are ANSI strings (the system codepage on the current machine, subject to total unportability) and there are Unicode strings (stored internally as UTF-16LE).
This was all devised in the early days of Unicode, before we realised that UCS-2 wasn't enough, and before UTF-8 was invented. This is why Windows's support for UTF-8 is all-round poor.
This misguided naming scheme became part of the user interface. A text editor that uses Windows's encoding support to provide a range of encodings will automatically and inappropriately describe UTF-16LE as “Unicode”, and UTF-16BE, if provided, as “Unicode big-endian”.
(Other editors that do encodings themselves, like Notepad++, don't have this problem.)
If it makes you feel any better about it, ‘ANSI’ strings aren't based on any ANSI standard, either.
How to print Unicode character in C++?
To represent the character you can use Universal Character Names (UCNs). The character '?' has the Unicode value U+0444 and so in C++ you could write it '\u0444' or '\U00000444'. Also if the source code encoding supports this character then you can just write it literally in your source code.
// both of these assume that the character can be represented with
// a single char in the execution encoding
char b = '\u0444';
char a = '?'; // this line additionally assumes that the source character encoding supports this character
Printing such characters out depends on what you're printing to. If you're printing to a Unix terminal emulator, the terminal emulator is using an encoding that supports this character, and that encoding matches the compiler's execution encoding, then you can do the following:
#include <iostream>
int main() {
std::cout << "Hello, ? or \u0444!\n";
}
This program does not require that '?' can be represented in a single char. On OS X and most any modern Linux install this will work just fine, because the source, execution, and console encodings will all be UTF-8 (which supports all Unicode characters).
Things are harder with Windows and there are different possibilities with different tradeoffs.
Probably the best, if you don't need portable code (you'll be using wchar_t, which should really be avoided on every other platform), is to set the mode of the output file handle to take only UTF-16 data.
#include <iostream>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L"Hello, \u0444!\n";
}
Portable code is more difficult.
A simple explanation of Naive Bayes Classification
Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv
and paste the following content.
Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no
Here is the code the comments explains everything we are doing here! [python]
import pandas as pd
import pprint
class Classifier():
data = None
class_attr = None
priori = {}
cp = {}
hypothesis = None
def __init__(self,filename=None, class_attr=None ):
self.data = pd.read_csv(filename, sep=',', header =(0))
self.class_attr = class_attr
'''
probability(class) = How many times it appears in cloumn
__________________________________________
count of all class attribute
'''
def calculate_priori(self):
class_values = list(set(self.data[self.class_attr]))
class_data = list(self.data[self.class_attr])
for i in class_values:
self.priori[i] = class_data.count(i)/float(len(class_data))
print "Priori Values: ", self.priori
'''
Here we calculate the individual probabilites
P(outcome|evidence) = P(Likelihood of Evidence) x Prior prob of outcome
___________________________________________
P(Evidence)
'''
def get_cp(self, attr, attr_type, class_value):
data_attr = list(self.data[attr])
class_data = list(self.data[self.class_attr])
total =1
for i in range(0, len(data_attr)):
if class_data[i] == class_value and data_attr[i] == attr_type:
total+=1
return total/float(class_data.count(class_value))
'''
Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
(Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
scaled by P(Multiple Evidence)
'''
def calculate_conditional_probabilities(self, hypothesis):
for i in self.priori:
self.cp[i] = {}
for j in hypothesis:
self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
print "\nCalculated Conditional Probabilities: \n"
pprint.pprint(self.cp)
def classify(self):
print "Result: "
for i in self.cp:
print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]
if __name__ == "__main__":
c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
c.calculate_priori()
c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
c.calculate_conditional_probabilities(c.hypothesis)
c.classify()
output:
Priori Values: {'yes': 0.6428571428571429, 'no': 0.35714285714285715}
Calculated Conditional Probabilities:
{
'no': {
'<=30': 0.8,
'fair': 0.6,
'medium': 0.6,
'yes': 0.4
},
'yes': {
'<=30': 0.3333333333333333,
'fair': 0.7777777777777778,
'medium': 0.5555555555555556,
'yes': 0.7777777777777778
}
}
Result:
yes ==> 0.0720164609053
no ==> 0.0411428571429
Hope it helps in better understanding the problem
peace
What is bootstrapping?
Alex, it's pretty much what your computer does when it boots up. ('Booting' a computer actually comes from the word bootstrapping)
Initially, the small program in your BIOS runs. That contains enough machine code to load and run a larger, more complex program.
That second program is probably something like NTLDR (in Windows) or LILO (in Linux), which then executes and is able to load, then run, the rest of the operating system.
Android Saving created bitmap to directory on sd card
Hi You can write data to bytes and then create a file in sdcard folder with whatever name and extension you want and then write the bytes to that file.
This will save bitmap to sdcard.
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
Call Jquery function
calling a function is simple ..
myFunction();
so your code will be something like..
$(function(){
$('#elementID').click(function(){
myFuntion(); //this will call your function
});
});
$(function(){
$('#elementID').click( myFuntion );
});
or with some condition
if(something){
myFunction(); //this will call your function
}
How to define the css :hover state in a jQuery selector?
It's too late, however the best example, how to add pseudo element in jQuery style
_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});_x000D_
$("a.dummy").hover(function() {_x000D_
$(this).css("background-color","#0670c9")_x000D_
}).mouseout(function(){_x000D_
$(this).css({"background-color":"#003d79",});_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>_x000D_
<a class="dummy" href="javascript:void()">Just Link</a>
_x000D_
_x000D_
_x000D_
Mocking a method to throw an exception (moq), but otherwise act like the mocked object?
Here's how you can mock your FileConnection
Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
.Throws(new IOException());
Then instantiate your Transfer class and use the mock in your method call
Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
Update:
First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.
Since you are setting those properties using another dependency, I would write it like this:
public class Transfer
{
public Transfer(IInternalConfig internalConfig)
{
source = internalConfig.GetFileConnection("source");
destination = internalConfig.GetFileConnection("destination");
}
//you should consider making these private or protected fields
public virtual IFileConnection source { get; set; }
public virtual IFileConnection destination { get; set; }
public virtual void GetFile(IFileConnection connection,
string remoteFilename, string localFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void PutFile(IFileConnection connection,
string localFilename, string remoteFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void TransferFiles(string sourceName, string destName)
{
var tempName = Path.GetTempFileName();
GetFile(source, sourceName, tempName);
PutFile(destination, tempName, destName);
}
}
This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.
How to do a join in linq to sql with method syntax?
Justin has correctly shown the expansion in the case where the join is just followed by a select
. If you've got something else, it becomes more tricky due to transparent identifiers - the mechanism the C# compiler uses to propagate the scope of both halves of the join.
So to change Justin's example slightly:
var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
where sc.X + sc.Y == 10
select new { SomeClass = sc, SomeOtherClass = soc }
would be converted into something like this:
var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new { sc, soc })
.Where(z => z.sc.X + z.sc.Y == 10)
.Select(z => new { SomeClass = z.sc, SomeOtherClass = z.soc });
The z
here is the transparent identifier - but because it's transparent, you can't see it in the original query :)
Download file using libcurl in C/C++
The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.
This is more or less what it should look like (no libcurl available here to test)
#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://localhost/aaa.txt";
char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”
I was getting below error on playback
finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://remote-abcabc-svc.an.abc.com:1935/abr/_definst_/smil:v2/video/492F2F82592F59EA74ABAA6B9D6E6F42/F6B1BD452132329FBACD32730862CAE0/091EAD80FE9BEDD52A2F33840CA3CBAC.v3.eng.smil/playlist.m3u8, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <692A1174-DA1C-4267-9560-9020A79F8458>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <692A1174-DA1C-4267-9560-9020A79F8458>
I made sure that I added entry in exception domains in plist file and NSAllowsArbitraryLoads is set to true and still I was seeing an error.
Then I realized that I am playing URL with https and not http.
I set video url to http and problem solved.
SQL server stored procedure return a table
I had a similar situation and solved by using a temp table inside the procedure, with the same fields being returned by the original Stored Procedure:
CREATE PROCEDURE mynewstoredprocedure
AS
BEGIN
INSERT INTO temptable (field1, field2)
EXEC mystoredprocedure @param1, @param2
select field1, field2 from temptable
-- (mystoredprocedure returns field1, field2)
END
Enum "Inheritance"
Enums are not actual classes, even if they look like it. Internally, they are treated just like their underlying type (by default Int32). Therefore, you can only do this by "copying" single values from one enum to another and casting them to their integer number to compare them for equality.
Routing HTTP Error 404.0 0x80070002
The solution suggested
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.
A more sensible solution is to include this in your web.config:
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>
Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.
What is the MySQL VARCHAR max size?
you can also use MEDIUMBLOB/LONGBLOB or MEDIUMTEXT/LONGTEXT
A BLOB type in MySQL can store up to 65,534 bytes, if you try to store more than this much data MySQL will truncate the data. MEDIUMBLOB can store up to 16,777,213 bytes, and LONGBLOB can store up to 4,294,967,292 bytes.
How to save a Seaborn plot into a file
Fewer lines for 2019 searchers:
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
plt.savefig('output.png')
UPDATE NOTE: size
was changed to height
.
How can I install a .ipa file to my iPhone simulator
Update for Xcode 9.4.1+
Hope my answer is getting seen down here as this took me a while to figure out but I just got it working.
First of all you need to build and run the App on your simulator. Then you open the Activity Monitor. Double click the name of your App to find its content.
In the next screen open the Open Files and Ports tab and find the line with MyAppName.app/MyAppName.
Copy the link but make sure to stop at the MyAppName.app. Do not copy the path following it.
Control click onto the finder icon and select Go to folder.
]
Paste the path and click enter. You will see your MyAppName.app file.
Copy it to the Desktop and zip it. Move it to your desired 2nd computer and unzip the file. Build a random project to have a simulator open.
Lastly: Literally drag and drop the App from your Desktop into your Simulator. You will see the install and the App opens and does not crash.
Getting Integer value from a String using javascript/jquery
For parseInt to work, your string should have only numerical data. Something like this:
str1 = "123.00";
str2 = "50.00";
total = parseInt(str1)+parseInt(str2);
alert(total);
Can you split the string before you start processing them for a total?
How can I pair socks from a pile efficiently?
What about doing some preprocessing? I would stitch a mark or id number in every sock in a way that every pair has the same mark/id number. This process might be done every time you buy a new pair of socks. Then, you could do a radix sort to get O(n) total cost. Find a place for every mark/id number and just pick all the socks one by one and put them into the correct place.
Video file formats supported in iPhone
Short answer: H.264 MPEG (MP4)
Long answer from Apple.com:
Video formats supported: H.264 video,
up to 1.5 Mbps, 640 by 480 pixels, 30
frames per second,
Low-Complexity
version of the H.264 Baseline Profile
with AAC-LC audio up to 160 Kbps,
48kHz, stereo audio in .m4v, .mp4, and
.mov file formats; H.264 video, up to
2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Baseline Profile up to
Level 3.0 with AAC-LC audio up to 160
Kbps, 48kHz, stereo audio in .m4v,
.mp4, and .mov file formats; MPEG-4
video, up to 2.5 Mbps, 640 by 480
pixels, 30 frames per second,
Simple
Profile with AAC-LC audio up to 160
Kbps, 48kHz, stereo audio in .m4v,
.mp4, and .mov file formats
http://www.apple.com/iphone/specs.html
kubectl apply vs kubectl create?
Those are two different approaches:
Imperative Management
kubectl create
is what we call Imperative Management. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like.
Declarative Management
kubectl apply
is part of the Declarative Management approach, where changes that you may have applied to a live object (i.e. through scale
) are "maintained" even if you apply
other changes to the object.
You can read more about imperative and declarative management in the Kubernetes Object Management documentation.
How does database indexing work?
Just a quick suggestion.. As indexing costs you additional writes and storage space, so if your application requires more insert/update operation, you might want to use tables without indexes, but if it requires more data retrieval operations, you should go for indexed table.
Insert PHP code In WordPress Page and Post
When I was trying to accomplish something very similar, I ended up doing something along these lines:
wp-content/themes/resources/functions.php
add_action('init', 'my_php_function');
function my_php_function() {
if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
// add desired php code here
}
}
Share variables between files in Node.js?
I'm unable to find an scenario where a global var
is the best option, of course you can have one, but take a look at these examples and you may find a better way to accomplish the same:
Scenario 1: Put the stuff in config files
You need some value that it's the same across the application, but it changes depending on the environment (production, dev or test), the mailer type as example, you'd need:
// File: config/environments/production.json
{
"mailerType": "SMTP",
"mailerConfig": {
"service": "Gmail",
....
}
and
// File: config/environments/test.json
{
"mailerType": "Stub",
"mailerConfig": {
"error": false
}
}
(make a similar config for dev too)
To decide which config will be loaded make a main config file (this will be used all over the application)
// File: config/config.js
var _ = require('underscore');
module.exports = _.extend(
require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});
And now you can get the data like this:
// File: server.js
...
var config = require('./config/config');
...
mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));
Scenario 2: Use a constants file
// File: constants.js
module.exports = {
appName: 'My neat app',
currentAPIVersion: 3
};
And use it this way
// File: config/routes.js
var constants = require('../constants');
module.exports = function(app, passport, auth) {
var apiroot = '/api/v' + constants.currentAPIVersion;
...
app.post(apiroot + '/users', users.create);
...
Scenario 3: Use a helper function to get/set the data
Not a big fan of this one, but at least you can track the use of the 'name' (citing the OP's example) and put validations in place.
// File: helpers/nameHelper.js
var _name = 'I shall not be null'
exports.getName = function() {
return _name;
};
exports.setName = function(name) {
//validate the name...
_name = name;
};
And use it
// File: controllers/users.js
var nameHelper = require('../helpers/nameHelper.js');
exports.create = function(req, res, next) {
var user = new User();
user.name = req.body.name || nameHelper.getName();
...
There could be a use case when there is no other solution than having a global var
, but usually you can share the data in your app using one of these scenarios, if you are starting to use node.js (as I was sometime ago) try to organize the way you handle the data over there because it can get messy really quick.
How to iterate over a string in C?
sizeof(source)
returns the number of bytes required by the pointer char*
. You should replace it with strlen(source)
which will be the length of the string you're trying to display.
Also, you should probably replace printf("%s",source[i])
with printf("%c",source[i])
since you're displaying a character.
Why is it not advisable to have the database and web server on the same machine?
On the other hand, referring to a different blogging Scott (Watermasyck, of Telligent) - they found that most users could speed up the websites (using Telligent's Community Server), by putting the database on the same machine as the web site. However, in their customer's case, usually the db & web server are the only applications on that machine, and the website isn't straining the machine that much. Then, the efficiency of not having to send data across the network more that made up for the increased strain.
How to create module-wide variables in Python?
For this, you need to declare the variable as global. However, a global variable is also accessible from outside the module by using module_name.var_name
. Add this as the first line of your module:
global __DBNAME__
Quick way to create a list of values in C#?
You can do that with
var list = new List<string>{ "foo", "bar" };
Here are some other common instantiations of other common Data Structures:
Dictionary
var dictionary = new Dictionary<string, string>
{
{ "texas", "TX" },
{ "utah", "UT" },
{ "florida", "FL" }
};
Array list
var array = new string[] { "foo", "bar" };
Queue
var queque = new Queue<int>(new[] { 1, 2, 3 });
Stack
var queque = new Stack<int>(new[] { 1, 2, 3 });
As you can see for the majority of cases it is merely adding the values in curly braces, or instantiating a new array followed by curly braces and values.
R: invalid multibyte string
This happened to me because I had the 'copyright' symbol in one of my strings! Once it was removed, problem solved.
A good rule of thumb, make sure that characters not appearing on your keyboard are removed if you are seeing this error.
What is C# analog of C++ std::pair?
Tuples are available since .NET4.0 and support generics:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
In previous versions you can use System.Collections.Generic.KeyValuePair<K, V>
or a solution like the following:
public class Pair<T, U> {
public Pair() {
}
public Pair(T first, U second) {
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
};
And use it like this:
Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);
This outputs:
test
2
Or even this chained pairs:
Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;
Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);
That outputs:
test
12
true
About the Full Screen And No Titlebar from manifest
If your Manifest.xml
has the default android:theme="@style/AppTheme"
Go to res/values/styles.xml and change
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
And the ActionBar
is disappeared!
How to save S3 object to a file using boto3
boto3 now has a nicer interface than the client:
resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)
This by itself isn't tremendously better than the client
in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.
Resources
generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.
Google Text-To-Speech API
Go to console.developer.google.com
login and get an API key
or use microsoft bing's API
https://msdn.microsoft.com/en-us/library/?f=255&MSPPError=-2147217396
or even better use AT&T's speech API developer.att.com
(paid one)
For voice recognition
Public Class Voice_recognition
Public Function convertTotext(ByVal path As String, ByVal output As String) As String
Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://www.google.com/speech-api/v1/recognize?xjerr=1&client=speech2text&lang=en-US&maxresults=10"), HttpWebRequest)
'path = Application.StartupPath & "curinputtmp.mp3"
request.Timeout = 60000
request.Method = "POST"
request.KeepAlive = True
request.ContentType = "audio/x-flac; rate=8000"
request.UserAgent = "speech2text"
Dim fInfo As New FileInfo(path)
Dim numBytes As Long = fInfo.Length
Dim data As Byte()
Using fStream As New FileStream(path, FileMode.Open, FileAccess.Read)
data = New Byte(CInt(fStream.Length - 1)) {}
fStream.Read(data, 0, CInt(fStream.Length))
fStream.Close()
End Using
Using wrStream As Stream = request.GetRequestStream()
wrStream.Write(data, 0, data.Length)
End Using
Try
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim resp = response.GetResponseStream()
If resp IsNot Nothing Then
Dim sr As New StreamReader(resp)
MessageBox.Show(sr.ReadToEnd())
resp.Close()
resp.Dispose()
End If
Catch ex As System.Exception
MessageBox.Show(ex.Message)
End Try
Return 0
End Function
End Class
And for text to speech: use this.
I think you'll understand this
if didn't then use vbscript to vb/C# converter.
still didn't then contact Me.
I have done this before ,can't find the code now that this why i'm not directly givin' you the code.
R - Markdown avoiding package loading messages
This is an old question, but here's another way to do it.
You can modify the R code itself instead of the chunk options, by wrapping the source
call in suppressPackageStartupMessages()
, suppressMessages()
, and/or suppressWarnings()
. E.g:
```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```
You can also put those functions around your library()
calls inside the "source.R"
script.
What is dtype('O'), in pandas?
When you see dtype('O')
inside dataframe this means Pandas string.
What is dtype
?
Something that belongs to pandas
or numpy
, or both, or something else? If we examine pandas code:
df = pd.DataFrame({'float': [1.0],
'int': [1],
'datetime': [pd.Timestamp('20180310')],
'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype
It will output like this:
float int datetime string
0 1.0 1 2018-03-10 foo
---
float64 int64 datetime64[ns] object
---
dtype('O')
You can interpret the last as Pandas dtype('O')
or Pandas object which is Python type string, and this corresponds to Numpy string_
, or unicode_
types.
Pandas dtype Python type NumPy type Usage
object str string_, unicode_ Text
Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype
for that.
Data type object is an instance of numpy.dtype
class that understand the data type more precise including:
- Type of the data (integer, float, Python object, etc.)
- Size of the data (how many bytes is in e.g. the integer)
- Byte order of the data (little-endian or big-endian)
- If the data type is structured, an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float)
- What are the names of the "fields" of the structure
- What is the data-type of each field
- Which part of the memory block each field takes
- If the data type is a sub-array, what is its shape and data type
In the context of this question dtype
belongs to both pands and numpy and in particular dtype('O')
means we expect the string.
Here is some code for testing with explanation:
If we have the dataset as dictionary
import pandas as pd
import numpy as np
from pandas import Timestamp
data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe
print(df)
print(df.dtypes)
The last lines will examine the dataframe and note the output:
id date role num fnum
0 1 2018-12-12 Support 123 3.14
1 2 2018-12-12 Marketing 234 2.14
2 3 2018-12-12 Business Development 345 -0.14
3 4 2018-12-12 Sales 456 41.30
4 5 2018-12-12 Engineering 567 3.14
id int64
date datetime64[ns]
role object
num int64
fnum float64
dtype: object
All kind of different dtypes
df.iloc[1,:] = np.nan
df.iloc[2,:] = None
But if we try to set np.nan
or None
this will not affect the original column dtype. The output will be like this:
print(df)
print(df.dtypes)
id date role num fnum
0 1.0 2018-12-12 Support 123.0 3.14
1 NaN NaT NaN NaN NaN
2 NaN NaT None NaN NaN
3 4.0 2018-12-12 Sales 456.0 41.30
4 5.0 2018-12-12 Engineering 567.0 3.14
id float64
date datetime64[ns]
role object
num float64
fnum float64
dtype: object
So np.nan
or None
will not change the columns dtype
, unless we set the all column rows to np.nan
or None
. In that case column will become float64
or object
respectively.
You may try also setting single rows:
df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object
And to note here, if we set string inside a non string column it will become string or object dtype
.
Execute JavaScript using Selenium WebDriver in C#
public void javascriptclick(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();",webElement);
System.out.println("javascriptclick"+" "+ element);
}
throwing exceptions out of a destructor
Throwing out of a destructor can result in a crash, because this destructor might be called as part of "Stack unwinding".
Stack unwinding is a procedure which takes place when an exception is thrown.
In this procedure, all the objects that were pushed into the stack since the "try" and until the exception was thrown, will be terminated -> their destructors will be called.
And during this procedure, another exception throw is not allowed, because it's not possible to handle two exceptions at a time, thus, this will provoke a call to abort(), the program will crash and the control will return to the OS.
How to remove focus without setting focus to another control?
Try the following (calling clearAllEditTextFocuses();
)
private final boolean clearAllEditTextFocuses() {
View v = getCurrentFocus();
if(v instanceof EditText) {
final FocusedEditTextItems list = new FocusedEditTextItems();
list.addAndClearFocus((EditText) v);
//Focus von allen EditTexten entfernen
boolean repeat = true;
do {
v = getCurrentFocus();
if(v instanceof EditText) {
if(list.containsView(v))
repeat = false;
else list.addAndClearFocus((EditText) v);
} else repeat = false;
} while(repeat);
final boolean result = !(v instanceof EditText);
//Focus wieder setzen
list.reset();
return result;
} else return false;
}
private final static class FocusedEditTextItem {
private final boolean focusable;
private final boolean focusableInTouchMode;
@NonNull
private final EditText editText;
private FocusedEditTextItem(final @NonNull EditText v) {
editText = v;
focusable = v.isFocusable();
focusableInTouchMode = v.isFocusableInTouchMode();
}
private final void clearFocus() {
if(focusable)
editText.setFocusable(false);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(false);
editText.clearFocus();
}
private final void reset() {
if(focusable)
editText.setFocusable(true);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(true);
}
}
private final static class FocusedEditTextItems extends ArrayList<FocusedEditTextItem> {
private final void addAndClearFocus(final @NonNull EditText v) {
final FocusedEditTextItem item = new FocusedEditTextItem(v);
add(item);
item.clearFocus();
}
private final boolean containsView(final @NonNull View v) {
boolean result = false;
for(FocusedEditTextItem item: this) {
if(item.editText == v) {
result = true;
break;
}
}
return result;
}
private final void reset() {
for(FocusedEditTextItem item: this)
item.reset();
}
}
Codeigniter LIKE with wildcard(%)
$this->db->like('title', 'match', 'before');
// Produces: WHERE title LIKE '%match'
$this->db->like('title', 'match', 'after');
// Produces: WHERE title LIKE 'match%'
$this->db->like('title', 'match', 'both');
// Produces: WHERE title LIKE '%match%'
Creating temporary files in bash
Is there any advantage in creating a temporary file in a more careful way
The temporary files are usually created in the temporary directory (such as /tmp
) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask
) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).
You could use the following approach to create the temporary directory:
TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"
or temporary file:
TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"
However it is still predictable and not considered safe.
As per man mktemp
, we can read:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.
So to be safe, it is recommended to use mktemp
command to create unique temporary file or directory (-d
).
Are PDO prepared statements sufficient to prevent SQL injection?
No this is not enough (in some specific cases)! By default PDO uses emulated prepared statements when using MySQL as a database driver. You should always disable emulated prepared statements when using MySQL and PDO:
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Another thing that always should be done it set the correct encoding of the database:
$dbh = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
Also see this related question: How can I prevent SQL injection in PHP?
Also note that that only is about the database side of the things you would still have to watch yourself when displaying the data. E.g. by using htmlspecialchars()
again with the correct encoding and quoting style.
Is background-color:none valid CSS?
So, I would like to explain the scenario where I had to make use of this solution. Basically, I wanted to undo the background-color attribute set by another CSS. The expected end result was to make it look as though the original CSS had never applied the background-color attribute . Setting background-color:transparent;
made that effective.
How to run Java program in command prompt
javac only compiles the code. You need to use java command to run the code. The error is because your classpath doesn't contain the class Subclass iwhen you tried to compile it. you need to add them with the -cp variable in javac command
java -cp classpath-entries mainjava arg1 arg2
should run your code with 2 arguments
Notice: Undefined offset: 0 in
Use print_r($votes);
to inspect the array $votes
, you will see that key 0
does not exist there. It will return NULL and throw that error.
Hibernate show real SQL
select this_.code from true.employee this_ where this_.code=?
is what will be sent to your database.
this_
is an alias for that instance of the employee
table.
Call angularjs function using jquery/javascript
Another way is to create functions in global scope. This was necessary for me since it wasn't possible in Angular 1.5 to reach a component's scope.
Example:
_x000D_
_x000D_
angular.module("app", []).component("component", {_x000D_
controller: ["$window", function($window) {_x000D_
var self = this;_x000D_
_x000D_
self.logg = function() {_x000D_
console.log("logging!");_x000D_
};_x000D_
_x000D_
$window.angularControllerLogg = self.logg;_x000D_
}_x000D_
});_x000D_
_x000D_
window.angularControllerLogg();
_x000D_
_x000D_
_x000D_
Importing class/java files in Eclipse
create a new java project in Eclipse and copy .java files to its src directory, if you don't know where those source files should be placed, right click on the root of the project and choose new->class to create a test class and see where its .java file is placed, then put other files with it, in the same directory, you may have to adjust the package in those source files according to the new project directory structure.
if you use external libraries in your code, you have two options: either copy / download jar files or use maven if you use maven you'll have to create the project at maven project in the first place, creating java projects as maven projects are the way to go anyway but that's for another post...
How to get file creation & modification date/times in Python?
os.stat
returns a named tuple with st_mtime
and st_ctime
attributes. The modification time is st_mtime
on both platforms; unfortunately, on Windows, ctime
means "creation time", whereas on POSIX it means "change time". I'm not aware of any way to get the creation time on POSIX platforms.
Triggering change detection manually in Angular
I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:
Import NgZone
:
import { Component, NgZone } from '@angular/core';
Add it to your class constructor
constructor(public zone: NgZone, ...args){}
Run code with zone.run
:
this.zone.run(() => this.donations = donations)
OpenMP set_num_threads() is not working
According to the GCC manual for omp_get_num_threads:
In a sequential section of the program omp_get_num_threads returns 1
So this:
cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;
Should be changed to something like:
#pragma omp parallel
{
cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;
}
The code I use follows Hristo's advice of disabling dynamic teams, too.
How to set selected item of Spinner by value, not by position?
Since I needed something, that also works with Localization, I came up with these two methods:
private int getArrayPositionForValue(final int arrayResId, final String value) {
final Resources english = Utils.getLocalizedResources(this, new Locale("en"));
final List<String> arrayValues = Arrays.asList(english.getStringArray(arrayResId));
for (int position = 0; position < arrayValues.size(); position++) {
if (arrayValues.get(position).equalsIgnoreCase(value)) {
return position;
}
}
Log.w(TAG, "getArrayPosition() --> return 0 (fallback); No index found for value = " + value);
return 0;
}
As you can see, I also stumbled over additional complexity of case sensitivity between arrays.xml and the value
I am comparing against.
If you don't have this, the above method can be simplified to something like:
return arrayValues.indexOf(value);
Static helper method
public static Resources getLocalizedResources(Context context, Locale desiredLocale) {
Configuration conf = context.getResources().getConfiguration();
conf = new Configuration(conf);
conf.setLocale(desiredLocale);
Context localizedContext = context.createConfigurationContext(conf);
return localizedContext.getResources();
}
Horizontal scroll css?
Just set your width to auto:
#myWorkContent{
width: auto;
height:210px;
border: 13px solid #bed5cd;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
This way your div can be as wide as possible, so you can add as many kitty images as possible ;3
Your div's width will expand based on the child elements it contains.
jsFiddle
How can I run an external command asynchronously from Python?
I have the same problem trying to connect to an 3270 terminal using the s3270 scripting software in Python. Now I'm solving the problem with an subclass of Process that I found here:
http://code.activestate.com/recipes/440554/
And here is the sample taken from file:
def recv_some(p, t=.1, e=1, tr=5, stderr=0):
if tr < 1:
tr = 1
x = time.time()+t
y = []
r = ''
pr = p.recv
if stderr:
pr = p.recv_err
while time.time() < x or r:
r = pr()
if r is None:
if e:
raise Exception(message)
else:
break
elif r:
y.append(r)
else:
time.sleep(max((x-time.time())/tr, 0))
return ''.join(y)
def send_all(p, data):
while len(data):
sent = p.send(data)
if sent is None:
raise Exception(message)
data = buffer(data, sent)
if __name__ == '__main__':
if sys.platform == 'win32':
shell, commands, tail = ('cmd', ('dir /w', 'echo HELLO WORLD'), '\r\n')
else:
shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), '\n')
a = Popen(shell, stdin=PIPE, stdout=PIPE)
print recv_some(a),
for cmd in commands:
send_all(a, cmd + tail)
print recv_some(a),
send_all(a, 'exit' + tail)
print recv_some(a, e=0)
a.wait()
PHP calculate age
Following the first logic, you have to use = in the comparison.
<?php
function age($birthdate) {
$birthdate = strtotime($birthdate);
$now = time();
$age = 0;
while ($now >= ($birthdate = strtotime("+1 YEAR", $birthdate))) {
$age++;
}
return $age;
}
// Usage:
echo age(implode("-",array_reverse(explode("/",'14/09/1986')))); // format yyyy-mm-dd is safe!
echo age("-10 YEARS") // without = in the comparison, will returns 9.
?>
Most efficient way to increment a Map value in Java
I think your solution would be the standard way, but - as you noted yourself - it is probably not the fastest way possible.
You may look at GNU Trove. That is a library which contains all sorts of fast primitive Collections. Your example would use a TObjectIntHashMap which has a method adjustOrPutValue which does exactly what you want.
The APR based Apache Tomcat Native library was not found on the java.library.path
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
Get filename from input [type='file'] using jQuery
This was a very important issue for me in order for my site to be multilingual. So here is my conclusion tested in Firefox and Chrome.
jQuery trigger comes in handy.
So this hides the standard boring type=file
labels. You can place any label you want and format anyway. I customized a script from http://demo.smarttutorials.net/ajax1/. The script allows multiple file uploads with thumbnail preview and uses PHP and MySQL.
<form enctype="multipart/form-data" name='imageform' role="form" ="imageform" method="post" action="upload_ajax.php">
<div class="form-group">
<div id="select_file">Select a file</div>
<input class='file' type="file" style="display: none " class="form-control" name="images_up" id="images_up" placeholder="Please choose your image">
<div id="my_file"></div>
<span class="help-block"></span>
</div>
<div id="loader" style="display: none;">
Please wait image uploading to server....
</div>
<input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>
$('#select_file').click(function() {
$('#images_up').trigger('click');
$('#images_up').change(function() {
var filename = $('#images_up').val();
if (filename.substring(3,11) == 'fakepath') {
filename = filename.substring(12);
} // Remove c:\fake at beginning from localhost chrome
$('#my_file').html(filename);
});
});
Default SecurityProtocol in .NET 4.5
Following code will:
- print enabled protocols
- print available protocols
- enable TLS1.2 if platform supports it and if it is not enabled to begin with
- disable SSL3 if it is enabled
- print end result
Constants:
- 48 is SSL3
- 192 is TLS1
- 768 is TLS1.1
- 3072 is TLS1.2
Other protocols will not be affected. This makes this compatible with future protocols (Tls1.3, etc).
Code
// print initial status
Console.WriteLine("Runtime: " + System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(int).Assembly.Location).ProductVersion);
Console.WriteLine("Enabled protocols: " + ServicePointManager.SecurityProtocol);
Console.WriteLine("Available protocols: ");
Boolean platformSupportsTls12 = false;
foreach (SecurityProtocolType protocol in Enum.GetValues(typeof(SecurityProtocolType))) {
Console.WriteLine(protocol.GetHashCode());
if (protocol.GetHashCode() == 3072){
platformSupportsTls12 = true;
}
}
Console.WriteLine("Is Tls12 enabled: " + ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072));
// enable Tls12, if possible
if (!ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072)){
if (platformSupportsTls12){
Console.WriteLine("Platform supports Tls12, but it is not enabled. Enabling it now.");
ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
} else {
Console.WriteLine("Platform does not supports Tls12.");
}
}
// disable ssl3
if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Ssl3)) {
Console.WriteLine("Ssl3SSL3 is enabled. Disabling it now.");
// disable SSL3. Has no negative impact if SSL3 is already disabled. The enclosing "if" if just for illustration.
System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
}
Console.WriteLine("Enabled protocols: " + ServicePointManager.SecurityProtocol);
Output
Runtime: 4.7.2114.0
Enabled protocols: Ssl3, Tls
Available protocols:
0
48
192
768
3072
Is Tls12 enabled: False
Platform supports Tls12, but it is not enabled. Enabling it now.
Ssl3 is enabled. Disabling it now.
Enabled protocols: Tls, Tls12
Excel Formula which places date/time in cell when data is entered in another cell in the same row
This can be accomplished with a simple VBA function. Excel has support for a Worksheet Change Sub which can be programmed to put a date in a related column every time it fires.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
End If
End Sub
A quick explanation. The following "if" statement checks for two things: (1) if it is the second column that changed (Column B), and (2) if the cell 3 columns over (Column E) is currently empty.
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
If both conditions are true, then it puts the date into the cell in Column E with the NOW()
function.
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
Range.Offset
Range.Column
Javascript sleep/delay/wait function
You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.
function exportar(page,miliseconds,totalpages)
{
if (page <= totalpages)
{
nextpage = page + 1;
console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
fnExcelReport(page);
setTimeout(function(){
exportar(nextpage,miliseconds,totalpages);
},miliseconds);
};
}
Make a link open a new window (not tab)
Browsers control a lot of this functionality but
<a href="http://www.yahoo.com" target="_blank">Go to Yahoo</a>
will attempt to open yahoo.com in a new window.
Bind service to activity in Android
There is a method called unbindService that will take a ServiceConnection which you will have created upon calling bindService. This will allow you to disconnect from the service while still leaving it running.
This may pose a problem when you connect to it again, since you probably don't know whether it's running or not when you start the activity again, so you'll have to consider that in your activity code.
Good luck!
How to change the background color of the options menu?
One thing to note that you guys are over-complicating the problem just like a lot of other posts! All you need to do is create drawable selectors with whatever backgrounds you need and set them to actual items. I just spend two hours trying your solutions (all suggested on this page) and none of them worked. Not to mention that there are tons of errors that essentially slow your performance in those try/catch blocks you have.
Anyways here is a menu xml file:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/m1"
android:icon="@drawable/item1_selector"
/>
<item android:id="@+id/m2"
android:icon="@drawable/item2_selector"
/>
</menu>
Now in your item1_selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/item_highlighted" />
<item android:state_selected="true" android:drawable="@drawable/item_highlighted" />
<item android:state_focused="true" android:drawable="@drawable/item_nonhighlighted" />
<item android:drawable="@drawable/item_nonhighlighted" />
</selector>
Next time you decide to go to the supermarket through Canada try google maps!
How to check if the request is an AJAX request with PHP
Set a session variable for every page on your site (actual pages not includes or rpcs) that contains the current page name, then in your Ajax call pass a nonce salted with the $_SERVER['SCRIPT_NAME'];
<?php
function create_nonce($optional_salt='')
{
return hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']);
}
$_SESSION['current_page'] = $_SERVER['SCRIPT_NAME'];
?>
<form>
<input name="formNonce" id="formNonce" type="hidden" value="<?=create_nonce($_SERVER['SCRIPT_NAME']);?>">
<label class="form-group">
Login<br />
<input name="userName" id="userName" type="text" />
</label>
<label class="form-group">
Password<br />
<input name="userPassword" id="userPassword" type="password" />
</label>
<button type="button" class="btnLogin">Sign in</button>
</form>
<script type="text/javascript">
$("form.login button").on("click", function() {
authorize($("#userName").val(),$("#userPassword").val(),$("#formNonce").val());
});
function authorize (authUser, authPassword, authNonce) {
$.ajax({
type: "POST",
url: "/inc/rpc.php",
dataType: "json",
data: "userID="+authUser+"&password="+authPassword+"&nonce="+authNonce
})
.success(function( msg ) {
//some successful stuff
});
}
</script>
Then in the rpc you are calling test the nonce you passed, if it is good then odds are pretty great that your rpc was legitimately called:
<?php
function check_nonce($nonce, $optional_salt='')
{
$lasthour = date("G")-1<0 ? date('Ymd').'23' : date("YmdG")-1;
if (hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce ||
hash_hmac('sha256', session_id().$optional_salt, $lasthour.'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce)
{
return true;
} else {
return false;
}
}
$ret = array();
header('Content-Type: application/json');
if (check_nonce($_POST['nonce'], $_SESSION['current_page']))
{
$ret['nonce_check'] = 'passed';
} else {
$ret['nonce_check'] = 'failed';
}
echo json_encode($ret);
exit;
?>
edit: FYI the way I have it set the nonce is only good for an hour and change, so if they have not refreshed the page doing the ajax call in the last hour or 2 the ajax request will fail.
Get full path without filename from path that includes filename
Path.GetDirectoryName()
... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).
You could validate first by testing File.Exists()
and/or Directory.Exists()
on your path first to see if you need to call Path.GetDirectoryName
How do I specify new lines on Python, when writing on files?
\n - simple newline character insertion works:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
# Output:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
Warning: comparison with string literals results in unspecified behaviour
if (args[i] == "&")
Ok, let's disect what this does.
args is an array of pointers. So, here you are comparing args[i]
(a pointer) to "&"
(also a pointer). Well, the only way this will every be true is if somewhere you have args[i]="&"
and even then, "&"
is not guaranteed to point to the same place everywhere.
I believe what you are actually looking for is either strcmp
to compare the entire string or your wanting to do if (*args[i] == '&')
to compare the first character of the args[i]
string to the &
character
When do I need to use Begin / End Blocks and the Go keyword in SQL Server?
GO ends a batch, you would only very rarely need to use it in code. Be aware that if you use it in a stored proc, no code after the GO will be executed when you execute the proc.
BEGIN and END are needed for any procedural type statements with multipe lines of code to process. You will need them for WHILE loops and cursors (which you will avoid if at all possible of course) and IF statements (well techincally you don't need them for an IF statment that only has one line of code, but it is easier to maintain the code if you always put them in after an IF). CASE statements also use an END but do not have a BEGIN.
How do I get the row count of a Pandas DataFrame?
...building on Jan-Philip Gehrcke's answer.
The reason why len(df)
or len(df.index)
is faster than df.shape[0]
:
Look at the code. df.shape is a @property
that runs a DataFrame method calling len
twice.
df.shape??
Type: property
String form: <property object at 0x1127b33c0>
Source:
# df.shape.fget
@property
def shape(self):
"""
Return a tuple representing the dimensionality of the DataFrame.
"""
return len(self.index), len(self.columns)
And beneath the hood of len(df)
df.__len__??
Signature: df.__len__()
Source:
def __len__(self):
"""Returns length of info axis, but here we use the index """
return len(self.index)
File: ~/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py
Type: instancemethod
len(df.index)
will be slightly faster than len(df)
since it has one less function call, but this is always faster than df.shape[0]
Rails 4 Authenticity Token
I don't think it's good to generally turn off CSRF protection as long as you don't exclusively implement an API.
When looking at the Rails 4 API documentation for ActionController I found that you can turn off forgery protection on a per controller or per method base.
For example to turn off CSRF protection for methods you can use
class FooController < ApplicationController
protect_from_forgery except: :index
This project references NuGet package(s) that are missing on this computer
In my case it happened after I moved my solution folder from one location to another, re-organized it a bit and in the process its relative folder structure changed.
So I had to edit all entries similar to the following one in my .csproj
file from
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
to
<Import Project="packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
(Note the change from ..\packages\
to packages\
. It might be a different relative structure in your case, but you get the idea.)
Send Email Intent
Compose an email in the phone email client:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android
The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):
mWebView = (WebView) findViewById(R.id.web_view);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle things like tel, mailto, etc.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
return true;
}
});
mWebView.loadUrl(url);
Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.
Using node.js as a simple web server
I use below code to start a simple web server which render default html file if no file mentioned in Url.
var http = require('http'),
fs = require('fs'),
url = require('url'),
rootFolder = '/views/',
defaultFileName = '/views/5 Tips on improving Programming Logic Geek Files.htm';
http.createServer(function(req, res){
var fileName = url.parse(req.url).pathname;
// If no file name in Url, use default file name
fileName = (fileName == "/") ? defaultFileName : rootFolder + fileName;
fs.readFile(__dirname + decodeURIComponent(fileName), 'binary',function(err, content){
if (content != null && content != '' ){
res.writeHead(200,{'Content-Length':content.length});
res.write(content);
}
res.end();
});
}).listen(8800);
It will render all js, css and image file, along with all html content.
Agree on statement "No content-type is better than a wrong one"
What does the ^ (XOR) operator do?
Another application for XOR
is in circuits. It is used to sum bits.
When you look at a truth table:
x | y | x^y
---|---|-----
0 | 0 | 0 // 0 plus 0 = 0
0 | 1 | 1 // 0 plus 1 = 1
1 | 0 | 1 // 1 plus 0 = 1
1 | 1 | 0 // 1 plus 1 = 0 ; binary math with 1 bit
You can notice that the result of XOR
is x added with y, without keeping track of the carry bit, the carry bit is obtained from the AND
between x and y.
x^y // is actually ~xy + ~yx
// Which is the (negated x ANDed with y) OR ( negated y ANDed with x ).
How can I define colors as variables in CSS?
I'm not clear on why you can't use PHP. You could then simply add and use variables as you wish, save the file as a PHP file and link to that .php file as the style sheet instead of the .css file.
It doesn't have to be PHP, but you get what I mean.
When we want programming stuff, why not use a programming language until CSS (maybe) supports things like variables?
Also, check out Nicole Sullivan's Object-oriented CSS.
How to resolve ORA-011033: ORACLE initialization or shutdown in progress
Here is my solution to this issue:
SQL> Startup mount
ORA-01081: cannot start already-running ORACLE - shut it down first
SQL> shutdown abort
ORACLE instance shut down.
SQL>
SQL> startup mount
ORACLE instance started.
Total System Global Area 1904054272 bytes
Fixed Size 2404024 bytes
Variable Size 570425672 bytes
Database Buffers 1325400064 bytes
Redo Buffers 5824512 bytes
Database mounted.
SQL> Show parameter control_files
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
control_files string C:\APP\USER\ORADATA\ORACLEDB\C
ONTROL01.CTL, C:\APP\USER\FAST
_RECOVERY_AREA\ORACLEDB\CONTRO
L02.CTL
SQL> select a.member,a.group#,b.status from v$logfile a ,v$log b where a.group#=
b.group# and b.status='CURRENT'
2
SQL> select a.member,a.group#,b.status from v$logfile a ,v$log b where a.group#=
b.group# and b.status='CURRENT';
MEMBER
--------------------------------------------------------------------------------
GROUP# STATUS
---------- ----------------
C:\APP\USER\ORADATA\ORACLEDB\REDO03.LOG
3 CURRENT
SQL> shutdown abort
ORACLE instance shut down.
SQL> startup mount
ORACLE instance started.
Total System Global Area 1904054272 bytes
Fixed Size 2404024 bytes
Variable Size 570425672 bytes
Database Buffers 1325400064 bytes
Redo Buffers 5824512 bytes
Database mounted.
SQL> recover database using backup controlfile until cancel;
ORA-00279: change 4234808 generated at 01/21/2014 18:31:05 needed for thread 1
ORA-00289: suggestion :
C:\APP\USER\FAST_RECOVERY_AREA\ORACLEDB\ARCHIVELOG\2014_01_22\O1_MF_1_108_%U_.AR
C
ORA-00280: change 4234808 for thread 1 is in sequence #108
Specify log: {<RET>=suggested | filename | AUTO | CANCEL}
C:\APP\USER\ORADATA\ORACLEDB\REDO03.LOG
Log applied.
Media recovery complete.
SQL> alter database open resetlogs;
Database altered.
And it worked:
HTML Drag And Drop On Mobile Devices
I needed to create a drag and drop + rotation that works on desktop, mobile, tablet including windows phone. The last one made it more complicated (mspointer vs. touch events).
The solution came from The great Greensock library
It took some jumping through hoops to make the same object draggable and rotatable but it works perfectly
Pro JavaScript programmer interview questions (with answers)
Ask them how they ensure their pages continue to be usable when the user has JavaScript turned off or JavaScript isn't available.
There's no One True Answer, but you're fishing for an answer talking about some strategies for Progressive Enhancement.
Progressive Enhancement consists of
the following core principles:
- basic content should be accessible to all browsers
- basic functionality should be accessible to all browsers
- sparse, semantic markup contains all content
- enhanced layout is provided by externally linked CSS
- enhanced behavior is provided by [[Unobtrusive
JavaScript|unobtrusive]], externally
linked JavaScript
- end user browser preferences are respected
Get next / previous element using JavaScript?
Tested it and it worked for me. The element finding me change as per the document structure that you have.
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form method="post" id = "formId" action="action.php" onsubmit="return false;">
<table>
<tr>
<td>
<label class="standard_text">E-mail</label>
</td>
<td><input class="textarea" name="mail" id="mail" placeholder="E-mail"></label></td>
<td><input class="textarea" name="name" id="name" placeholder="E-mail"> </label></td>
<td><input class="textarea" name="myname" id="myname" placeholder="E-mail"></label></td>
<td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
<td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
<td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
</tr>
</table>
<input class="button_submit" type="submit" name="send_form" value="Register"/>
</form>
</body>
</html>
var inputs;
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('formId');
inputs = form.getElementsByTagName("input");
for(var i = 0 ; i < inputs.length;i++) {
inputs[i].addEventListener('keydown', function(e){
if(e.keyCode == 13) {
var currentIndex = findElement(e.target)
if(currentIndex > -1 && currentIndex < inputs.length) {
inputs[currentIndex+1].focus();
}
}
});
}
});
function findElement(element) {
var index = -1;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i] == element) {
return i;
}
}
return index;
}
Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?
If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.
If you are serving content out of /var/www/abc
, you can verify the selinux permissions with a Z
appended to the normal ls -l
command. i.e. ls -laZ
will give the selinux context.
To add a directory to be served by selinux you can use the semanage
command like this. This will change the label on /var/www/abc
to httpd_sys_content_t
semanage fcontext -a -t httpd_sys_content_t /var/www/abc
this will update the label for /var/www/abc
restorecon /var/www/abc
This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.
Unzip files (7-zip) via cmd command
Regarding Phil Street's post:
It may actually be installed in your 32-bit program folder instead of your default x64, if you're running 64-bit OS. Check to see where 7-zip
is installed, and if it is in Program Files (x86)
then try using this instead:
PATH=%PATH%;C:\Program Files (x86)\7-Zip
Template not provided using create-react-app
For any Windows users still having this issue, this is what fixed it for me:
- Run
where create-react-app
to get the path (mine was in C:\Users\username\AppData\Local\Yarn\bin).
- Navigate to that directory and delete both "create-react-app" and "create-react-app.cmd".
- Navigate to the directory you want to start a project in.
- Run
npm install create-react-app
,
npx create-react-app name-of-app
,
cd name-of-app
, yarn start
.
Step #4 will vary based on your configuration, but that's just what got me up and running.
How can I get the list of files in a directory using C or C++?
Here is a very simple code in C++11
using boost::filesystem
library to get file names in a directory (excluding folder names):
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main()
{
path p("D:/AnyFolder");
for (auto i = directory_iterator(p); i != directory_iterator(); i++)
{
if (!is_directory(i->path())) //we eliminate directories
{
cout << i->path().filename().string() << endl;
}
else
continue;
}
}
Output is like:
file1.txt
file2.dat
What does "to stub" mean in programming?
Layman's terms, it's dummy data (or fake data, test data...etc.) that you can use to test or develop your code against until you (or the other party) is ready to present/receive real data. It's a programmer's "Lorem Ipsum".
Employee database not ready? Make up a simple one with Jane Doe, John Doe...etc.
API not ready? Make up a fake one by creating a static .json file containing fake data.
How do I work with dynamic multi-dimensional arrays in C?
There's no way to allocate the whole thing in one go. Instead, create an array of pointers, then, for each pointer, create the memory for it. For example:
int** array;
array = (int**)malloc(sizeof(int*) * 50);
for(int i = 0; i < 50; i++)
array[i] = (int*)malloc(sizeof(int) * 50);
Of course, you can also declare the array as int* array[50]
and skip the first malloc, but the second set is needed in order to dynamically allocate the required storage.
It is possible to hack a way to allocate it in a single step, but it would require a custom lookup function, but writing that in such a way that it will always work can be annoying. An example could be L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]
, then malloc a block of 50*50 ints or whatever and access using that L
macro, e.g.
#define L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]
int dim_x = 50;
int dim_y = 50;
int* array = malloc(dim_x*dim_y*sizeof(int));
int foo = L(array, 4, 6, dim_x);
But that's much nastier unless you know the effects of what you're doing with the preprocessor macro.
Fastest way to convert string to integer in PHP
I've just set up a quick benchmarking exercise:
Function time to run 1 million iterations
--------------------------------------------
(int) "123": 0.55029
intval("123"): 1.0115 (183%)
(int) "0": 0.42461
intval("0"): 0.95683 (225%)
(int) int: 0.1502
intval(int): 0.65716 (438%)
(int) array("a", "b"): 0.91264
intval(array("a", "b")): 1.47681 (162%)
(int) "hello": 0.42208
intval("hello"): 0.93678 (222%)
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
I'd be interested to know why though.
Update: I've run the tests again, this time with coercion (0 + $var)
| INPUT ($x) | (int) $x |intval($x) | 0 + $x |
|-----------------|------------|-----------|-----------|
| "123" | 0.51541 | 0.96924 | 0.33828 |
| "0" | 0.42723 | 0.97418 | 0.31353 |
| 123 | 0.15011 | 0.61690 | 0.15452 |
| array("a", "b") | 0.8893 | 1.45109 | err! |
| "hello" | 0.42618 | 0.88803 | 0.1691 |
|-----------------|------------|-----------|-----------|
Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
$x = "11";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11)
$x = "0x11";
(int) $x; // int(0)
intval($x); // int(0)
$x + 0; // int(17) !
$x = "011";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11) (not 9)
Tested using PHP 5.3.1
Changing navigation title programmatically
You change the title by changing the title of the view controller being displayed:
viewController.title = "some title"
Normally this is done in view did load on the view controller:
override func viewDidLoad() {
super.viewDidLoad()
self.title = "some title"
}
However, this only works if you have your view controller embedded in a UINavigationController. I highly recommend doing this instead of creating a navigation bar yourself. If you insist on creating a navigation bar yourself, you can change the title by doing:
navigationBar.topItem.title = "some title"
How to add a button programmatically in VBA next to some sheet cell data?
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
How to display both icon and title of action inside ActionBar?
The solution I find is to use custom action Layout:
Here is XML for menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:Eventapp="http://schemas.android.com/apk/res-auto">
<!-- This is a comment. -->
<item
android:id="@+id/action_create"
android:actionLayout="@layout/action_view_details_layout"
android:orderInCategory="50"
android:showAsAction = "always"/>
</menu>
The Layout is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:gravity="center"
android:text="@string/create"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:gravity="center"
android:src="@drawable/ic_action_v"/>
</LinearLayout>
this will show the icon and the text together.
To get the clickitem the the fragment or activity:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
//super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_details_fragment, menu);
View view = menu.findItem(R.id.action_create).getActionView();
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
How to use ternary operator in razor (specifically on HTML attributes)?
Addendum:
The important concept is that you are evaluating an expression in your Razor code. The best way to do this (if, for example, you are in a foreach loop) is using a generic method.
The syntax for calling a generic method in Razor is:
@(expression)
In this case, the expression is:
User.Identity.IsAuthenticated ? "auth" : "anon"
Therefore, the solution is:
@(User.Identity.IsAuthenticated ? "auth" : "anon")
This code can be used anywhere in Razor, not just for an html attribute.
See @Kyralessa 's comment for C# Razor Syntax Quick Reference (Phil Haack's blog).
How do I concatenate multiple C++ strings on one line?
Your code can be written as1,
s = "Hello world," "nice to see you," "or not."
...but I doubt that's what you're looking for. In your case, you are probably looking for streams:
std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();
1 "can be written as" : This only works for string literals. The concatenation is done by the compiler.
How can I capture the result of var_dump to a string?
This maybe a bit off topic.
I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.
fwrite(fopen('php://stdout', 'w'), var_export($object, true));
Comparing Java enum members: == or equals()?
Using ==
to compare two enum values works, because there is only one object for each enum constant.
On a side note, there is actually no need to use ==
to write null-safe code, if you write your equals()
like this:
public useEnums(final SomeEnum a) {
if (SomeEnum.SOME_ENUM_VALUE.equals(a)) {
…
}
…
}
This is a best practice known as Compare Constants From The Left that you definitely should follow.
XAMPP - Apache could not start - Attempting to start Apache service
My scenario was different after I tested all the possible options. If you have changed the ports and still get the same problem, well here's something you can try out. This was done in Windows 7.
Step 1: Confirm the cause of the error by going to Control Panel -> System and Security -> Administrative Tools -> Event Viewer -> Windows Logs -> Application -> Error. Mine said "The Apache service named reported the following error:
httpd.exe: Syntax error on line 424 of C:/xampp/apache/conf/httpd.conf: Cannot load c:\xampp\php\php5apache.dll into server: The specified module could not be found." So I needed to change \php5apache.dll to the version of my php and apache version installed which was php7apache2_4.dll
Step 2: To get the correct name for your .dll php and apache file, got to C:\xampp\php. You will see something like php7apache2_4.dll with other files in the folder.
Step 3: Go to C:/xampp/apache/conf/httpd.conf and edit the configuration file and change "c:\xampp\php\php5apache.dll" to "c:\xampp\php\php7apache2_4.dll" in my case. Make sure you open the file as administrator save changes made.
Step 4: Run the xampp server and everything should work fine. Do not forget to shut down the xampp server before doing the changes to the apache configuration file.
Hope this helps. Cheers! :)
Standard concise way to copy a file in Java?
- These methods are performance-engineered (they integrate with operating system native I/O).
- These methods work with files, directories and links.
- Each of the options supplied may be left out - they are optional.
The utility class
package com.yourcompany.nio;
class Files {
static int copyRecursive(Path source, Path target, boolean prompt, CopyOptions options...) {
CopyVisitor copyVisitor = new CopyVisitor(source, target, options).copy();
EnumSet<FileVisitOption> fileVisitOpts;
if (Arrays.toList(options).contains(java.nio.file.LinkOption.NOFOLLOW_LINKS) {
fileVisitOpts = EnumSet.noneOf(FileVisitOption.class)
} else {
fileVisitOpts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
}
Files.walkFileTree(source[i], fileVisitOpts, Integer.MAX_VALUE, copyVisitor);
}
private class CopyVisitor implements FileVisitor<Path> {
final Path source;
final Path target;
final CopyOptions[] options;
CopyVisitor(Path source, Path target, CopyOptions options...) {
this.source = source; this.target = target; this.options = options;
};
@Override
FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
// before visiting entries in a directory we copy the directory
// (okay if directory already exists).
Path newdir = target.resolve(source.relativize(dir));
try {
Files.copy(dir, newdir, options);
} catch (FileAlreadyExistsException x) {
// ignore
} catch (IOException x) {
System.err.format("Unable to create: %s: %s%n", newdir, x);
return SKIP_SUBTREE;
}
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Path newfile= target.resolve(source.relativize(file));
try {
Files.copy(file, newfile, options);
} catch (IOException x) {
System.err.format("Unable to copy: %s: %s%n", source, x);
}
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
// fix up modification time of directory when done
if (exc == null && Arrays.toList(options).contains(COPY_ATTRIBUTES)) {
Path newdir = target.resolve(source.relativize(dir));
try {
FileTime time = Files.getLastModifiedTime(dir);
Files.setLastModifiedTime(newdir, time);
} catch (IOException x) {
System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
}
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
if (exc instanceof FileSystemLoopException) {
System.err.println("cycle detected: " + file);
} else {
System.err.format("Unable to copy: %s: %s%n", file, exc);
}
return CONTINUE;
}
}
Copying a directory or file
long bytes = java.nio.file.Files.copy(
new java.io.File("<filepath1>").toPath(),
new java.io.File("<filepath2>").toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.COPY_ATTRIBUTES,
java.nio.file.LinkOption.NOFOLLOW_LINKS);
Moving a directory or file
long bytes = java.nio.file.Files.move(
new java.io.File("<filepath1>").toPath(),
new java.io.File("<filepath2>").toPath(),
java.nio.file.StandardCopyOption.ATOMIC_MOVE,
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Copying a directory or file recursively
long bytes = com.yourcompany.nio.Files.copyRecursive(
new java.io.File("<filepath1>").toPath(),
new java.io.File("<filepath2>").toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
java.nio.file.LinkOption.NOFOLLOW_LINKS );
Bootstrap 3: pull-right for col-lg only
For those interested in text alignment, a simple solution is to create a new class:
.text-right-large {
text-align: right;
}
@media (max-width: 991px) {
.text-right-large {
text-align: left;
}
}
Then add that class:
<div class="row">
<div class="col-lg-6 col-md-6">elements 1</div>
<div class="col-lg-6 col-md-6 text-right-large">
elements 2
</div>
</div>
How can you program if you're blind?
When I was in grad school, we had a member of our research team who was blind. He was a bit older, maybe mid-40s. He told us about how he programmed his first computer (which was well before text-to-speech was common) to output the contents of the screen in Morse Code. To overcome the obvious chicken-and-egg problem, he had to completely rewrite the code each time through from scratch until it was working well enough for him to have it read back to him.
Now he uses text-to-speech, though he plans the code very thoroughly before actually writing any of it, to minimize the debug loop.
He was also pretty good at giving PowerPoint presentations that, despite his lack of sight, were just about as well formatted as any sighted presenter's.
How to check which locks are held on a table
To add to the other responses, sp_lock
can also be used to dump full lock information on all running processes. The output can be overwhelming, but if you want to know exactly what is locked, it's a valuable one to run. I usually use it along with sp_who2
to quickly zero in on locking problems.
There are multiple different versions of "friendlier" sp_lock
procedures available online, depending on the version of SQL Server in question.
In your case, for SQL Server 2005, sp_lock
is still available, but deprecated, so it's now recommended to use the sys.dm_tran_locks
view for this kind of thing. You can find an example of how to "roll your own" sp_lock function here.
Custom thread pool in Java 8 parallel stream
There actually is a trick how to execute a parallel operation in a specific fork-join pool. If you execute it as a task in a fork-join pool, it stays there and does not use the common one.
final int parallelism = 4;
ForkJoinPool forkJoinPool = null;
try {
forkJoinPool = new ForkJoinPool(parallelism);
final List<Integer> primes = forkJoinPool.submit(() ->
// Parallel task here, for example
IntStream.range(1, 1_000_000).parallel()
.filter(PrimesPrint::isPrime)
.boxed().collect(Collectors.toList())
).get();
System.out.println(primes);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
} finally {
if (forkJoinPool != null) {
forkJoinPool.shutdown();
}
}
The trick is based on ForkJoinTask.fork
which specifies: "Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool()
if not inForkJoinPool()
"
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.
How to modify memory contents using GDB?
As Nikolai has said you can use the gdb 'set' command to change the value of a variable.
You can also use the 'set' command to change memory locations.
eg. Expanding on Nikolai's example:
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20
This should work for any valid pointer, and can be cast to any appropriate data type.
React Native: Getting the position of an element
You can use onLayout
to get the width, height, and relative-to-parent position of a component at the earliest moment that they're available:
<View
onLayout={event => {
const layout = event.nativeEvent.layout;
console.log('height:', layout.height);
console.log('width:', layout.width);
console.log('x:', layout.x);
console.log('y:', layout.y);
}}
>
Compared to using .measure()
as shown in the accepted answer, this has the advantage that you'll never have to fiddle around deferring your .measure()
calls with setTimeout
to make sure that the measurements are available, but the disadvantage that it doesn't give you offsets relative to the entire page, only ones relative to the element's parent.
Django CSRF check failing with an Ajax POST request
I've just encountered a bit different but similar situation. Not 100% sure if it'd be a resolution to your case, but I resolved the issue for Django 1.3 by setting a POST parameter 'csrfmiddlewaretoken' with the proper cookie value string which is usually returned within the form of your home HTML by Django's template system with '{% csrf_token %}' tag. I did not try on the older Django, just happened and resolved on Django1.3.
My problem was that the first request submitted via Ajax from a form was successfully done but the second attempt from the exact same from failed, resulted in 403 state even though the header 'X-CSRFToken' is correctly placed with the CSRF token value as well as in the case of the first attempt.
Hope this helps.
Regards,
Hiro
Git undo changes in some files
Yes;
git commit FILE
will commit just FILE. Then you can use
git reset --hard
to undo local changes in other files.
There may be other ways too that I don't know about...
edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)
Releasing memory in Python
First, you may want to install glances:
sudo apt-get install python-pip build-essential python-dev lm-sensors
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances
Then run it in the terminal!
glances
In your Python code, add at the begin of the file, the following:
import os
import gc # Garbage Collector
After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:
del myBigVar
gc.collect()
In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!
Good luck!
P.S. I assume you are working on a Debian or Ubuntu system
What's faster, SELECT DISTINCT or GROUP BY in MySQL?
It seems that the queries are not exactly the same. At least for MySQL.
Compare:
- describe select distinct productname from northwind.products
- describe select productname from northwind.products group by productname
The second query gives additionally "Using filesort" in Extra.
Getting the client's time zone (and offset) in JavaScript
This value is from user's machine and it can be changed anytime so I think it doesn't matter, I just want to get an approximate value and then convert it to GMT in my server.
For example, I am from Taiwan and it returns "+8" for me.
Working example
JS
function timezone() {
var offset = new Date().getTimezoneOffset();
var minutes = Math.abs(offset);
var hours = Math.floor(minutes / 60);
var prefix = offset < 0 ? "+" : "-";
return prefix+hours;
}
$('#result').html(timezone());
HTML
<div id="result"></div>
Result
+8
Passing variables, creating instances, self, The mechanics and usage of classes: need explanation
So here is a simple example of how to use classes:
Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:
class bankaccount():
def __init__(self, name, money):
self.name = name
self.money = money
def earn_money(self, amount):
self.money += amount
def withdraw_money(self, amount):
self.money -= amount
def show_balance(self):
print self.money
Now you have an abstract model of a simple account and its mechanism.
The def __init__(self, name, money)
is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:
spidermans_account = bankaccount("SpiderMan", 1000)
If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw
method on his account:
spidermans_account.withdraw_money(100)
If he wants to see the balance he calls:
spidermans_account.show_balance()
The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
__init__() missing 1 required positional argument
Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:
class DHT:
def __init__(self):
self.data = {}
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Or even just:
class DHT:
def __init__(self):
self.data = {'one': '1', 'two': '2', 'three': '3'}
def showData(self):
print(self.data)
SQL Server equivalent of MySQL's NOW()?
You can also use CURRENT_TIMESTAMP
, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate()
under the covers (see this question for more on that).
There's no ANSI equivalent for GetUTCDate()
, however, which is probably the one you should be using if your app operates in more than a single time zone ...
Validation for 10 digit mobile number and focus input field on invalid
I used $form.submit() as it keeps html input validation.
Also I used input type tel as it supported by mobile browsers, only display numeric keypad.
<input type="tel" minlength="10" maxlength="10" id="mobile" name="mobile" title="10 digit mobile number" required>
$('#mob_frm').submit(function(e) {
e.preventDefault();
if(!$('#mobile').val().match('[0-9]{10}')) {
alert("Please put 10 digit mobile number");
return;
}
});
Android - get children inside a View?
This method takes all views inside a layout, this is similar to Alexander Kulyakhtin's answer. The difference is, it accepts any type of parent layouts & returns an Array List of views.
public List<View> getAllViews(ViewGroup layout){
List<View> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
views.add(layout.getChildAt(i));
}
return views;
}
The character encoding of the plain text document was not declared - mootool script
If anyone is using SQL and they have meta tags there and still the error is shown, this happens because of your connection from .net to SQL.
In you appsettings.json update your connection string to have: Persist Security Info=True
. So your connection string should look like this:
"DefaultConnection": "Server=[[server]];Initial Catalog=[[db]];Persist Security Info=True;User ID=[[user]];Password=[[pass]];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
htaccess redirect all pages to single page
This will direct everything from the old host to the root of the new host:
RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]
Webdriver findElements By xpath
The XPath turns into this:
Get me all of the div elements that have an id equal to container.
As for getting the first etc, you have two options.
Turn it into a .findElement()
- this will just return the first one for you anyway.
or
To explicitly do this in XPath, you'd be looking at:
(//div[@id='container'])[1]
for the first one, for the second etc:
(//div[@id='container'])[2]
Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:
(//div[@id='container'])[last()]
Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.
As for getting the parent 'node', well, you can use parent:
//div[@id='container']/parent::*
That would get the div's direct parent.
You could then go further and say I want the first *div* with an id of container, and I want his parent:
(//div[@id='container'])[1]/parent::*
Hope that helps!
How to change line width in IntelliJ (from 120 character)
You can alter the "Right margin" attribute in the preferences, which can be found via
File | Settings | Project Settings | Code Style - General
Right Margin (columns) In this text box, specify the number of columns
to be used to display pages in the editor.
Source: Jetbrains
What is the 'override' keyword in C++ used for?
Wikipedia says:
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
In detail, when you have an object foo that has a void hello() function:
class foo {
virtual void hello(); // Code : printf("Hello!");
}
A child of foo, will also have a hello() function:
class bar : foo {
// no functions in here but yet, you can call
// bar.hello()
}
However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override
class bar : foo {
virtual void hello() override; // Code : printf("Hello Bar!");
}
Start redis-server with config file
To start redis with a config file all you need to do is specifiy the config file as an argument:
redis-server /root/config/redis.rb
Instead of using and killing PID's I would suggest creating an init script for your service
I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start
and service redis_server stop
to control your server.
I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.
Utilizing multi core for tar+gzip/bzip compression/decompression
A relatively newer (de)compression tool you might want to consider is zstandard. It does an excellent job of utilizing spare cores, and it has made some great trade-offs when it comes to compression ratio vs. (de)compression time. It is also highly tweak-able depending on your compression ratio needs.
File name without extension name VBA
Using the Split function seems more elegant than InStr and Left, in my opinion.
Private Sub CommandButton2_Click()
Dim ThisFileName As String
Dim BaseFileName As String
Dim FileNameArray() As String
ThisFileName = ThisWorkbook.Name
FileNameArray = Split(ThisFileName, ".")
BaseFileName = FileNameArray(0)
MsgBox "Base file name is " & BaseFileName
End Sub
Add querystring parameters to link_to
In case you want to pass in a block, say, for a glyphicon button, as in the following:
<%= link_to my_url, class: "stuff" do %>
<i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>
Then passing querystrings params could be accomplished through:
<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
<i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>
How to get the top 10 values in postgresql?
Note that if there are ties in top 10 values, you will only get the top 10 rows, not the top 10 values with the answers provided.
Ex: if the top 5 values are 10, 11, 12, 13, 14, 15 but your data contains
10, 10, 11, 12, 13, 14, 15 you will only get 10, 10, 11, 12, 13, 14 as your top 5 with a LIMIT
Here is a solution which will return more than 10 rows if there are ties but you will get all the rows where some_value_column
is technically in the top 10.
select
*
from
(select
*,
rank() over (order by some_value_column desc) as my_rank
from mytable) subquery
where my_rank <= 10
issue ORA-00001: unique constraint violated coming in INSERT/UPDATE
This ORA error is occurred because of violation of unique constraint.
ORA-00001: unique constraint (constraint_name) violated
This is caused because of trying to execute an INSERT
or UPDATE
statement that has created a duplicate value in a field restricted by a unique index.
You can resolve this either by
- changing the constraint to allow duplicates, or
- drop the unique constraint or you can change your SQL to avoid duplicate inserts
Remove HTML Tags in Javascript with Regex
The selected answer doesn't always ensure that HTML is stripped, as it's still possible to construct an invalid HTML string through it by crafting a string like the following.
"<<h1>h1>foo<<//</h1>h1/>"
This input will ensure that the stripping assembles a set of tags for you and will result in:
"<h1>foo</h1>"
additionally jquery's text function will strip text not surrounded by tags.
Here's a function that uses jQuery but should be more robust against both of these cases:
var stripHTML = function(s) {
var lastString;
do {
s = $('<div>').html(lastString = s).text();
} while(lastString !== s)
return s;
};
How to pass an event object to a function in Javascript?
Although this is the accepted answer, toto_tico's answer below is better :)
Try making the onclick js use 'return' to ensure the desired return value gets used...
<button type="button" value="click me" onclick="return check_me();" />
Creating a new user and password with Ansible
The Ansible 'user' module manages users, in the idempotent way. In the playbook below the first task declares state=present for the user. Note that 'register: newuser' in the first action helps the second action to determine if the user is new (newuser.changed==True) or existing (newuser.changed==False
), to only generate the password once.
The Ansible playbook has:
tasks:
- name: create deployment user
user:
name: deployer
createhome: yes
state: present
register: newuser
- name: generate random password for user only on creation
shell: /usr/bin/openssl rand -base64 32 | passwd --stdin deployer
when: newuser.changed
How to determine if object is in array
i know this is an old post, but i wanted to provide a JQuery plugin version and my code.
// Find the first occurrence of object in list, Similar to $.grep, but stops searching
function findFirst(a,b){
var i; for (i = 0; i < a.length; ++i) { if (b(a[i], i)) return a[i]; } return undefined;
}
usage:
var product = $.findFirst(arrProducts, function(p) { return p.id == 10 });
How to remove an appended element with Jquery and why bind or live is causing elements to repeat
If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on()
to register event handlers. Here's a link to the jQuery docs about on
: link
Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.
Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.
$('#answer').on('click', function() {
feedback('hey there');
});
var counter = 0;
function feedback(message) {
$('#feedback').remove();
$('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');
counter++;
}
"No X11 DISPLAY variable" - what does it mean?
For those who are trying to get an X Window application working from Windows from Linux:
What worked for me was to setup xming server on my windows machine, set X11 forwarding option in putty when I connect to the linux host and put in my windows ip address with the display port and then the display variable with my windows IP address:0.0
Dont forget to add the linux hosts IP address to the X0.hosts file to ensure that the xming server accepts traffic from that host. Took me a while to figure that out.
Simplest way to detect a pinch
My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.
HTML:
<div id="zoom_here">....</div>
JS
<script>
var dist1=0;
function start(ev) {
if (ev.targetTouches.length == 2) {//check if two fingers touched screen
dist1 = Math.hypot( //get rough estimate of distance between two fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
}
}
function move(ev) {
if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
// Check if the two target touches are the same ones that started
var dist2 = Math.hypot(//get rough estimate of new distance between fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
//alert(dist);
if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
alert('zoom out');
}
if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
alert('zoom in');
}
}
}
document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>
How to include *.so library in Android Studio?
Solution 1 : Creation of a JniLibs folder
Create a folder called “jniLibs” into your app and the folders containing your *.so inside.
The "jniLibs" folder needs to be created in the same folder as your "Java" or "Assets" folders.
Solution 2 : Modification of the build.gradle file
If you don’t want to create a new folder and keep your *.so files into the libs folder, it is possible !
In that case, just add your *.so files into the libs folder (please respect the same architecture as the solution 1 : libs/armeabi/.so for instance) and modify the build.gradle file of your app to add the source directory of the jniLibs.
sourceSets {
main {
jniLibs.srcDirs = ["libs"]
}
}
You will have more explanations, with screenshots to help you here ( Step 6 ):
http://blog.guillaumeagis.eu/setup-andengine-with-android-studio/
EDIT It had to be jniLibs.srcDirs, not jni.srcDirs - edited the code. The directory can be a [relative] path that points outside of the project directory.
Why doesn't list have safe "get" method like dictionary?
Your usecase is basically only relevant for when doing arrays and matrixes of a fixed length, so that you know how long they are before hand. In that case you typically also create them before hand filling them up with None or 0, so that in fact any index you will use already exists.
You could say this: I need .get() on dictionaries quite often. After ten years as a full time programmer I don't think I have ever needed it on a list. :)
How to get the return value from a thread in python?
Here is the version that I created of @Kindall's answer https://stackoverflow.com/a/6894023/12900787
This version makes it so that all you have to do is input your command with arguments to create the new thread.
(I have also included a couple of tests)
this was made with python 3.8
from threading import Thread
from typing import Any
#def threader(com): # my original Version (Ignore this)
# try:
# threader = Thread(target = com)
# threader.start()
# except Exception as e:
# print(e)
# print('Could not start thread')
def test(plug, plug2, plug3):
print(f"hello {plug}")
print(f'I am the second plug : {plug2}')
print(plug3)
return 'I am the return Value!'
def test2(msg):
return f'I am from the second test: {msg}'
def test3():
print('hello world')
def NewThread(com, Returning: bool, *arguments) -> Any:
"""
Will create a new thread for a function/command.
:param com: Command to be Executed
:param arguments: Arguments to be sent to Command
:param Returning: True/False Will this command need to return anything
"""
class NewThreadWorker(Thread):
def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, *,
daemon = None):
Thread.__init__(self, group, target, name, args, kwargs, daemon = daemon)
self._return = None
def run(self):
if self._target is not None:
self._return = self._target(*self._args, **self._kwargs)
def join(self):
Thread.join(self)
return self._return
ntw = NewThreadWorker(target = com, args = (*arguments,))
ntw.start()
if Returning:
return ntw.join()
if __name__ == "__main__":
# threader(test('world'))
print(NewThread(test, True, 'hi', 'test', test2('hi')))
NewThread(test3, True)
Hope that this is useful to someone :)
How to pretty-print a numpy.array without scientific notation and with given precision?
Unutbu gave a really complete answer (they got a +1 from me too), but here is a lo-tech alternative:
>>> x=np.random.randn(5)
>>> x
array([ 0.25276524, 2.28334499, -1.88221637, 0.69949927, 1.0285625 ])
>>> ['{:.2f}'.format(i) for i in x]
['0.25', '2.28', '-1.88', '0.70', '1.03']
As a function (using the format()
syntax for formatting):
def ndprint(a, format_string ='{0:.2f}'):
print [format_string.format(v,i) for i,v in enumerate(a)]
Usage:
>>> ndprint(x)
['0.25', '2.28', '-1.88', '0.70', '1.03']
>>> ndprint(x, '{:10.4e}')
['2.5277e-01', '2.2833e+00', '-1.8822e+00', '6.9950e-01', '1.0286e+00']
>>> ndprint(x, '{:.8g}')
['0.25276524', '2.283345', '-1.8822164', '0.69949927', '1.0285625']
The index of the array is accessible in the format string:
>>> ndprint(x, 'Element[{1:d}]={0:.2f}')
['Element[0]=0.25', 'Element[1]=2.28', 'Element[2]=-1.88', 'Element[3]=0.70', 'Element[4]=1.03']
JUnit Testing private variables?
I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?
Import module from subfolder
Say your project is structured this way:
+---MyPythonProject
| +---.gitignore
| +---run.py
| | +---subscripts
| | | +---script_one.py
| | | +---script_two.py
Inside run.py
, you can import scripts one and two by:
from subscripts import script_one as One
from subscripts import script_two as Two
Now, still inside run.py
, you'll be able to call their methods with:
One.method_from_one(param)
Two.method_from_two(other_param)
How to create a DOM node as an object?
First make your template into a jQuery object:
var template = $("<li><div class='bar'>bla</div></li>");
Then set the attributes and append it to the DOM.
template.find('li').attr('id','1234');
$(document.body).append(template);
Note that it however makes no sense at all to add a li directly to the DOM since li should always be children of ul or ol. Also it is better to not make jQuery parse raw HTML. Instead create a li, set its attributes. Create a div and set it's attributes. Insert the div into the li and then append the li to the DOM.
Get all files that have been modified in git branch
Expanding off of what @twalberg and @iconoclast had, if you're using cmd for whatever reason, you can use:
FOR /F "usebackq" %x IN (`"git branch | grep '*' | cut -f2 -d' '"`) DO FOR /F "usebackq" %y IN (`"git merge-base %x master"`) DO git diff --name-only %x %y
How to reset Jenkins security settings from the command line?
The simplest solution is to completely disable security - change true
to false
in /var/lib/jenkins/config.xml
file.
<useSecurity>true</useSecurity>
Then just restart Jenkins, by
sudo service jenkins restart
And then go to admin panel and set everything once again.
If you in case are running your Jenkins inside k8s pod from a docker, which is my case and can not run service
command, then you can just restart Jenkins by deleting the pod:
kubectl delete pod <jenkins-pod-name>
Once the command was issued, the k8s will terminate the old pod and start a new one.