Number of visitors on a specific page
As Blexy already answered, go to "Behavior > Site Content > All Pages".
Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:
How to refresh token with Google API client?
FYI: The 3.0 Google Analytics API will automatically refresh the access token if you have a refresh token when it expires so your script never needs refreshToken
.
(See the Sign
function in auth/apiOAuth2.php
)
Can I use tcpdump to get HTTP requests, response header and response body?
There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):
Run man tcpdump | less -Ip examples
to see some examples
Here’s a tcpdump filter for HTTP GET (GET
= 0x47
, 0x45
, 0x54
, 0x20
):
sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
Here’s a tcpdump filter for HTTP POST (POST
= 0x50
, 0x4f
, 0x53
, 0x54
):
sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
Monitor HTTP traffic including request and response headers and message body (source):
tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).
How to uncheck a radio button?
function clearForm(){
$('#frm input[type="text"]').each(function(){
$(this).val("");
});
$('#frm input[type="radio":checked]').each(function(){
$(this).attr('checked', false);
});
}
The correct selector is: #frm input[type="radio"]:checked
not #frm input[type="radio":checked]
NSDictionary to NSArray?
+ (NSArray *)getArrayListFromDictionary:(NSDictionary *)dictMain paramName:(NSString *)paramName
{
if([dictMain isKindOfClass:[NSDictionary class]])
{
if ([dictMain objectForKey:paramName])
{
if ([[dictMain objectForKey:paramName] isKindOfClass:[NSArray class]])
{
NSArray *dataArray = [dictMain objectForKey:paramName];
return dataArray;
}
}
}
return [[NSArray alloc] init];
}
Hope this helps!
Get checkbox value in jQuery
Those 2 ways are working:
$('#checkbox').prop('checked')
$('#checkbox').is(':checked')
(thanks @mgsloan)
_x000D_
_x000D_
$('#test').click(function() {_x000D_
alert("Checkbox state (method 1) = " + $('#test').prop('checked'));_x000D_
alert("Checkbox state (method 2) = " + $('#test').is(':checked'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
Check me: <input id="test" type="checkbox" />
_x000D_
_x000D_
_x000D_
CSS table layout: why does table-row not accept a margin?
How's this for a work around (using an actual table)?
table {
border-collapse: collapse;
}
tr.row {
border-bottom: solid white 30px; /* change "white" to your background color */
}
It's not as dynamic, since you have to explicitly set the color of the border (unless there's a way around that too), but this is something I'm experimenting with on a project of my own.
Edit to include comments regarding transparent
:
tr.row {
border-bottom: 30px solid transparent;
}
COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?
Two of them always produce the same answer:
COUNT(*)
counts the number of rows
COUNT(1)
also counts the number of rows
Assuming the pk
is a primary key and that no nulls are allowed in the values, then
COUNT(pk)
also counts the number of rows
However, if pk
is not constrained to be not null, then it produces a different answer:
COUNT(possibly_null)
counts the number of rows with non-null values in the column possibly_null
.
COUNT(DISTINCT pk)
also counts the number of rows (because a primary key does not allow duplicates).
COUNT(DISTINCT possibly_null_or_dup)
counts the number of distinct non-null values in the column possibly_null_or_dup
.
COUNT(DISTINCT possibly_duplicated)
counts the number of distinct (necessarily non-null) values in the column possibly_duplicated
when that has the NOT NULL
clause on it.
Normally, I write COUNT(*)
; it is the original recommended notation for SQL. Similarly, with the EXISTS
clause, I normally write WHERE EXISTS(SELECT * FROM ...)
because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.
Best way to save a trained model in PyTorch?
It depends on what you want to do.
Case # 1: Save the model to use it yourself for inference: You save the model, you restore it, and then you change the model to evaluation mode. This is done because you usually have BatchNorm
and Dropout
layers that by default are in train mode on construction:
torch.save(model.state_dict(), filepath)
#Later to restore:
model.load_state_dict(torch.load(filepath))
model.eval()
Case # 2: Save model to resume training later: If you need to keep training the model that you are about to save, you need to save more than just the model. You also need to save the state of the optimizer, epochs, score, etc. You would do it like this:
state = {
'epoch': epoch,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
...
}
torch.save(state, filepath)
To resume training you would do things like: state = torch.load(filepath)
, and then, to restore the state of each individual object, something like this:
model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])
Since you are resuming training, DO NOT call model.eval()
once you restore the states when loading.
Case # 3: Model to be used by someone else with no access to your code:
In Tensorflow you can create a .pb
file that defines both the architecture and the weights of the model. This is very handy, specially when using Tensorflow serve
. The equivalent way to do this in Pytorch would be:
torch.save(model, filepath)
# Then later:
model = torch.load(filepath)
This way is still not bullet proof and since pytorch is still undergoing a lot of changes, I wouldn't recommend it.
Format date as dd/MM/yyyy using pipes
You can find more information about the date pipe here, such as formats.
If you want to use it in your component, you can simply do
pipe = new DatePipe('en-US'); // Use your own locale
Now, you can simply use its transform method, which will be
const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');
How to edit hosts file via CMD?
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
JAVA_HOME should point to a JDK not a JRE
In IntelliJ IDEA go to File>Project Structure>SDK>JDK home path
.
Copy it and then go to
My Computer>Advanced Settings>Environment Variables
Change the JAVA_HOME path to what you have copied.
Then open new cmd, and try mvn -v
It worked for me !!!
Using RegEX To Prefix And Append In Notepad++
Use a Macro.
Macro>Start Recording
Use the keyboard to make your changes in a repeatable manner e.g.
home>type "able">end>down arrow>home
Then go back to the menu and click stop recording then run a macro multiple times.
That should do it and no regex based complications!
How to force the browser to reload cached CSS and JavaScript files
Thanks to Kip for his perfect solution!
I extended it to use it as an Zend_view_Helper. Because my client run his page on a virtual host I also extended it for that.
/**
* Extend filepath with timestamp to force browser to
* automatically refresh them if they are updated
*
* This is based on Kip's version, but now
* also works on virtual hosts
* @link http://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files
*
* Usage:
* - extend your .htaccess file with
* # Route for My_View_Helper_AutoRefreshRewriter
* # which extends files with there timestamp so if these
* # are updated a automatic refresh should occur
* # RewriteRule ^(.*)\.[^.][\d]+\.(css|js)$ $1.$2 [L]
* - then use it in your view script like
* $this->headLink()->appendStylesheet( $this->autoRefreshRewriter($this->cssPath . 'default.css'));
*
*/
class My_View_Helper_AutoRefreshRewriter extends Zend_View_Helper_Abstract {
public function autoRefreshRewriter($filePath) {
if (strpos($filePath, '/') !== 0) {
// Path has no leading '/'
return $filePath;
} elseif (file_exists($_SERVER['DOCUMENT_ROOT'] . $filePath)) {
// File exists under normal path
// so build path based on this
$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $filePath);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $filePath);
} else {
// Fetch directory of index.php file (file from all others are included)
// and get only the directory
$indexFilePath = dirname(current(get_included_files()));
// Check if file exist relativ to index file
if (file_exists($indexFilePath . $filePath)) {
// Get timestamp based on this relativ path
$mtime = filemtime($indexFilePath . $filePath);
// Write generated timestamp to path
// but use old path not the relativ one
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $filePath);
} else {
return $filePath;
}
}
}
}
What does the @Valid annotation indicate in Spring?
@Valid
in itself has nothing to do with Spring. It's part of Bean Validation specification(there are several of them, the latest one being JSR 380 as of second half of 2017), but @Valid
is very old and derives all the way from JSR 303.
As we all know, Spring is very good at providing integration with all different JSRs and java libraries in general(think of JPA, JTA, Caching, etc.) and of course those guys took care of validation as well. One of the key components that facilitates this is MethodValidationPostProcessor.
Trying to answer your question - @Valid
is very handy for so called validation cascading when you want to validate a complex graph and not just a top-level elements of an object. Every time you want to go deeper, you have to use @Valid
. That's what JSR dictates. Spring will comply with that with some minor deviations(for example I tried putting @Validated
instead of @Valid
on RestController method and validation works, but the same will not apply for a regular "service" beans).
jQuery delete confirmation box
Try with this JSFiddle
DEMO : http://jsfiddle.net/2yEtK/3/
Jquery Code:
$("a.removeRecord").live("click",function(event){
event.stopPropagation();
if(confirm("Do you want to delete?")) {
this.click;
alert("Ok");
}
else
{
alert("Cancel");
}
event.preventDefault();
});
jQuery Ajax PUT with parameters
Use:
$.ajax({
url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
console.log(data);
}
});
Always remember to use _METHOD=PUT
.
Annotation @Transactional. How to rollback?
For me rollbackFor was not enough, so I had to put this and it works as expected:
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
I hope it helps :-)
The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located
According to your repro steps, I assumed that changing the output path in the application's property was your only change after you created the application. The only thing this change does is that it tells Visual Studio to put the output assemblies of MSBuild into the new folder. At runtime, however, ASP.Net wouldn't have any idea that it should load assemblies from this new folder instead of the \bin folder.
This answer shows the way to change the build output directory of a WebApi application. To get the exact same error showed in that post, you need to comment out the entire <system.codedom> section in web.config. And then you can follow the instructions to change the output path.
After you get your applicaiton work, you may then uncomment the <system.codedom> section. If you don't use C# 6 new syntax in your application at all you can uninstall the Microsoft.CodeDom.Providers.DotNetCompilerPlatform from you application; otherwise, you may want to add the following command line in your post-build event,
xcopy /Q /Y "$(TargetDir)roslyn\*.*" "$(TargetDir)..\roslyn\"
The new CodeDom provider always looks for the "\roslyn" folder in \bin. The above command works as a workaround and copies the \roslyn folder from your new output folder to \bin.
In my experiments, the publish tool of Visual Studio, however, published the output assemblies to the \bin folder in the deployment location regardless my output path setting. I guess your application should still work on actual deployment.
$_POST not working. "Notice: Undefined index: username..."
undefined index means that somewhere in the $_POST array, there isn't an index (key) for the key username.
You should be setting your posted values into variables for a more clean solution, and it's a good habit to get into.
If I was having a similar error, I'd do something like this:
$username = $_POST['username']; // you should really do some more logic to see if it's set first
echo $username;
If username didn't turn up, that'd mean I was screwing up somewhere. You can also,
var_dump($_POST);
To see what you're posting. var_dump is really useful as far as debugging. Check it out: var_dump
How to run script as another user without password?
`su -c "Your command right here" -s /bin/sh username`
The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example;
execl: couldn't exec /bin/sh
execl: Permission denied
I had to install setroubleshoot and setools and run the following to allow it:
yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p
JavaScript Array to Set
What levi said about passing it into the constructor is correct, but you could also use an object.
I think what Veverke is trying to say is that you could easily use the delete
keyword on an object to achieve the same effect.
I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).
Try something like this:
var obj = {
"bob": "dole",
"mr.": "peabody",
"darkwing": "duck"
};
Then, you could just do this:
delete obj["bob"];
The structure of the object would then be this:
{
"mr.": "peabody",
"darkwing": "duck"
}
Which has the same effect.
Can pandas automatically recognize dates?
Perhaps the pandas interface has changed since @Rutger answered, but in the version I'm using (0.15.2), the date_parser
function receives a list of dates instead of a single value. In this case, his code should be updated like so:
dateparse = lambda dates: [pd.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dates]
df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)
How to start nginx via different port(other than 80)
Follow this:
Open your config file
vi /etc/nginx/conf.d/default.conf
Change port number on which you are listening;
listen 81;
server_name localhost;
Add a rule to iptables
vi /etc/sysconfig/iptables
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT
Restart IPtables
service iptables restart;
Restart the nginx server
service nginx restart
Access yr nginx server files on port 81
How to put multiple statements in one line?
if you want it without try and except then there is the solution
what you are trying to do is print 'hello' if 'harry' in a list
then the solution is
'hello' if 'harry' in sam else ''
Convert pyQt UI to python
Update for anyone using PyQt5 with python 3.x:
- Open terminal (eg. Powershell, cmd etc.)
- cd into the folder with your
.ui
file.
- Type:
"C:\python\Lib\site-packages\PyQt5\pyuic5.bat" -x Trial.ui -o trial_gui.py
for cases where PyQt5 is not a path variable. The path in quotes " " represents where the pyuic5.bat
file is.
This should work!
How do I profile memory usage in Python?
Disclosure:
- Applicable on Linux only
- Reports memory used by the current process as a whole, not individual functions within
But nice because of its simplicity:
import resource
def using(point=""):
usage=resource.getrusage(resource.RUSAGE_SELF)
return '''%s: usertime=%s systime=%s mem=%s mb
'''%(point,usage[0],usage[1],
usage[2]/1024.0 )
Just insert using("Label")
where you want to see what's going on. For example
print(using("before"))
wrk = ["wasting mem"] * 1000000
print(using("after"))
>>> before: usertime=2.117053 systime=1.703466 mem=53.97265625 mb
>>> after: usertime=2.12023 systime=1.70708 mem=60.8828125 mb
The import javax.servlet can't be resolved
You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar
in Tomcat's lib
folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.
If you want to leave the JAR in Tomcat's lib
folder:
- Right-click the project, click Properties.
- Choose Java Build Path.
- Click the Libraries tab
- Click Add External JARs...
- Browse to find
servlet-api.jar
and select it.
- Click OK to update the build path.
Or, if you copy the JAR into your project:
- Right-click the project, click Properties.
- Choose Java Build Path.
- Click Add JARs...
- Find
servlet-api.jar
in your project and select it.
- Click OK to update the build path.
Remove element of a regular array
As usual, I'm late to the party...
I'd like to add another option to the nice solutions list already present. =)
I would see this as a good opportunity for Extensions.
Reference:
http://msdn.microsoft.com/en-us/library/bb311042.aspx
So, we define some static class and in it, our Method.
After that, we can use our extended method willy-nilly. =)
using System;
namespace FunctionTesting {
// The class doesn't matter, as long as it's static
public static class SomeRandomClassWhoseNameDoesntMatter {
// Here's the actual method that extends arrays
public static T[] RemoveAt<T>( this T[] oArray, int idx ) {
T[] nArray = new T[oArray.Length - 1];
for( int i = 0; i < nArray.Length; ++i ) {
nArray[i] = ( i < idx ) ? oArray[i] : oArray[i + 1];
}
return nArray;
}
}
// Sample usage...
class Program {
static void Main( string[] args ) {
string[] myStrArray = { "Zero", "One", "Two", "Three" };
Console.WriteLine( String.Join( " ", myStrArray ) );
myStrArray = myStrArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myStrArray ) );
/* Output
* "Zero One Two Three"
* "Zero One Three"
*/
int[] myIntArray = { 0, 1, 2, 3 };
Console.WriteLine( String.Join( " ", myIntArray ) );
myIntArray = myIntArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myIntArray ) );
/* Output
* "0 1 2 3"
* "0 1 3"
*/
}
}
}
sed with literal string--not input file
You have a single quotes conflict, so use:
echo "A,B,C" | sed "s/,/','/g"
If using bash, you can do too (<<<
is a here-string
):
sed "s/,/','/g" <<< "A,B,C"
but not
sed "s/,/','/g" "A,B,C"
because sed
expect file(s) as argument(s)
EDIT:
if you use ksh or any other ones :
echo string | sed ...
How to build and fill pandas dataframe from for loop?
The simplest answer is what Paul H said:
d = []
for p in game.players.passing():
d.append(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
pd.DataFrame(d)
But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do it.
d = pd.DataFrame()
for p in game.players.passing():
temp = pd.DataFrame(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
d = pd.concat([d, temp])
How do I find where JDK is installed on my windows machine?
#!/bin/bash
if [[ $(which ${JAVA_HOME}/bin/java) ]]; then
exe="${JAVA_HOME}/bin/java"
elif [[ $(which java) ]]; then
exe="java"
else
echo "Java environment is not detected."
exit 1
fi
${exe} -version
For windows:
@echo off
if "%JAVA_HOME%" == "" goto nojavahome
echo Using JAVA_HOME : %JAVA_HOME%
"%JAVA_HOME%/bin/java.exe" -version
goto exit
:nojavahome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program.
goto exit
:exit
This link might help to explain how to find java executable from bash: http://srcode.org/2014/05/07/detect-java-executable/
How to remove duplicate values from a multi-dimensional array in PHP
if you need to eliminate duplicates on specific keys, such as a mysqli id, here's a simple funciton
function search_array_compact($data,$key){
$compact = [];
foreach($data as $row){
if(!in_array($row[$key],$compact)){
$compact[] = $row;
}
}
return $compact;
}
Bonus Points
You can pass an array of keys and add an outer foreach, but it will be 2x slower per additional key.
Placing an image to the top right corner - CSS
You can just do it like this:
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>
Are HTTPS headers encrypted?
HTTPS (HTTP over SSL) sends all HTTP content over a SSL tunel, so HTTP content and headers are encrypted as well.
Using ResourceManager
According to the MSDN documentation here, The basename argument specifies "The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named "MyApplication.MyResource.en-US.resources" is "MyApplication.MyResource"."
The ResourceManager will automatically try to retrieve the values for the current UI culture.
If you want to use a specific language, you'll need to set the current UI culture to the language you wish to use.
How to sort a List of objects by their date (java collections, List<Object>)
Do not access or modify the collection in the Comparator
. The comparator should be used only to determine which object is comes before another. The two objects that are to be compared are supplied as arguments.
Date
itself is comparable, so, using generics:
class MovieComparator implements Comparator<Movie> {
public int compare(Movie m1, Movie m2) {
//possibly check for nulls to avoid NullPointerException
return m1.getDate().compareTo(m2.getDate());
}
}
And do not instantiate the comparator on each sort. Use:
private static final MovieComparator comparator = new MovieComparator();
How do I get the dialer to open with phone number displayed?
Two ways to achieve it.
1) Need to start the dialer via code, without user interaction.
You need Action_Dial
,
use below code it will open Dialer with number specified
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
The 'tel:' prefix is required, otherwhise the following exception will be thrown:
java.lang.IllegalStateException: Could not execute method of the activity.
Action_Dial doesn't require any permission.
If you want to initiate the call directly without user's interaction , You can use action Intent.ACTION_CALL
. In this case, you must add the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
2) Need user to click on Phone_Number string and start the call.
android:autoLink="phone"
You need to use TextView with below property.
android:autoLink="phone"
android:linksClickable="true" a textView property
You don't need to use intent or to get permission via this way.
Convert cells(1,1) into "A1" and vice versa
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
How can I determine the URL that a local Git repository was originally cloned from?
With git remote show origin
you have to be in the projects directory. But if you want to determine the URLs from anywhere else
you could use:
cat <path2project>/.git/config | grep url
If you'll need this command often, you could define an alias in your .bashrc
or .bash_profile
with MacOS.
alias giturl='cat ./.git/config | grep url'
So you just need to call giturl
in the Git root folder in order to simply obtain its URL.
If you extend this alias like this
alias giturl='cat .git/config | grep -i url | cut -d'=' -f 2'
you get only the plain URL without the preceding
"url="
in
url=http://example.com/repo.git
you get more possibilities in its usage:
Example
On Mac you could call open $(giturl)
to open the URL in the standard browser.
Or chrome $(giturl)
to open it with the Chrome browser on Linux.
Open directory dialog
I'd suggest, to add in the nugget package:
Install-Package OpenDialog
Then the way to used it is:
Gat.Controls.OpenDialogView openDialog = new Gat.Controls.OpenDialogView();
Gat.Controls.OpenDialogViewModel vm = (Gat.Controls.OpenDialogViewModel)openDialog.DataContext;
vm.IsDirectoryChooser = true;
vm.Show();
WPFLabel.Text = vm.SelectedFilePath.ToString();
Here's the documentation:
http://opendialog.codeplex.com/documentation
Works for Files, files with filter, folders, etc
post ajax data to PHP and return data
So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:
$id = $_POST['id'];
function getVotes($id){
// call your database here
$query = ("SELECT votes FROM poll WHERE ID = $id");
$result = @mysql_query($query);
$row = mysql_fetch_row($result);
return $row->votes;
}
$votes = getVotes($id);
echo $votes;
This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.
Sum one number to every element in a list (or array) in Python
using List Comprehension:
>>> L = [1]*5
>>> [x+1 for x in L]
[2, 2, 2, 2, 2]
>>>
which roughly translates to using a for loop:
>>> newL = []
>>> for x in L:
... newL+=[x+1]
...
>>> newL
[2, 2, 2, 2, 2]
or using map:
>>> map(lambda x:x+1, L)
[2, 2, 2, 2, 2]
>>>
ImportError: no module named win32api
I had an identical problem, which I solved by restarting my Python editor and shell. I had installed pywin32
but the new modules were not picked up until the restarts.
If you've already done that, do a search in your Python installation for win32api
and you should find win32api.pyd
under ${PYTHON_HOME}\Lib\site-packages\win32
.
addEventListener not working in IE8
IE doesn't support addEventListener
until version 9, so you have to use attachEvent
, here's an example:
if (!someElement.addEventListener) {
_checkbox.attachEvent("onclick", setCheckedValues);
}
else {
_checkbox.addEventListener("click", setCheckedValues, false);
}
What does the DOCKER_HOST variable do?
Ok, I think I got it.
The client is the docker
command installed into OS X.
The host is the Boot2Docker VM.
The daemon is a background service running inside Boot2Docker.
This variable tells the client how to connect to the daemon.
When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST
set, so that's why docker
commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.
Failing to set it gives a message like this:
$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create:
dial unix /var/run/docker.sock: no such file or directory
One way to fix that would be to simply do this:
$ export DOCKER_HOST=tcp://192.168.59.103:2375
But, as pointed out by others, it's better to do this:
$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]
To spell out this possibly non-intuitive Bash command, running boot2docker shellinit
returns a set of Bash commands that set environment variables:
export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1
Hence running $(boot2docker shellinit)
generates those commands, and then runs them.
What's an object file in C?
An Object file is the compiled file itself. There is no difference between the two.
An executable file is formed by linking the Object files.
Object file contains low level instructions which can be understood by the CPU. That is why it is also called machine code.
This low level machine code is the binary representation of the instructions which you can also write directly using assembly language and then process the assembly language code (represented in English) into machine language (represented in Hex) using an assembler.
Here's a typical high level flow for this process for code in High Level Language such as C
--> goes through pre-processor
--> to give optimized code, still in C
--> goes through compiler
--> to give assembly code
--> goes through an assembler
--> to give code in machine language which is stored in OBJECT FILES
--> goes through Linker
--> to get an executable file.
This flow can have some variations for example most compilers can directly generate the machine language code, without going through an assembler. Similarly, they can do the pre-processing for you. Still, it is nice to break up the constituents for a better understanding.
Exporting result of select statement to CSV format in DB2
DBeaver allows you connect to a DB2 database, run a query, and export the result-set to a CSV file that can be opened and fine-tuned in MS Excel or LibreOffice Calc.
To do this, all you have to do (in DBeaver) is right-click on the results grid (after running the query) and select "Export Resultset" from the context-menu.
This produces the dialog below, where you can ultimately save the result-set to a file as CSV, XML, or HTML:
Using an authorization header with Fetch in React Native
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
...
let headers = {"Content-Type": "application/json"};
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/instruments/", {headers,})
.then(res => {
...
I was running apache.
What solved this problem for me was changing WSGIPassAuthorization
to 'On'
in wsgi.conf
.
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config
, I did this:
container_commands:
01wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
Reorder / reset auto increment primary key
in phpmyadmin
note: this will work if you delete last rows not middle rows.
goto your table-> click on operations menu-> goto table options->change AUTO_INCREMENT to that no from where you want to start.
your table autoincrement start from that no.
try it.
Get current location of user in Android without using GPS or internet
No, you cannot currently get location without using GPS or internet.
Location techniques based on WiFi, Cellular, or Bluetooth work with the help of a large database that is constantly being updated. A device scans for transmitter IDs and then sends these in a query through the internet to a service such as Google, Apple, or Skyhook. That service responds with a location based on previous wireless surveys from known locations. Without internet access, you have to have a local copy of such a database and keep this up to date. For global usage, this is very impractical.
Theoretically, a mobile provider could provide local data service only but no access to the internet, and then answer location queries from mobile devices. Mobile providers don't do this; no one wants to pay for this kind of restricted data access. If you have data service through your mobile provider, then you have internet access.
In short, using LocationManager.NETWORK_PROVIDER or android.hardware.location.network to get location requires use of the internet.
Using the last known position requires you to have had GPS or internet access very recently. If you just had internet, presumably you can adjust your position or settings to get internet again. If your device has not had GPS or internet access, the last known position feature will not help you.
Without GPS or internet, you could:
- Take pictures of the night sky and use the current time to estimate your location based on a star chart. This would probably require additional equipment to ensure that the angles for your pictures are correctly measured.
- Use an accelerometer to track location starting from a known position. The accumulation of error in this kind of approach makes it impractical for most situations.
vertical-align: middle doesn't work
Vertical align doesn't quite work the way you want it to. See: http://phrogz.net/css/vertical-align/index.html
This isn't pretty, but it WILL do what you want: Vertical align behaves as expected only when used in a table cell.
http://jsfiddle.net/e8ESb/6/
There are other alternatives: You can declare things as tables or table cells within CSS to make them behave as desired, for example. Margins and positioning can sometimes be played with to get the same effect. None of the solutions are terrible pretty, though.
ES6 export all values from object
Every answer requires changing of the import statements.
If you want to be able to use:
import {a} from './my-module' // a === 1
import * as myModule from './my-module' // myModule.a === 1
as in the question, and in your my-module
you have everything that you need to export in one object (which can be useful e.g. if you want to validate the exported values with Joi or JSON Schema) then your my-module
would have to be either:
let values = { a: 1, b: 2, c: 3 }
let {a, b, c} = values;
export {a, b, c};
Or:
let values = { a: 1, b: 2, c: 3 }
export let {a, b, c} = values;
Not pretty, but it compiles to what you need.
See: Babel example
Use PHP to convert PNG to JPG with compression?
Do this to convert safely a PNG to JPG with the transparency in white.
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
'pip install' fails for every package ("Could not find a version that satisfies the requirement")
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
What's happening:
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought
to upgrade to the latest pip (9.0.3) to connect to the Python Package
Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS <
10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times.
Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
jquery Ajax call - data parameters are not being passed to MVC Controller action
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
How do I create a self-signed certificate for code signing on Windows?
Roger's answer was very helpful.
I had a little trouble using it, though, and kept getting the red "Windows can't verify the publisher of this driver software" error dialog. The key was to install the test root certificate with
certutil -addstore Root Demo_CA.cer
which Roger's answer didn't quite cover.
Here is a batch file that worked for me (with my .inf file, not included).
It shows how to do it all from start to finish, with no GUI tools at all
(except for a few password prompts).
REM Demo of signing a printer driver with a self-signed test certificate.
REM Run as administrator (else devcon won't be able to try installing the driver)
REM Use a single 'x' as the password for all certificates for simplicity.
PATH %PATH%;"c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin";"c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin";c:\WinDDK\7600.16385.1\bin\selfsign;c:\WinDDK\7600.16385.1\Tools\devcon\amd64
makecert -r -pe -n "CN=Demo_CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature ^
-sv Demo_CA.pvk Demo_CA.cer
makecert -pe -n "CN=Demo_SPC" -a sha256 -cy end ^
-sky signature ^
-ic Demo_CA.cer -iv Demo_CA.pvk ^
-sv Demo_SPC.pvk Demo_SPC.cer
pvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^
-pfx Demo_SPC.pfx ^
-po x
inf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v
signtool sign /d "description" /du "www.yoyodyne.com" ^
/f Demo_SPC.pfx ^
/p x ^
/v driver\demoprinter.cat
certutil -addstore Root Demo_CA.cer
rem Needs administrator. If this command works, the driver is properly signed.
devcon install driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
rem Now uninstall the test driver and certificate.
devcon remove driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
certutil -delstore Root Demo_CA
jquery variable syntax
$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.
example:
var self = 'some string';
var $self = 'another string';
These are declared as two different variables. It's like putting underscore before private variables.
A somewhat popular pattern is:
var foo = 'some string';
var $foo = $('.foo');
That way, you know $foo is a cached jQuery object later on in the code.
How to fix committing to the wrong Git branch?
If the branch you wanted to apply your changes to already exists (branch develop, for example), follow the instructions that were provided by fotanus below, then:
git checkout develop
git rebase develop my_feature # applies changes to correct branch
git checkout develop # 'cuz rebasing will leave you on my_feature
git merge develop my_feature # will be a fast-forward
git branch -d my_feature
And obviously you could use tempbranch or any other branch name instead of my_feature if you wanted.
Also, if applicable, delay the stash pop (apply) until after you've merged at your target branch.
How to make a redirection on page load in JSF 1.x
Edit 2
I finally found a solution by implementing my forward action like that:
private void applyForward() {
FacesContext facesContext = FacesContext.getCurrentInstance();
// Find where to redirect the user.
String redirect = getTheFromOutCome();
// Change the Navigation context.
NavigationHandler myNav = facesContext.getApplication().getNavigationHandler();
myNav.handleNavigation(facesContext, null, redirect);
// Update the view root
UIViewRoot vr = facesContext.getViewRoot();
if (vr != null) {
// Get the URL where to redirect the user
String url = facesContext.getExternalContext().getRequestContextPath();
url = url + "/" + vr.getViewId().replace(".xhtml", ".jsf");
Object obj = facesContext.getExternalContext().getResponse();
if (obj instanceof HttpServletResponse) {
HttpServletResponse response = (HttpServletResponse) obj;
try {
// Redirect the user now.
response.sendRedirect(response.encodeURL(url));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It works (at least regarding my first tests), but I still don't like the way it is implemented... Any better idea?
Edit This solution does not work. Indeed, when the doForward()
function is called, the JSF lifecycle has already been started, and then recreate a new request is not possible.
One idea to solve this issue, but I don't really like it, is to force the doForward()
action during one of the setBindedInputHidden()
method:
private boolean actionDefined = false;
private boolean actionParamDefined = false;
public void setHiddenActionParam(HtmlInputHidden hiddenActionParam) {
this.hiddenActionParam = hiddenActionParam;
String actionParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("actionParam");
this.hiddenActionParam.setValue(actionParam);
actionParamDefined = true;
forwardAction();
}
public void setHiddenAction(HtmlInputHidden hiddenAction) {
this.hiddenAction = hiddenAction;
String action = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("action");
this.hiddenAction.setValue(action);
actionDefined = true;
forwardAction();
}
private void forwardAction() {
if (!actionDefined || !actionParamDefined) {
// As one of the inputHidden was not binded yet, we do nothing...
return;
}
// Now, both action and actionParam inputHidden are binded, we can execute the forward...
doForward(null);
}
This solution does not involve any Javascript call, and works does not work.
SSIS Excel Import Forcing Incorrect Column Type
I was banging my head against a wall with this issue for a while. In our environment, we consume price files from our suppliers in various formats, some of which have upward of a million records. This issue usually occurs where:
- The rows scanned by the OLEDB driver appear to contain numbers, but do contain mixed values later on in the record set, or
- Fields do contain only numbers, but the source has some formatted as text (usually Excel files).
The problem is that even if you set your external input column to the desired data type, the file gets scanned every time you run the package and is dynamically changed to whatever the OLEDB driver thinks the field should be.
Our source files typically contain field headers (text) and prices (numeric fields), which gives me an easy solution:
First step:
- Change your SQL statement to include the header fields. This forces
SSIS to see all fields as text, including the price fields.
For mixed fields:
- Your initial problem is solved because your fields are now text, but you still have a header row in your output.
- Prevent the header row from making it into your output by changing the SQL WHERE clause to exclude the header values e.g. "WHERE NOT([F4]='Price')"
For numeric fields:
Using the advanced editor for the OLE DB source, set the output
column for the price field (or any other numeric field) to a numeric
DataType. This causes any records that contain text in these fields
to fail, including the header record, but forces a conversion on
numeric values saved as text.
Set the Error Output to ignore failures on your numeric fields.
Alternatively, if you still need any errors on the numeric fields redirected, remove the header row by changing the SQL WHERE clause to exclude the header values then,
- Set the Error Output to redirect failures on this field.
Obviously this method only works where you have header fields, but hopefully this helps some of you.
How do I get the raw request body from the Request.Content object using .net 4 api endpoint
For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:
[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{
var body = new StreamReader(Request.Body);
//The modelbinder has already read the stream and need to reset the stream index
body.BaseStream.Seek(0, SeekOrigin.Begin);
var requestBody = body.ReadToEnd();
//etc, we use this for an audit trail
}
Splitting templated C++ classes into .hpp/.cpp files--is it possible?
It is not possible to write the implementation of a template class in a separate cpp file and compile. All the ways to do so, if anyone claims, are workarounds to mimic the usage of separate cpp file but practically if you intend to write a template class library and distribute it with header and lib files to hide the implementation, it is simply not possible.
To know why, let us look at the compilation process. The header files are never compiled. They are only preprocessed. The preprocessed code is then clubbed with the cpp file which is actually compiled. Now if the compiler has to generate the appropriate memory layout for the object it needs to know the data type of the template class.
Actually it must be understood that template class is not a class at all but a template for a class the declaration and definition of which is generated by the compiler at compile time after getting the information of the data type from the argument. As long as the memory layout cannot be created, the instructions for the method definition cannot be generated. Remember the first argument of the class method is the 'this' operator. All class methods are converted into individual methods with name mangling and the first parameter as the object which it operates on. The 'this' argument is which actually tells about size of the object which incase of template class is unavailable for the compiler unless the user instantiates the object with a valid type argument. In this case if you put the method definitions in a separate cpp file and try to compile it the object file itself will not be generated with the class information. The compilation will not fail, it would generate the object file but it won't generate any code for the template class in the object file. This is the reason why the linker is unable to find the symbols in the object files and the build fails.
Now what is the alternative to hide important implementation details? As we all know the main objective behind separating interface from implementation is hiding implementation details in binary form. This is where you must separate the data structures and algorithms. Your template classes must represent only data structures not the algorithms. This enables you to hide more valuable implementation details in separate non-templatized class libraries, the classes inside which would work on the template classes or just use them to hold data. The template class would actually contain less code to assign, get and set data. Rest of the work would be done by the algorithm classes.
I hope this discussion would be helpful.
Function or sub to add new row and data to table
Is this what you are looking for?
Option Explicit
Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal col As Integer)
Dim lLastRow As Long
Dim iHeader As Integer
With ActiveSheet.ListObjects(strTableName)
'find the last row of the list
lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.Count
'shift from an extra row if list has header
If .Sort.Header = xlYes Then
iHeader = 1
Else
iHeader = 0
End If
End With
'add the data a row after the end of the list
ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = strData
End Sub
It handles both cases whether you have header or not.
How to remove only 0 (Zero) values from column in excel 2010
Some of the other answers are great for removing zeros from existing data, but if you have a working sheet that is constantly changed and want to prevent zeros from ever appearing, I find it's easiest to use conditional formatting to make them invisible. Just select the range of cells you want to apply it to > conditional formatting > new rule.
Change the rule type to "format only cells that contain"
Cell value > equal to > 0.
Under "Format" change the text colour to white or whatever your background happens to be, and all cells which contain exactly zero will disappear.
Obviously this also works with any other value you want to make disappear.
Generate C# class from XML
I realise that this is a rather old post and you have probably moved on.
But I had the same problem as you so I decided to write my own program.
The problem with the "xml -> xsd -> classes" route for me was that it just generated
a lump of code that was completely unmaintainable and I ended up turfing it.
It is in no way elegant but it did the job for me.
You can get it here: Please make suggestions if you like it.
SimpleXmlToCode
Password Strength Meter
Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/
I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
var variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
Good passwords start to score around 60 or so, here's function to translate that in words:
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "strong";
if (score > 60)
return "good";
if (score >= 30)
return "weak";
return "";
}
you might want to tune this a bit but i found it working for me nicely
Most efficient way to see if an ArrayList contains an object in Java
I would say the simplest solution would be to wrap the object and delegate the contains call to a collection of the wrapped class. This is similar to the comparator but doesn't force you to sort the resulting collection, you can simply use ArrayList.contains().
public class Widget {
private String name;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
public abstract class EqualsHashcodeEnforcer<T> {
protected T wrapped;
public T getWrappedObject() {
return wrapped;
}
@Override
public boolean equals(Object obj) {
return equalsDelegate(obj);
}
@Override
public int hashCode() {
return hashCodeDelegate();
}
protected abstract boolean equalsDelegate(Object obj);
protected abstract int hashCodeDelegate();
}
public class WrappedWidget extends EqualsHashcodeEnforcer<Widget> {
@Override
protected boolean equalsDelegate(Object obj) {
if (obj == null) {
return false;
}
if (obj == getWrappedObject()) {
return true;
}
if (obj.getClass() != getWrappedObject().getClass()) {
return false;
}
Widget rhs = (Widget) obj;
return new EqualsBuilder().append(getWrappedObject().getName(),
rhs.getName()).append(getWrappedObject().getDesc(),
rhs.getDesc()).isEquals();
}
@Override
protected int hashCodeDelegate() {
return new HashCodeBuilder(121, 991).append(
getWrappedObject().getName()).append(
getWrappedObject().getDesc()).toHashCode();
}
}
How to use GROUP_CONCAT in a CONCAT in MySQL
First of all, I don't see the reason for having an ID that's not unique, but I guess it's an ID that connects to another table.
Second there is no need for subqueries, which beats up the server. You do this in one query, like this
SELECT id,GROUP_CONCAT(name, ':', value SEPARATOR "|") FROM sample GROUP BY id
You get fast and correct results, and you can split the result by that SEPARATOR "|". I always use this separator, because it's impossible to find it inside a string, therefor it's unique.
There is no problem having two A's, you identify only the value. Or you can have one more colum, with the letter, which is even better.
Like this :
SELECT id,GROUP_CONCAT(DISTINCT(name)), GROUP_CONCAT(value SEPARATOR "|") FROM sample GROUP BY name
Attempted to read or write protected memory. This is often an indication that other memory is corrupt
I had this problem recently when I changed the development server for a project. I was getting this error on the line of code where I declared a new OracleConnection variable.
After trying many things, including installing hotfixes, I tried changing the references Oracle.DataAccess and System.Data.OracleClient in the project and it worked!
When a project is moved to a new machine, I suggest you renew all the references added in that project.
Why does Math.Round(2.5) return 2 instead of 3?
This post has the answer you are looking for:
http://weblogs.asp.net/sfurman/archive/2003/03/07/3537.aspx
Basically this is what it says:
Return Value
The number nearest value with precision equal to digits. If value is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of value is less than digits, then value is returned unchanged.
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. If digits is zero, this kind of rounding is sometimes called rounding toward zero.
How to redirect output of an already running process
Screen
If process is running in a screen session you can use screen's log command to log the output of that window to a file:
Switch to the script's window, C-a H to log.
Now you can :
$ tail -f screenlog.2 | grep whatever
From screen's man page:
log [on|off]
Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.
I'm sure tmux has something similar as well.
How to use a Java8 lambda to sort a stream in reverse order?
Instead of all these complications, this simple step should do the trick for reverse sorting using Lambda .sorted(Comparator.reverseOrder())
Arrays.asList(files).stream()
.filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
.sorted(Comparator.reverseOrder()).skip(numOfNewestToLeave)
.forEach(item -> item.delete());
Converting a date in MySQL from string field
This:
STR_TO_DATE(t.datestring, '%d/%m/%Y')
...will convert the string into a datetime datatype. To be sure that it comes out in the format you desire, use DATE_FORMAT:
DATE_FORMAT(STR_TO_DATE(t.datestring, '%d/%m/%Y'), '%Y-%m-%d')
If you can't change the datatype on the original column, I suggest creating a view that uses the STR_TO_DATE
call to convert the string to a DateTime data type.
How to access property of anonymous type in C#?
If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.
var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();
Then you'll be able to access it like:
nodes.Any(n => n.Checked);
Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.
nodes.Add(new { Checked = false, /* etc */ });
Pandas column of lists, create a row for each list element
Trying to work through Roman Pekar's solution step-by-step to understand it better, I came up with my own solution, which uses melt
to avoid some of the confusing stacking and index resetting. I can't say that it's obviously a clearer solution though:
items_as_cols = df.apply(lambda x: pd.Series(x['samples']), axis=1)
# Keep original df index as a column so it's retained after melt
items_as_cols['orig_index'] = items_as_cols.index
melted_items = pd.melt(items_as_cols, id_vars='orig_index',
var_name='sample_num', value_name='sample')
melted_items.set_index('orig_index', inplace=True)
df.merge(melted_items, left_index=True, right_index=True)
Output (obviously we can drop the original samples column now):
samples subject trial_num sample_num sample
0 [1.84, 1.05, -0.66] 1 1 0 1.84
0 [1.84, 1.05, -0.66] 1 1 1 1.05
0 [1.84, 1.05, -0.66] 1 1 2 -0.66
1 [-0.24, -0.9, 0.65] 1 2 0 -0.24
1 [-0.24, -0.9, 0.65] 1 2 1 -0.90
1 [-0.24, -0.9, 0.65] 1 2 2 0.65
2 [1.15, -0.87, -1.1] 1 3 0 1.15
2 [1.15, -0.87, -1.1] 1 3 1 -0.87
2 [1.15, -0.87, -1.1] 1 3 2 -1.10
3 [-0.8, -0.62, -0.68] 2 1 0 -0.80
3 [-0.8, -0.62, -0.68] 2 1 1 -0.62
3 [-0.8, -0.62, -0.68] 2 1 2 -0.68
4 [0.91, -0.47, 1.43] 2 2 0 0.91
4 [0.91, -0.47, 1.43] 2 2 1 -0.47
4 [0.91, -0.47, 1.43] 2 2 2 1.43
5 [-1.14, -0.24, -0.91] 2 3 0 -1.14
5 [-1.14, -0.24, -0.91] 2 3 1 -0.24
5 [-1.14, -0.24, -0.91] 2 3 2 -0.91
java.lang.UnsupportedClassVersionError: Bad version number in .class file?
Another scenario where this could happen is when you are launching an instance of eclipse (for debug etc.) from a host eclipse - in which case, altering the project's level or JRE library on the project's classpath alone doesn't help. What matters is the JRE used to launch the target eclipse environment.
How to Deserialize XML document
The following snippet should do the trick (and you can ignore most of the serialization attributes):
public class Car
{
public string StockNumber { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
[XmlRootAttribute("Cars")]
public class CarCollection
{
[XmlElement("Car")]
public Car[] Cars { get; set; }
}
...
using (TextReader reader = new StreamReader(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
return (CarCollection) serializer.Deserialize(reader);
}
Largest and smallest number in an array
public int MinimumValue { get; private set; }
public int MaxmimumValue { get; private set; }
public void num()
{
int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
MaxmimumValue = array[0];
MinimumValue = array[0];
foreach (int num in array)
{
if (num > MaxmimumValue) MaxmimumValue = num;
if (num < MinimumValue) MinimumValue = num;
}
Console.WriteLine(MinimumValue);
Console.WriteLine(MaxmimumValue);
}
Run PostgreSQL queries from the command line
Open "SQL Shell (psql)" from your Applications (Mac).
Click enter for the default settings. Enter the password when prompted.
*) Type \?
for help
*) Type \conninfo
to see which user you are connected as.
*) Type \l
to see the list of Databases.
*) Connect to a database by \c <Name of DB>
, for example \c GeneDB1
You should see the key prompt change to the new DB, like so:
*) Now that you're in a given DB, you want to know the Schemas for that DB. The best command to do this is \dn
.
Other commands that also work (but not as good) are select schema_name from information_schema.schemata;
and select nspname from pg_catalog.pg_namespace;
:
-) Now that you have the Schemas, you want to know the tables in those Schemas. For that, you can use the dt
command. For example \dt "GeneSchema1".*
*) Now you can do your queries. For example:
*) Here is what the above DB, Schema, and Tables look like in pgAdmin:
Pandas DataFrame Groupby two columns and get counts
Inserting data into a pandas dataframe and providing column name.
import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df) #printing dataframe.
This is our printed data:
For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.
Like this:
df['COUNTER'] =1 #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)
OUTPUT:
How do I align views at the bottom of the screen?
In case you have a hierarchy like this:
<ScrollView>
|-- <RelativeLayout>
|-- <LinearLayout>
First, apply android:fillViewport="true"
to the ScrollView
and then apply android:layout_alignParentBottom="true"
to the LinearLayout
.
This worked for me perfectly.
<ScrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scrollbars="none"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/linearLayoutHorizontal"
android:layout_alignParentBottom="true">
</LinearLayout>
</RelativeLayout>
</ScrollView>
How do I completely remove root password
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
How do I check if a string is a number (float)?
I think your solution is fine, but there is a correct regexp implementation.
There does seem to be a lot of regexp hate towards these answers which I think is unjustified, regexps can be reasonably clean and correct and fast. It really depends on what you're trying to do. The original question was how can you "check if a string can be represented as a number (float)" (as per your title). Presumably you would want to use the numeric/float value once you've checked that it's valid, in which case your try/except makes a lot of sense. But if, for some reason, you just want to validate that a string is a number then a regex also works fine, but it's hard to get correct. I think most of the regex answers so far, for example, do not properly parse strings without an integer part (such as ".7") which is a float as far as python is concerned. And that's slightly tricky to check for in a single regex where the fractional portion is not required. I've included two regex to show this.
It does raise the interesting question as to what a "number" is. Do you include "inf" which is valid as a float in python? Or do you include numbers that are "numbers" but maybe can't be represented in python (such as numbers that are larger than the float max).
There's also ambiguities in how you parse numbers. For example, what about "--20"? Is this a "number"? Is this a legal way to represent "20"? Python will let you do "var = --20" and set it to 20 (though really this is because it treats it as an expression), but float("--20") does not work.
Anyways, without more info, here's a regex that I believe covers all the ints and floats as python parses them.
# Doesn't properly handle floats missing the integer part, such as ".7"
SIMPLE_FLOAT_REGEXP = re.compile(r'^[-+]?[0-9]+\.?[0-9]+([eE][-+]?[0-9]+)?$')
# Example "-12.34E+56" # sign (-)
# integer (12)
# mantissa (34)
# exponent (E+56)
# Should handle all floats
FLOAT_REGEXP = re.compile(r'^[-+]?([0-9]+|[0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?$')
# Example "-12.34E+56" # sign (-)
# integer (12)
# OR
# int/mantissa (12.34)
# exponent (E+56)
def is_float(str):
return True if FLOAT_REGEXP.match(str) else False
Some example test values:
True <- +42
True <- +42.42
False <- +42.42.22
True <- +42.42e22
True <- +42.42E-22
False <- +42.42e-22.8
True <- .42
False <- 42nope
Running the benchmarking code in @ron-reiter's answer shows that this regex is actually faster than the normal regex and is much faster at handling bad values than the exception, which makes some sense. Results:
check_regexp with good floats: 18.001921
check_regexp with bad floats: 17.861423
check_regexp with strings: 17.558862
check_correct_regexp with good floats: 11.04428
check_correct_regexp with bad floats: 8.71211
check_correct_regexp with strings: 8.144161
check_replace with good floats: 6.020597
check_replace with bad floats: 5.343049
check_replace with strings: 5.091642
check_exception with good floats: 5.201605
check_exception with bad floats: 23.921864
check_exception with strings: 23.755481
SQL Server, How to set auto increment after creating a table without data loss?
If you don't want to add a new column, and you can guarantee that your current int column is unique, you could select all of the data out into a temporary table, drop the table and recreate with the IDENTITY column specified. Then using SET IDENTITY INSERT ON
you can insert all of your data in the temporary table into the new table.
Padding zeros to the left in postgreSQL
The to_char()
function is there to format numbers:
select to_char(column_1, 'fm000') as column_2
from some_table;
The fm
prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000
simply defines the number of digits you want to have.
psql (9.3.5)
Type "help" for help.
postgres=> with sample_numbers (nr) as (
postgres(> values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
to_char
---------
001
011
100
(3 rows)
postgres=>
For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html
Merging multiple PDFs using iTextSharp in c#.net
Using iTextSharp.dll
protected void Page_Load(object sender, EventArgs e)
{
String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
}
}
Response.Write("Success");
document.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
IPython/Jupyter Problems saving notebook as PDF
For converting any Jupyter notebook to PDF, please follow the below instructions:
(Be inside Jupyter notebook):
On Mac OS:
command + P --> you will get a print dialog box --> change destination as PDF --> Click print
On Windows:
Ctrl + P --> you will get a print dialog box --> change destination as PDF --> Click print
If the above steps doesn't generate full PDF of the Jupyter notebook (probably because Chrome, some times, don't print all the outputs because Jupyter make a scroll for big outputs),
Try performing below steps for removing the auto scroll in the menu:-
Credits: @ÂngeloPolotto
In your Jupyter Notebook, click Cell on top of the jupyter notebook
Next click All output --> Toggle scrolling for removing auto scroll.
Rails 4 - passing variable to partial
You need the full render partial syntax if you are passing locals
<%= render @users, :locals => {:size => 30} %>
Becomes
<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>
Or to use the new hash syntax
<%= render partial: 'users', collection: @users, locals: {size: 30} %>
Which I think is much more readable
Fitting a Normal distribution to 1D data
You can use matplotlib
to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm
, as follows.
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
# Generate some data for this demonstration.
data = norm.rvs(10.0, 2.5, size=500)
# Fit a normal distribution to the data:
mu, std = norm.fit(data)
# Plot the histogram.
plt.hist(data, bins=25, density=True, alpha=0.6, color='g')
# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Fit results: mu = %.2f, std = %.2f" % (mu, std)
plt.title(title)
plt.show()
Here's the plot generated by the script:
HTML select form with option to enter custom value
If the datalist option doesn't fulfill your requirements, take a look to the Select2 library and the "Dynamic option creation"
_x000D_
_x000D_
$(".js-example-tags").select2({_x000D_
tags: true_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select class="form-control js-example-tags">_x000D_
<option selected="selected">orange</option>_x000D_
<option>white</option>_x000D_
<option>purple</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
Get input value from TextField in iOS alert in Swift
In Swift5 ans Xcode 10
Add two textfields with Save and Cancel actions and read TextFields text data
func alertWithTF() {
//Step : 1
let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
//Step : 2
let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
let textField = alert.textFields![0] as UITextField
let textField2 = alert.textFields![1] as UITextField
if textField.text != "" {
//Read TextFields text data
print(textField.text!)
print("TF 1 : \(textField.text!)")
} else {
print("TF 1 is Empty...")
}
if textField2.text != "" {
print(textField2.text!)
print("TF 2 : \(textField2.text!)")
} else {
print("TF 2 is Empty...")
}
}
//Step : 3
//For first TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your first name"
textField.textColor = .red
}
//For second TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your last name"
textField.textColor = .blue
}
//Step : 4
alert.addAction(save)
//Cancel action
let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
alert.addAction(cancel)
//OR single line action
//alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
self.present(alert, animated:true, completion: nil)
}
For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c
Number of regex matches
If you always need to know the length, and you just need the content of the match rather than the other info, you might as well use re.findall
. Otherwise, if you only need the length sometimes, you can use e.g.
matches = re.finditer(...)
...
matches = tuple(matches)
to store the iteration of the matches in a reusable tuple. Then just do len(matches)
.
Another option, if you just need to know the total count after doing whatever with the match objects, is to use
matches = enumerate(re.finditer(...))
which will return an (index, match)
pair for each of the original matches. So then you can just store the first element of each tuple in some variable.
But if you need the length first of all, and you need match objects as opposed to just the strings, you should just do
matches = tuple(re.finditer(...))
JavaScript/regex: Remove text between parentheses
Try / \([\s\S]*?\)/g
Where
(space) matches the character
(space) literally
\(
matches the character (
literally
[\s\S]
matches any character (\s
matches any whitespace character and \S
matches any non-whitespace character)
*?
matches between zero and unlimited times
\)
matches the character )
literally
g
matches globally
Code Example:
_x000D_
_x000D_
var str = "Hello, this is Mike (example)";
str = str.replace(/ \([\s\S]*?\)/g, '');
console.log(str);
_x000D_
.as-console-wrapper {top: 0}
_x000D_
_x000D_
_x000D_
bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date
I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change'
event by listening to a <form>
element (not the input itself) and none of the answers here worked for me. I tried to do:
$(form).on('change change.dp dp.change changeDate' function () {...})
And nothing would fire. I ended up listening to the focus
and blur
events and setting a custom property before/after on the element itself:
// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {
$('input[bs-datepicker]').on('focus', function (e){
e.currentTarget.focusValue = e.currentTarget.value;
});
$('input[bs-datepicker]').on('blur', function (e){
if (e.currentTarget.focusValue !== e.currentTarget.value) {
var event = new Event('change', { bubbles: true });
e.currentTarget.dispatchEvent(event);
}
});
})
This basically manually checks the value before and after the focus
and blur
and dispatches a new 'change'
event. The { bubbles: true }
bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if
you'll need to wrap the listeners in a $timeout
to make sure the digest happens first so all of your datepicker elements exist.
Hope this helps someone!
Font is not available to the JVM with Jasper Reports
I faced the issue with my web application based on Spring 3 and deployed on Weblogic 10.3 on Oracle Linux 6. The solution mentioned at the link did not work for me.
I had to take the following steps -
1. Copy the Arial*.ttf font files to JROCKIT_JAVA_HOME/jre/lib/fonts directory
2. Make entries of the fonts in fontconfig.properties.src
3. Restart the cluster from Weblogic console
filename.Arial=Arial.ttf
filename.Arial_Bold=Arial_Bold.ttf
filename.Arial_Italic=Arial_Italic.ttf
filename.Arial_Bold_Italic=Arial_Bold_Italic.ttf
Set Colorbar Range in matplotlib
Not sure if this is the most elegant solution (this is what I used), but you could scale your data to the range between 0 to 1 and then modify the colorbar:
import matplotlib as mpl
...
ax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.5)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cm,
norm=mpl.colors.Normalize(vmin=-0.5, vmax=1.5))
cbar.set_clim(-2.0, 2.0)
With the two different limits you can control the range and legend of the colorbar. In this example only the range between -0.5 to 1.5 is show in the bar, while the colormap covers -2 to 2 (so this could be your data range, which you record before the scaling).
So instead of scaling the colormap you scale your data and fit the colorbar to that.
Differences between ConstraintLayout and RelativeLayout
In addition to @dhaval-jivani answer.
I've updated the project github project to latest version of constraint layout v.1.1.0-beta3
I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1
Here results:
Fresh start (first screen opening after application launch)
Relative Layout
OnCreate: 123ms
Last preformDraw time - OnCreate time: 311.3ms
Constraint Layout
OnCreate: 120.3ms
Last preformDraw time - OnCreate time: 310ms
Besides that, I've checked performance test from this article , here the code
and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.
As a conclusion I agree with comments from the article:
Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?
As always: It depends
I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it.
For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.
How to check that an element is in a std::set?
I use
if(!my_set.count(that_element)) //Element is present...
;
But it is not as efficient as
if(my_set.find(that_element)!=my_set.end()) ....;
My version only saves my time in writing the code. I prefer it this way for competitive coding.
Get the IP address of the machine
I found the ioctl solution problematic on os x (which is POSIX compliant so should be similiar to linux). However getifaddress() will let you do the same thing easily, it works fine for me on os x 10.5 and should be the same below.
I've done a quick example below which will print all of the machine's IPv4 address, (you should also check the getifaddrs was successful ie returns 0).
I've updated it show IPv6 addresses too.
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
int main (int argc, const char * argv[]) {
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
} else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6
// is a valid IP6 Address
tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
}
}
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
return 0;
}
Why can't I use a list as a dict key in python?
According to the Python 2.7.2 documentation:
An object is hashable if it has a hash value which never changes
during its lifetime (it needs a hash() method), and can be
compared to other objects (it needs an eq() or cmp() method).
Hashable objects which compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set
member, because these data structures use the hash value internally.
All of Python’s immutable built-in objects are hashable, while no
mutable containers (such as lists or dictionaries) are. Objects which
are instances of user-defined classes are hashable by default; they
all compare unequal, and their hash value is their id().
A tuple is immutable in the sense that you cannot add, remove or replace its elements, but the elements themselves may be mutable. List's hash value depends on the hash values of its elements, and so it changes when you change the elements.
Using id's for list hashes would imply that all lists compare differently, which would be surprising and inconvenient.
What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?
Definitions:
- Frame Layout: This is designed to block out an area on the screen to display a single item.
- Linear Layout: A layout that arranges its children in a single column or a single row.
- Relative Layout: This layout is a view group that displays child views in relative positions.
- Table Layout: A layout that arranges its children into rows and columns.
More Information:
FrameLayout
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity
attribute.
Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).
RelativeLayout
A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.
(Current docs here)
TableLayout
A TableLayout consists of a number of TableRow
objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.
The width of a column is defined by the row with the widest cell in that column.
Note: Absolute Layout is deprecated.
Java: Sending Multiple Parameters to Method
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
TypeError: $.ajax(...) is not a function?
Double-check if you're using full-version of jquery and not some slim version.
I was using the jquery cdn-script link that comes with jquery. The problem is this one by default is slim.jquery.js which doesn't have the ajax
function in it. So, if you're using (copy-pasted from Bootstrap website) slim version jquery script link, use the full version instead.
That is to say use
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
instead of
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
Error: request entity too large
2016, none of the above worked for me until i explicity set the 'type' in addition to the 'limit' for bodyparser, example:
var app = express();
var jsonParser = bodyParser.json({limit:1024*1024*20, type:'application/json'});
var urlencodedParser = bodyParser.urlencoded({ extended:true,limit:1024*1024*20,type:'application/x-www-form-urlencoded' })
app.use(jsonParser);
app.use(urlencodedParser);
Add quotation at the start and end of each line in Notepad++
You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:
Find (in regular expression mode):
(.+)
Replace with:
"\1"
This adds the quotes:
"AliceBlue"
"AntiqueWhite"
"Aqua"
"Aquamarine"
"Azure"
"Beige"
"Bisque"
"Black"
"BlanchedAlmond"
Find (in extended mode):
\r\n
Replace with (with a space after the comma, not shown):
,
This converts the lines into a comma-separated list:
"AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
Add the var myArray =
assignment and braces manually:
var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
Java - Access is denied java.io.FileNotFoundException
I have search for this problem and i got the following answers:
"C:\Program Files\Apache-tomcat-7.0.69\"
remove the extra backslash (\
)
- Right click the log folder in tomcat folder and in security tab give this folder as a write-permission and then restart the net-beans as an run as administrator.
Your problem will be solved
asp.net mvc @Html.CheckBoxFor
CheckBoxFor
takes a bool
, you're passing a List<CheckBoxes>
to it. You'd need to do:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.DisplayFor(m => m.EmploymentType[i].Text)
}
Notice I've added a HiddenFor
for the Text
property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType
list is null
when the view is served. You'll need to populate that too, by doing this in your action method:
public ActionResult YourActionMethod()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBox>
{
new CheckBox { Text = "Fulltime" },
new CheckBox { Text = "Partly" },
new CheckBox { Text = "Contract" }
};
return View(model);
}
How to convert a String into an ArrayList?
I recommend use the StringTokenizer, is very efficient
List<String> list = new ArrayList<>();
StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
How to convert a double to long without casting?
The preferred approach should be:
Double.valueOf(d).longValue()
From the Double (Java Platform SE 7) documentation:
Double.valueOf(d)
Returns a Double
instance representing the specified double
value.
If a new Double
instance is not required, this method should
generally be used in preference to the constructor Double(double)
,
as this method is likely to yield significantly better space and time
performance by caching frequently requested values.
Wait until boolean value changes it state
Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.
Integer any = new Integer(0);
public synchronized boolean waitTillChange() {
any.wait();
return true;
}
public synchronized void change() {
any.notify();
}
How do I remove the blue styling of telephone numbers on iPhone/iOS?
I’ve been going back and forth between
1.
<a href="tel:5551231234">
2.
<meta name="format-detection" content="telephone=no">
Trying to make the same code work for desktop and iPhone. The problem was that if the first option is used and you click it from a desktop browser it gives an error message, and if the second one is used it disables the tab-to-call functionality on iPhone iOS5.
So I tried and tried and it turned out that iPhone treats the phone number as a special type of link that can be formatted with CSS as one. I wrapped the number in an address tag (it would work with any other HTML tag, just try avoiding <a>
tag) and styled it in CSS as
.myDiv address a {color:#FFF; font-style: normal; text-decoration:none;}
and it worked - in a desktop browser showed a plain text and in a Safari mobile showed as a link with the Call/Cancel window popping up on tab and without the default blue color and underlining.
Just be careful with the css rules applied to the number especially when using padding/margin.
pip or pip3 to install packages for Python 3?
If you had python 2.x and then installed python3, your pip will be pointing to pip3.
you can verify that by typing pip --version
which would be the same as pip3 --version
.
On your system you have now pip, pip2 and pip3.
If you want you can change pip to point to pip2 instead of pip3.
SSL certificate is not trusted - on mobile only
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
how to find my angular version in my project?
For Angular 1 or 2 (but not for Angular 4+):
You can also open the console and go to the element tab on the developer tools of whatever browser you use.
Or
Type angular.version to access the Javascript object that holds angular version.
For Angular 4+ There is are the number of ways as listed below :
Write below code in the command prompt/or in the terminal in the VS Code.
- ng version or ng --version (See the attachment for the reference.)
- ng v
- ng -v
In the terminal you can find the angular version as shown in the attached image :
- You can also open the console and go to the element tab on the developer tools of whatever browser you use. As displayed in the below image :
5.Find the package.json file, You will find all the installed packages and their version.
- declare the variable named as 'VERSION', Import the dependencies.
import { VERSION } from '@angular/core';
// To display the version in the console.
console.log(VERSION.full);
Set angular scope variable in markup
You can set values from html like this.
I don't think there is a direct solution from angular yet.
<div style="visibility: hidden;">{{activeTitle='home'}}</div>
How to turn on front flash light programmatically in Android?
Complete Code for android Flashlight App
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.user.flashlight"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OFF"
android:id="@+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="turnFlashOnOrOff" />
</RelativeLayout>
MainActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.security.Policy;
public class MainActivity extends AppCompatActivity {
Button button;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
getCamera();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
button.setText("ON");
} else {
turnOnFlash();
button.setText("OFF");
}
}
});
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
}catch (Exception e) {
}
}
}
private void turnOnFlash() {
if(!isFlashOn) {
if(camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
@Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
@Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
How to embed PDF file with responsive width
<object data="resume.pdf" type="application/pdf" width="100%" height="800px">
<p>It appears you don't have a PDF plugin for this browser.
No biggie... you can <a href="resume.pdf">click here to
download the PDF file.</a>
</p>
</object>
Git/GitHub can't push to master
I had this issue after upgrading the Git client, and suddenly my repository could not push.
I found that some old remote had the wrong value of url
, even through my currently active remote had the same value for url
and was working fine.
But there was also the pushurl
param, so adding it for the old remote worked for me:
Before:
[remote "origin"]
url = git://github.com/user/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
pushurl = [email protected]:user/repo.git
NOTE: This part of file "config" was unused for ages, but the new client complained about the wrong URL:
[remote "composer"]
url = git://github.com/user/repo.git
fetch = +refs/heads/*:refs/remotes/composer/*
So I added the pushurl
param to the old remote:
[remote "composer"]
url = git://github.com/user/repo.git
fetch = +refs/heads/*:refs/remotes/composer/*
pushurl = [email protected]:user/repo.git
To check if string contains particular word
Not as complicated as they say, check this you will not regret.
String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";
if ( sentence.toLowerCase().indexOf(search.toLowerCase()) != -1 ) {
System.out.println("I found the keyword");
} else {
System.out.println("not found");
}
You can change the toLowerCase()
if you want.
How to scp in Python?
You can use the package subprocess and the command call to use the scp command from the shell.
from subprocess import call
cmd = "scp user1@host1:files user2@host2:files"
call(cmd.split(" "))
How to write a cron that will run a script every day at midnight?
You can execute shell script in two ways,either by using cron job or by writing a shell script
Lets assume your script name is "yourscript.sh"
First check the user permission of the script.
use below command to check user permission of the script
ll script.sh
If the script is in root,then use below command
sudo crontab -e
Second if the script holds the user "ubuntu", then use below command
crontab -e
Add the following line in your crontab:-
55 23 * * * /path/to/yourscript.sh
Another way of doing this is to write a script and run it in the backgroud
Here is the script where you have to put your script name(eg:- youscript.sh) which is going to run at 23:55pm everyday
#!/bin/bash
while true
do
/home/modassir/yourscript.sh
sleep 1d
done
save it in a file (lets name it "every-day.sh")
sleep 1d - means it waits for one day and then it runs again.
now give the permission to your script.use below command:-
chmod +x every-day.sh
now, execute this shell script in the background by using "nohup".
This will keep executing the script even after you logout from your session.
use below command to execute the script.
nohup ./every-day.sh &
Note:- to run "yourscript.sh" at 23:55pm everyday,you have to execute "every-day.sh" script at exactly 23:55pm.
Best way to check if a URL is valid
Came across this article from 2012. It takes into account variables that may or may not be just plain URLs.
The author of the article, David Müeller, provides this function that he says, "...could be worth wile [sic]," along with some examples of filter_var
and its shortcomings.
/**
* Modified version of `filter_var`.
*
* @param mixed $url Could be a URL or possibly much more.
* @return bool
*/
function validate_url( $url ) {
$url = trim( $url );
return (
( strpos( $url, 'http://' ) === 0 || strpos( $url, 'https://' ) === 0 ) &&
filter_var(
$url,
FILTER_VALIDATE_URL,
FILTER_FLAG_SCHEME_REQUIRED || FILTER_FLAG_HOST_REQUIRED
) !== false
);
}
Unable to import path from django.urls
Python 2 doesn't support Django 2. On a Mac once you've installed Python 3 and Django 2 run the following command from shell to run your app while keeping path:
python3 manage.py runserver
Even if you have upgraded and are on a mac you will, by default, run Python 2 if you're entering the following command:
python manage.py runserver
The version of Django will then be wrong and you will see import errors for path
C# Interfaces. Implicit implementation versus Explicit implementation
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN: implicit and explicit interface implementations
jQuery change input text value
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
<meta charset="utf-8"> vs <meta http-equiv="Content-Type">
Another reason to go with the short one is that it matches other instances where you might specify a character set in markup. For example:
<script type="javascript" charset="UTF-8" src="/script.js"></script>
<p><a charset="UTF-8" href="http://example.com/">Example Site</a></p>
Consistency helps to reduce errors and make code more readable.
Note that the charset attribute is case-insensitive. You can use UTF-8 or utf-8, however UTF-8 is clearer, more readable, more accurate.
Also, there is absolutely no reason at all to use any value other than UTF-8 in the meta charset attribute or page header. UTF-8 is the default encoding for Web documents since HTML4 in 1999 and the only practical way to make modern Web pages.
Also you should not use HTML entities in UTF-8. Characters like the copyright symbol should be typed directly. The only entities you should use are for the 5 reserved markup characters: less than, greater than, ampersand, prime, double prime. Entities need an HTML parser, which you may not always want to use going forward, they introduce errors, make your code less readable, increase your file sizes, and sometimes decode incorrectly in various browsers depending on which entities you used. Learn how to type/insert copyright, trademark, open quote, close quote, apostrophe, em dash, en dash, bullet, Euro, and any other characters you encounter in your content, and use those actual characters in your code. The Mac has a Character Viewer that you can turn on in the Keyboard System Preference, and you can find and then drag and drop the characters you need, or use the matching Keyboard Viewer to see which keys to type. For example, trademark is Option+2. UTF-8 contains all of the characters and symbols from every written human language. So there is no excuse for using -- instead of an em dash. It is not a bad idea to learn the rules of punctuation and typography also ... for example, knowing that a period goes inside a close quote, not outside.
Using a tag for something like content-type and encoding is highly
ironic, since without knowing those things, you couldn't parse the file
to get the value of the meta tag.
No, that is not true. The browser starts out parsing the file as the browser's default encoding, either UTF-8 or ISO-8859-1. Since US-ASCII is a subset of both ISO-8859-1 and UTF-8, the browser can read just fine either way ... it is the same. When the browser encounters the meta charset tag, if the encoding is different than what the browser is already using, the browser reloads the page in the specified encoding. That is why we put the meta charset tag at the top, right after the head tag, before anything else, even the title. That way you can use UTF-8 characters in your title.
You must save your file(s) in UTF-8 encoding without BOM
That is not strictly true. If you only have US-ASCII characters in your document, you can Save it as US-ASCII and serve it as UTF-8, because it is a subset. But if there are Unicode characters, you are correct, you must Save as UTF-8 without BOM.
If you want a good text editor that will save your files
in UTF-8, I recommend Notepad++.
On the Mac, use Bare Bones TextWrangler (free) from Mac App Store, or Bare Bones BBEdit which is at Mac App Store for $39.99 ... very cheap for such a great tool. In either app, there is a menu at the bottom of the document window where you specify the document encoding and you can easily choose "UTF-8 no BOM". And of course you can set that as the default for new documents in Preferences.
But if your Webserver serves the encoding in the HTTP header,
which is recommended, both [meta tags] are needless.
That is incorrect. You should of course set the encoding in the HTTP header, but you should also set it in the meta charset attribute so that the page can be Saved by the user, out of the browser onto local storage and then Opened again later, in which case the only indication of the encoding that will be present is the meta charset attribute. You should also set a base tag for the same reason ... on the server, the base tag is unnecessary, but when opened from local storage, the base tag enables the page to work as if it is on the server, with all the assets in place and so on, no broken links.
AddDefaultCharset UTF-8
Or you can just change the encoding of particular file types like so:
AddType text/html;charset=utf-8 html
A tip for serving both UTF-8 and Latin-1 (ISO-8859-1) files is to give the UTF-8 files a "text" extension and Latin-1 files "txt."
AddType text/plain;charset=iso-8859-1 txt
AddType text/plain;charset=utf-8 text
Finally, consider Saving your documents with Unix line endings, not legacy DOS or (classic) Mac line endings, which don't help and may hurt, especially down the line as we get further and further from those legacy systems. An HTML document with valid HTML5, UTF-8 encoding, and Unix line endings is a job well done. You can share and edit and store and read and recover and rely on that document in many contexts. It's lingua franca. It's digital paper.
What is the 'pythonic' equivalent to the 'fold' function from functional programming?
I may be quite late to the party, but we can create custom foldr
using simple lambda calculus and curried function. Here is my implementation of foldr in python.
def foldr(func):
def accumulator(acc):
def listFunc(l):
if l:
x = l[0]
xs = l[1:]
return func(x)(foldr(func)(acc)(xs))
else:
return acc
return listFunc
return accumulator
def curried_add(x):
def inner(y):
return x + y
return inner
def curried_mult(x):
def inner(y):
return x * y
return inner
print foldr(curried_add)(0)(range(1, 6))
print foldr(curried_mult)(1)(range(1, 6))
Even though the implementation is recursive (might be slow), it will print the values 15
and 120
respectively
Java sending and receiving file (byte[]) over sockets
Adding up on EJP's answer; use this for more fluidity.
Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:
int count;
byte[] bytes = new byte[4096];
try {
while ((count = is.read(bytes)) > 0) {
System.out.println(count);
bos.write(bytes, 0, count);
}
} catch ( Exception e )
{
//It will land here....
}
// Then continue from here
EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!
Hope this post solves any of your issues
Formula to determine brightness of RGB color
I have made comparison of the three algorithms in the accepted answer. I generated colors in cycle where only about every 400th color was used. Each color is represented by 2x2 pixels, colors are sorted from darkest to lightest (left to right, top to bottom).
1st picture - Luminance (relative)
0.2126 * R + 0.7152 * G + 0.0722 * B
2nd picture - http://www.w3.org/TR/AERT#color-contrast
0.299 * R + 0.587 * G + 0.114 * B
3rd picture - HSP Color Model
sqrt(0.299 * R^2 + 0.587 * G^2 + 0.114 * B^2)
4th picture - WCAG 2.0 SC 1.4.3 relative luminance and contrast ratio formula (see @Synchro's answer here)
Pattern can be sometimes spotted on 1st and 2nd picture depending on the number of colors in one row. I never spotted any pattern on picture from 3rd or 4th algorithm.
If i had to choose i would go with algorithm number 3 since its much easier to implement and its about 33% faster than the 4th.
PersistenceContext EntityManager injection NullPointerException
An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.
Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).
Here's an example of injecting an EntityManagerFactory:
package com.test.service;
import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;
@Path("/service")
public class TestService {
@PersistenceUnit(unitName = "test")
private EntityManagerFactory entityManagerFactory;
@GET
@Path("/get")
@Produces("application/json")
public List get() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
return entityManager.createQuery("from TestEntity").getResultList();
} finally {
entityManager.close();
}
}
}
The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.
Related question:
Inject an EJB into JAX-RS (RESTful service)
Can I run Keras model on gpu?
Sure. I suppose that you have already installed TensorFlow for GPU.
You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.
import keras
import tensorflow as tf
config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.
lvalue required as left operand of assignment
You cannot assign an rvalue to an rvalue.
if (strcmp("hello", "hello") = 0)
is wrong. Suggestions:
if (strcmp("hello", "hello") == 0)
^
=
is the assign operator.
==
is the equal to operator.
I know many new programmers are confused with this fact.
Cannot connect to repo with TortoiseSVN
I was struggling with exactly the same issue. I got my work laptop replaced and suddenly I stopped being able to connect to server. Strangely, initially I was getting errors only blocking me from committing, like:
Command : Commit
Error : Commit failed (details follow):
Error : MKACTIVITY of '/svn//!svn/act/c511b853-23b4-db4a-8991-0bc689a63353':
Error : Could not parse response status line (http://*.**.com)
Completed! :
When I moved to work in another branch (the SVN server was accessible with no issues for everyone on both branches, who has proper security), I started getting error like:
Command : Checkout from http://.com/svn/fineos//trunk, revision HEAD, Fully recursive, Externals included
Error : Unable to connect to a repository at URL
Error : 'http://**.com/svn/fineos*/*/trunk'
Error : OPTIONS of
Error : 'http://*.com/svn/fineos*/*/trunk': could
Error : not connect to server (http://*.com)
Completed! :
Note: In each case, I could access repository through browser and it was working for everyone else, so obviously it wasn't network or repository issue.
This what worked for me was to uninstall Tortoise client, then remove Tortoise cache folder from Local and Roaming folders under C:\Users\user\AppData.
Additionally I renamed TortoiseSVN node in Windows registry so the old configuration cannot be found.
Then after reinstallation, client connected to repo beautifully. I am not sure if both steps are required, maybe just changing registry will be enough, I will leave that to you to confirm.
Apologies for long response, but as I haven't seen response to this problem after googling for longer while, I thought that may be helpful for different cases.
How to add a border just on the top side of a UIView
I took both Adam Waite's and Pauls answers and combined them. I also added the possibility to pipe the selected edges together, so you need to call only one function like so:
[self.view addBordersToEdge:(UIRectEdgeLeft|UIRectEdgeRight)
withColor:[UIColor grayColor]
andWidth:1.0];
or so:
[self.view addBordersToEdge:(UIRectEdgeAll)
withColor:[UIColor grayColor]
andWidth:1.0];
What you need to implement is a category on UIView as suggested in other answers with the following implementation:
- (void)addBordersToEdge:(UIRectEdge)edge withColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
if (edge & UIRectEdgeTop) {
UIView *border = [UIView new];
border.backgroundColor = color;
[border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
[self addSubview:border];
}
if (edge & UIRectEdgeLeft) {
UIView *border = [UIView new];
border.backgroundColor = color;
border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
[border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
[self addSubview:border];
}
if (edge & UIRectEdgeBottom) {
UIView *border = [UIView new];
border.backgroundColor = color;
[border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
[self addSubview:border];
}
if (edge & UIRectEdgeRight) {
UIView *border = [UIView new];
border.backgroundColor = color;
[border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
[self addSubview:border];
}
}
What is the difference between Nexus and Maven?
This has a good general description:
https://gephi.wordpress.com/tag/maven/
Let me make a few statement that can put the difference in focus:
We migrated our code base from Ant to Maven
All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.
Basic functionalities of a repository manager like Sonatype are:
- Managing project dependencies,
- Artifacts & Metadata,
- Proxying external repositories
- and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.
What is the purpose of class methods?
I think the most clear answer is AmanKow's one. It boils down to how u want to organize your code. You can write everything as module level functions which are wrapped in the namespace of the module i.e
module.py (file 1)
---------
def f1() : pass
def f2() : pass
def f3() : pass
usage.py (file 2)
--------
from module import *
f1()
f2()
f3()
def f4():pass
def f5():pass
usage1.py (file 3)
-------------------
from usage import f4,f5
f4()
f5()
The above procedural code is not well organized, as you can see after only 3 modules it gets confusing, what is each method do ? You can use long descriptive names for functions(like in java) but still your code gets unmanageable very quick.
The object oriented way is to break down your code into manageable blocks i.e Classes & objects and functions can be associated with objects instances or with classes.
With class functions you gain another level of division in your code compared with module level functions.
So you can group related functions within a class to make them more specific to a task that you assigned to that class. For example you can create a file utility class :
class FileUtil ():
def copy(source,dest):pass
def move(source,dest):pass
def copyDir(source,dest):pass
def moveDir(source,dest):pass
//usage
FileUtil.copy("1.txt","2.txt")
FileUtil.moveDir("dir1","dir2")
This way is more flexible and more maintainable, you group functions together and its more obvious to what each function do. Also you prevent name conflicts, for example the function copy may exist in another imported module(for example network copy) that you use in your code, so when you use the full name FileUtil.copy() you remove the problem and both copy functions can be used side by side.
Difference between two lists
I think important to emphasize - using Except method will return you items who are in the first without the items in the second one only. It does not return those elements in second that do not appear in first.
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list3 = list1.Except(list2).ToList(); //list3 contains only 1, 2
But if you want get real difference between two lists:
Items who are in the first without the items in the second one
and items who are in the second without the items in the first one.
You need using Except twice:
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list3 = list1.Except(list2); //list3 contains only 1, 2
var list4 = list2.Except(list1); //list4 contains only 6, 7
var resultList = list3.Concat(list4).ToList(); //resultList contains 1, 2, 6, 7
Or you can use SymmetricExceptWith method of HashSet. But it changes the set on which called:
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list1Set = list1.ToHashSet(); //.net framework 4.7.2 and .net core 2.0 and above otherwise new HashSet(list1)
list1Set.SymmetricExceptWith(list2);
var resultList = list1Set.ToList(); //resultList contains 1, 2, 6, 7
Top 5 time-consuming SQL queries in Oracle
While searching I got the following query which does the job with one assumption(query execution time >6 seconds)
SELECT username, sql_text, sofar, totalwork, units
FROM v$sql,v$session_longops
WHERE sql_address = address AND sql_hash_value = hash_value
ORDER BY address, hash_value, child_number;
I think above query will list the details for current user.
Comments are welcome!!
Accessing Google Account Id /username via Android
I've ran into the same issue and these two links solved for me:
The first one is this one: How do I retrieve the logged in Google account on android phones?
Which presents the code for retrieving the accounts associated with the phone. Basically you will need something like this:
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
And to add the permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"></uses-permission>
Additionally, if you are using the Emulator the following link will help you to set it up with an account : Android Emulator - Trouble creating user accounts
Basically, it says that you must create an android device based on a API Level and not the SDK Version (like is usually done).
Using jQuery To Get Size of Viewport
1. Response to the main question
The script $(window).height()
does work well (showing the viewport's height and not the document with scrolling height), BUT it needs that you put correctly the doctype tag in your document, for example these doctypes:
For HTML 5:
<!DOCTYPE html>
For transitional HTML4:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Probably the default doctype assumed by some browsers is such, that $(window).height()
takes the document's height and not the browser's height. With the doctype specification, it's satisfactorily solved, and I'm pretty sure you peps will avoid the "changing scroll-overflow to hidden and then back", which is, I'm sorry, a bit dirty trick, specially if you don't document it on the code for future programmer's usage.
2. An ADDITIONAL tip, note aside:
Moreover, if you are doing a script, you can invent tests to help programmers in using your libraries, let me invent a couple:
$(document).ready(function() {
if(typeof $=='undefined') {
alert("PROGRAMMER'S Error: you haven't called JQuery library");
} else if (typeof $.ui=='undefined') {
alert("PROGRAMMER'S Error: you haven't installed the UI Jquery library");
}
if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
alert("ERROR, check your doctype, the calculated heights are not what you might expect");
}
});
EDIT: about the part 2, "An ADDITIONAL tip, note aside":
@Machiel, in yesterday's comment (2014-09-04), was UTTERLY right: the check of the $ can not be inside the ready event of Jquery, because we are, as he pointed out, assuming $ is already defined. THANKS FOR POINTING THAT OUT, and do please the rest of you readers correct this, if you used it in your scripts. My suggestion is: in your libraries put an "install_script()" function which initializes the library (put any reference to $ inside such init function, including the declaration of ready()) and AT THE BEGINNING of such "install_script()" function, check if the $ is defined, but make everything independent of JQuery, so your library can "diagnose itself" when JQuery is not yet defined. I prefer this method rather than forcing the automatic creation of a JQuery bringing it from a CDN. Those are tiny notes aside for helping out other programmers. I think that people who make libraries must be richer in the feedback to potential programmer's mistakes. For example, Google Apis need an aside manual to understand the error messages. That's absurd, to need external documentation for some tiny mistakes that don't need you to go and search a manual or a specification. The library must be SELF-DOCUMENTED. I write code even taking care of the mistakes I might commit even six months from now, and it still tries to be a clean and not-repetitive code, already-written-to-prevent-future-developer-mistakes.
redirect while passing arguments
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session
(cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
@app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How to run Unix shell script from Java code?
Yes it is possible to do so. This worked out for me.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.InputStream;
public static void readBashScript() {
try {
Process proc = Runtime.getRuntime().exec("/home/destino/workspace/JavaProject/listing.sh /"); //Whatever you want to execute
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
How to limit the maximum value of a numeric field in a Django model?
You can use Django's built-in validators—
from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator
class CoolModelBro(Model):
limited_integer_field = IntegerField(
default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
]
)
Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm
since the forms will do that automatically.
c# - How to get sum of the values from List?
You can use LINQ for this
var list = new List<int>();
var sum = list.Sum();
and for a List of strings like Roy Dictus said you have to convert
list.Sum(str => Convert.ToInt32(str));
How to create a drop shadow only on one side of an element?
You can do that like this:
General syntax:
selector {
box-shadow: topBoxShadow, bottomBoxShadow, rightBoxShadow, leftBoxShadow
}
Example: we want to make only a bottom box shadow with red color,
so to do that we have to set all the sides options where we have to set the bottom box shadow options and set all the others as empty as follow:
.box {
-moz-box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
-o-box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
-webkit-box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
}