I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.
Just move the var inside the "name" block:
- name: Download apache
vars:
url: czxcxz
shell: wget {{url}}
The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)
You can send an OPTIONS request with curl like this:
curl -i -X OPTIONS http://example.org/path
You may also use -v
instead of -i
to see more output.
To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:
curl -i --request-target "*" -X OPTIONS http://example.org
I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.
Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete
So basically you have to return a promise
when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $q
service/directive/controller where you issue your HTTP Request.
Example:
function getMyHttpData(){
var deferred = $q.defer();
$http.jsonp(request).success(function(data){
// the promise gets resolved with the data from HTTP
deferred.resolve(data);
});
// return the promise
return deferred.promise;
}
I hope this helps.
A class is a blueprint which you use to create objects. An object is an instance of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class.
This is easy to understand if you look at an example. For example, suppose you have a class House
. Your own house is an object and is an instance of class House
. Your sister's house is another object (another instance of class House
).
// Class House describes what a house is
class House {
// ...
}
// You can use class House to create objects (instances of class House)
House myHouse = new House();
House sistersHouse = new House();
The class House
describes the concept of what a house is, and there are specific, concrete houses which are objects and instances of class House
.
Note: This is exactly the same in Java as in all object oriented programming languages.
This is the fastest method I have created that doesn't use the prototype, so it will maintain hasOwnProperty in the new object.
The solution is to iterate the top level properties of the original object, make two copies, delete each property from the original and then reset the original object and return the new copy. It only has to iterate as many times as top level properties. This saves all the if
conditions to check if each property is a function, object, string, etc., and doesn't have to iterate each descendant property.
The only drawback is that the original object must be supplied with its original created namespace, in order to reset it.
copyDeleteAndReset:function(namespace,strObjName){
var obj = namespace[strObjName],
objNew = {},objOrig = {};
for(i in obj){
if(obj.hasOwnProperty(i)){
objNew[i] = objOrig[i] = obj[i];
delete obj[i];
}
}
namespace[strObjName] = objOrig;
return objNew;
}
var namespace = {};
namespace.objOrig = {
'0':{
innerObj:{a:0,b:1,c:2}
}
}
var objNew = copyDeleteAndReset(namespace,'objOrig');
objNew['0'] = 'NEW VALUE';
console.log(objNew['0']) === 'NEW VALUE';
console.log(namespace.objOrig['0']) === innerObj:{a:0,b:1,c:2};
You can remove the blue outline by using outline: none
.
However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.
Check out: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#navigation-mechanisms-focus-visible. More reading here: http://outlinenone.com
Use the static Double.isNaN(double)
method, or your Double
's .isNaN()
method.
// 1. static method
if (Double.isNaN(doubleValue)) {
...
}
// 2. object's method
if (doubleObject.isNaN()) {
...
}
Simply doing:
if (var == Double.NaN) {
...
}
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
Yes, as @ggkmath said, sometimes a good old restart is exactly what you need. Like when "contact the author and have him rewrite the app, meanwhile wait" is not an option.
This happens when an application is not written (yet) in a way that it can handle restarts of the underlying database.
If you're dealing with a text file & based on linux system, you could use the linux commands.
For me, this worked well!
import commands
def read_line(path, line=1):
return commands.getoutput('head -%s %s | tail -1' % (line, path))
line_to_jump = 141978
read_line("path_to_large_text_file", line_to_jump)
Check if there is a space character between the previous path and the next:
Incorrect:
c:\path1; c:\Maven\bin\; c:\path2\
Correct:
c:\path1;c:\Maven\bin\;c:\path2\
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.
That said, please try the following filter and see if you're getting the entries that you think you should be getting:
dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7
I was having a similar issue with formatting CardViews in a recylerView.
I got this simple solution working, not sure if it's the best solution, but it worked for me.
mv_cardView.getBackground().setTint(Color.BLUE)
It gets the background Drawable of the cardView and tints it.
Task.Delay(0)
as in the accepted answer was a good approach, as it is a cached copy of a completed Task
.
As of 4.6 there's now Task.CompletedTask
which is more explicit in its purpose, but not only does Task.Delay(0)
still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask
.
The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0)
was better than the accepted answer.
I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.
Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.
If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:
N = Log60(t * 10,000)
where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).
1 minute: 3.2
5 minute: 3.6
30 minutes: 4.1
2 hours: 4.4
3 days: 5.2
So given a 3 days we'd be able to crack the password if it's 5 characters long.
This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.
Let's clear up some misconceptions:
The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.
SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.
update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.
The accepted answer as of September 2014 is incorrect and dangerously wrong:
In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.
The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.
The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...
That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...
Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.
When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea
folder.
Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.
Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.
Note: If you are using git or some version control system, you might want to set this folder "ignore".
Example - for git, add this directory to .gitignore
. This way, the application is not IDE-specific.
It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5))
is similar to [math.e**x for x in range(5)]
.
I have experimented many of the backslash escape characters. \n
which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.
Code:
#include <stdio.h>
int main(void){
printf("Hello World!");
printf("Goodbye \a");
printf("Hi \b");
printf("Yo\f");
printf("What? \t");
printf("pewpew");
return 0;
}
There's no such concept as an integer with padding. How many legs do you have - 2, 02 or 002? They're the same number. Indeed, even the "2" part isn't really part of the number, it's only relevant in the decimal representation.
If you need padding, that suggests you're talking about the textual representation of a number... i.e. a string.
You can achieve that using string formatting options, e.g.
string text = value.ToString("0000000");
or
string text = value.ToString("D7");
This doesn't remove whitespace automatically before a commit, but it is pretty easy to effect. I put the following perl script in a file named git-wsf (git whitespace fix) in a dir in $PATH so I can:
git wsf | sh
and it removes all whitespace only from lines of files that git reports as a diff.
#! /bin/sh
git diff --check | perl -x $0
exit
#! /usr/bin/perl
use strict;
my %stuff;
while (<>) {
if (/trailing whitespace./) {
my ($file,$line) = split(/:/);
push @{$stuff{$file}},$line;
}
}
while (my ($file, $line) = each %stuff) {
printf "ex %s <<EOT\n", $file;
for (@$line) {
printf '%ds/ *$//'."\n", $_;
}
print "wq\nEOT\n";
}
Mockito has limitations testing final, static, and private methods.
with jMockit testing library, you can do few stuff very easy and straight-forward as below:
Mock constructor of a java.io.File class:
new MockUp<File>(){
@Mock
public void $init(String pathname){
System.out.println(pathname);
// or do whatever you want
}
};
Mock a static method:
In my case error caused next. I've tried to execute commands globally i.e outside of any target.
UPD. To run command globally one must be properly formed. For example command
ln -sf ../../user/curl/$SRC_NAME ./$SRC_NAME
would become:
$(shell ln -sf ../../user/curl/$(SRC_NAME) ./$(SRC_NAME))
As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.
SELECT name, GROUP_CONCAT( section )
FROM `tmp`
GROUP BY name
String to JSON using Jackson
with com.fasterxml.jackson.databind
:
Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Simple code exmpl
*/
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();
In C# (Sharp), you can make an empty character as '\0'. Maybe you can do this:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '\0')
Search on google or surf on the interent and check if javascript allows you to make empty characters, like C# does. If yes, then learn how to do it, and maybe the replaceAt function will work at last, and you'll achieve what you want!
Finally that 'r' character will be removed!
The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.
Just update the node you have selected and .Save() that XmlDocument.
MacOS X specific:
C11 is supported, so you can just call aligned_malloc (16, size).
MacOS X picks code that is optimised for individual processors at boot time for memset, memcpy and memmove and that code uses tricks that you've never heard of to make it fast. 99% chance that memset runs faster than any hand-written memset16 which makes the whole question pointless.
If you want a 100% portable solution, before C11 there is none. Because there is no portable way to test alignment of a pointer. If it doesn't have to be 100% portable, you can use
char* p = malloc (size + 15);
p += (- (unsigned int) p) % 16;
This assumes that the alignment of a pointer is stored in the lowest bits when converting a pointer to unsigned int. Converting to unsigned int loses information and is implementation defined, but that doesn't matter because we don't convert the result back to a pointer.
The horrible part is of course that the original pointer must be saved somewhere to call free () with it. So all in all I would really doubt the wisdom of this design.
I really do not see any way to really get to the number of values in an enumeration in C++. Any of the before mention solution work as long as you do not define the value of your enumerations if you define you value that you might run into situations where you either create arrays too big or too small
enum example{ test1 = -2, test2 = -1, test3 = 0, test4 = 1, test5 = 2 }
in this about examples the result would create a array of 3 items when you need an array of 5 items
enum example2{ test1 , test2 , test3 , test4 , test5 = 301 }
in this about examples the result would create a array of 301 items when you need an array of 5 items
The best way to solve this problem in the general case would be to iterate through your enumerations but that is not in the standard yet as far as I know
Just use this one, You have to use more when they are classes.
SELECT Url='',
p.ArtNo,
p.[Description],
p.Specification,
CASE
WHEN 1 = 1 or 1 = 1
THEN 1
WHEN 2 = 2
THEN 2
WHEN 3 = 3
THEN 3
ELSE 0
END as Qty,
p.NetPrice,
[Status] = 0
FROM Product p (NOLOCK)
You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.
Your session will last 1440 seconds which is 24 minutes (default).
For ssh
you can use sshpass
: sshpass -p yourpassphrase ssh user@host
.
You just need to download sshpass first :)
$ apt-get install sshpass
$ sshpass -p 'password' ssh username@server
Empty
refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty
then it would return true.
IsEmpty
refers to no value being initialized.
In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty
. If you want to see if something is currently in its default value then use Empty
.
Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):
Public oConn As ADODB.Connection
Sub MySqlInit()
If oConn Is Nothing Then
Dim str As String
str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
Set oConn = New ADODB.Connection
oConn.Open str
End If
End Sub
The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />
EF doesn't support unique columns except keys. If you are using EF Migrations you can force EF to create unique index on UserName
column (in migration code, not by any annotation) but the uniqueness will be enforced only in the database. If you try to save duplicate value you will have to catch exception (constraint violation) fired by the database.
IN SWIFT
func captureScreen() -> UIImage
{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
For people looking for a quick solution, you can use the NetworkShareAccesser
I wrote recently (based on this answer (thanks so much!)):
Usage:
using (NetworkShareAccesser.Access(REMOTE_COMPUTER_NAME, DOMAIN, USER_NAME, PASSWORD))
{
File.Copy(@"C:\Some\File\To\copy.txt", @"\\REMOTE-COMPUTER\My\Shared\Target\file.txt");
}
WARNING: Please make absolutely sure, that Dispose
of the NetworkShareAccesser
is called (even if you app crashes!), otherwise an open connection will remain on Windows. You can see all open connections by opening the cmd
prompt and enter net use
.
The Code:
/// <summary>
/// Provides access to a network share.
/// </summary>
public class NetworkShareAccesser : IDisposable
{
private string _remoteUncName;
private string _remoteComputerName;
public string RemoteComputerName
{
get
{
return this._remoteComputerName;
}
set
{
this._remoteComputerName = value;
this._remoteUncName = @"\\" + this._remoteComputerName;
}
}
public string UserName
{
get;
set;
}
public string Password
{
get;
set;
}
#region Consts
private const int RESOURCE_CONNECTED = 0x00000001;
private const int RESOURCE_GLOBALNET = 0x00000002;
private const int RESOURCE_REMEMBERED = 0x00000003;
private const int RESOURCETYPE_ANY = 0x00000000;
private const int RESOURCETYPE_DISK = 0x00000001;
private const int RESOURCETYPE_PRINT = 0x00000002;
private const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
private const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
private const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
private const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
private const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;
private const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
private const int RESOURCEUSAGE_CONTAINER = 0x00000002;
private const int CONNECT_INTERACTIVE = 0x00000008;
private const int CONNECT_PROMPT = 0x00000010;
private const int CONNECT_REDIRECT = 0x00000080;
private const int CONNECT_UPDATE_PROFILE = 0x00000001;
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_CMD_SAVECRED = 0x00001000;
private const int CONNECT_LOCALDRIVE = 0x00000100;
#endregion
#region Errors
private const int NO_ERROR = 0;
private const int ERROR_ACCESS_DENIED = 5;
private const int ERROR_ALREADY_ASSIGNED = 85;
private const int ERROR_BAD_DEVICE = 1200;
private const int ERROR_BAD_NET_NAME = 67;
private const int ERROR_BAD_PROVIDER = 1204;
private const int ERROR_CANCELLED = 1223;
private const int ERROR_EXTENDED_ERROR = 1208;
private const int ERROR_INVALID_ADDRESS = 487;
private const int ERROR_INVALID_PARAMETER = 87;
private const int ERROR_INVALID_PASSWORD = 1216;
private const int ERROR_MORE_DATA = 234;
private const int ERROR_NO_MORE_ITEMS = 259;
private const int ERROR_NO_NET_OR_BAD_PATH = 1203;
private const int ERROR_NO_NETWORK = 1222;
private const int ERROR_BAD_PROFILE = 1206;
private const int ERROR_CANNOT_OPEN_PROFILE = 1205;
private const int ERROR_DEVICE_IN_USE = 2404;
private const int ERROR_NOT_CONNECTED = 2250;
private const int ERROR_OPEN_FILES = 2401;
#endregion
#region PInvoke Signatures
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
[DllImport("Mpr.dll")]
private static extern int WNetCancelConnection2(
string lpName,
int dwFlags,
bool fForce
);
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
#endregion
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name. The user will be promted to enter credentials
/// </summary>
/// <param name="remoteComputerName"></param>
/// <returns></returns>
public static NetworkShareAccesser Access(string remoteComputerName)
{
return new NetworkShareAccesser(remoteComputerName);
}
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name using the given domain/computer name, username and password
/// </summary>
/// <param name="remoteComputerName"></param>
/// <param name="domainOrComuterName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
public static NetworkShareAccesser Access(string remoteComputerName, string domainOrComuterName, string userName, string password)
{
return new NetworkShareAccesser(remoteComputerName,
domainOrComuterName + @"\" + userName,
password);
}
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name using the given username (format: domainOrComputername\Username) and password
/// </summary>
/// <param name="remoteComputerName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
public static NetworkShareAccesser Access(string remoteComputerName, string userName, string password)
{
return new NetworkShareAccesser(remoteComputerName,
userName,
password);
}
private NetworkShareAccesser(string remoteComputerName)
{
RemoteComputerName = remoteComputerName;
this.ConnectToShare(this._remoteUncName, null, null, true);
}
private NetworkShareAccesser(string remoteComputerName, string userName, string password)
{
RemoteComputerName = remoteComputerName;
UserName = userName;
Password = password;
this.ConnectToShare(this._remoteUncName, this.UserName, this.Password, false);
}
private void ConnectToShare(string remoteUnc, string username, string password, bool promptUser)
{
NETRESOURCE nr = new NETRESOURCE
{
dwType = RESOURCETYPE_DISK,
lpRemoteName = remoteUnc
};
int result;
if (promptUser)
{
result = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
}
else
{
result = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
}
if (result != NO_ERROR)
{
throw new Win32Exception(result);
}
}
private void DisconnectFromShare(string remoteUnc)
{
int result = WNetCancelConnection2(remoteUnc, CONNECT_UPDATE_PROFILE, false);
if (result != NO_ERROR)
{
throw new Win32Exception(result);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
this.DisconnectFromShare(this._remoteUncName);
}
}
If you want to do manually then You also can clear your user data by clicking “Clear Data”
button in Settings–>Applications–>Manage Aplications–>
YOUR APPLICATION
or Is there any other way to do that?
Then Download code here
Here is part of my program related to plotting confidence interval.
ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)
sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
tmp <- 1.96*sqrt(tmp)
y_e_minus[i] <- y_e[i] - tmp
y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')
Works fine for me
See example here. http://jsfiddle.net/blowsie/c6VAy/
Make sure your jquery is inside $(document).ready
function or similar.
Also you can improve your code by using jquery data
$('#amount').data('min','1000');
<div id="amount" data-min=""></div>
Update,
A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/
Below is the Odd_Even_function.py file that has the definition of the function.
def OE(n):
for a in range(n):
if a % 2 == 0:
print(a)
else:
print(a, "ODD")
Now to call the same from Command prompt below are the options worked for me.
Options 1 Full path of the exe\python.exe -c "import Odd_Even_function; Odd_Even_function.OE(100)"
Option 2 Full path of the exe\python.exe -c "from Odd_Even_function import OE; OE(100)"
Thanks.
I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:
I encountered this when using scrapy and fetching a zipped csvfile without having a correct middleware to unzip the response body before handing it to the csvreader. Hence the file was not really a csv file and threw the line contains NULL byte
error accordingly.
These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"
With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append()
syntax to achieve multiple params in the body since we are working with an immutable object:
login(userName: string, password: string): Promise<boolean> {
if (!userName || !password) {
return Promise.resolve(false);
}
let body: HttpParams = new HttpParams();
body = body.append('grant_type', 'password');
body = body.append('username', userName);
body = body.append('password', password);
return this.http.post(this.url, body)
.map(res => {
if (res) {
return true;
}
return false;
})
.toPromise();
}
Beside commands like M-x eval-buffer or M-x load-file you can restart a fresh emacs from the command line:
emacs -q --load "init.el"
Usage example stackoverflow.com/questions/44959535/company-backends-in-gnu-emacs/
You don't really need jQuery for this as there is a Media API that provides you with all you need.
var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();
The Media API also contains a load()
method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."
(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType()
function to decide on which one to play).
You can then wait for either the loadedmetadata
or loadeddata
(depending on what you want) events to fire:
video.addEventListener('loadeddata', function() {
// Video is loaded and can be played
}, false);
site-packages
directory where pip is installing your packages.psycopg2
directory).pip install YOUR-PACKAGE
Explanation:
First create a database or use an existing database. In my case, I am using an existing database
Load the database by giving <name of database> = ClassicModels
in my case and using the operator <
give the path to the database = sakila-data.sql
By running show tables, I get the list of tables as you can see.
Note : In my case I got an error 1062, because I am trying to load the same thing again.
I like this approach
my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)
Note the appended d and s to the brackets respectively.
output will be:
I scored 3 goals and took 5 penalties
I too have had this problem but solved it without script and only using CSS. I start by following the recommended padding-top for a fixed menu by setting of 60px described on the Bootstrap website. Then I added three media tags that resize the padding at the cutoff points where my menu also resizes.
<style>
body{
padding-top:60px;
}
/* fix padding under menu after resize */
@media screen and (max-width: 767px) {
body { padding-top: 60px; }
}
@media screen and (min-width:768px) and (max-width: 991px) {
body { padding-top: 110px; }
}
@media screen and (min-width: 992px) {
body { padding-top: 60px; }
}
</style>
One note, when my menu width is between 768 and 991, the menu logo in my layout plus the <li>
options cause the menu to wrap to two lines. Therefore, I had to adjust the padding-top to prevent the menu from covering the content, hence 110px.
Hope this helps...
Aesthetically I tend to favor this approach.
unsigned int special_events[] = {
ERROR_01,
ERROR_07,
ERROR_0A,
ERROR_10,
ERROR_15,
ERROR_16,
ERROR_20
};
int special_events_length = sizeof (special_events) / sizeof (unsigned int);
void process_event(unsigned int numError) {
for (int i = 0; i < special_events_length; i++) {
if (numError == special_events[i]) {
fire_special_event();
break;
}
}
}
Make the data a little smarter so we can make the logic a little dumber.
I realize it looks weird. Here's the inspiration (from how I'd do it in Python):
special_events = [
ERROR_01,
ERROR_07,
ERROR_0A,
ERROR_10,
ERROR_15,
ERROR_16,
ERROR_20,
]
def process_event(numError):
if numError in special_events:
fire_special_event()
You can try something like this:
strncpy(new_str, str1, strlen(str1));
strcat(new_str, str2);
More info on strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
According to this Video if you use the ProGuard you don't need even think about Enums performance issues!!
Proguard can in many situations optimize Enums to INT values on your behalf so really don't need to think about it or do any work.
The simplest way to create a manifest is:
Project Properties -> Security -> Click "enable ClickOnce security settings"
(it will generate default manifest in your project Properties) -> then Click
it again in order to uncheck that Checkbox -> open your app.maifest and edit
it as you wish.
The values can be retrieved during the parsing:
var yahoo = [], j = `[{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]`_x000D_
_x000D_
var data = JSON.parse(j, function(key, value) { _x000D_
if ( value.website === "yahoo" ) yahoo.push(value); _x000D_
return value; })_x000D_
_x000D_
console.log( yahoo )
_x000D_
a few small changes to make it responsive
<style type="text/css">
#wrap {
width: 100%;
margin: 0 auto;
display: table;
}
#left_col {
float:left;
width:50%;
}
#right_col {
float:right;
width:50%;
}
@media only screen and (max-width: 480px){
#left_col {
width:100%;
}
#right_col {
width:100%;
}
}
</style>
<div id="wrap">
<div id="left_col">
...
</div>
<div id="right_col">
...
</div>
</div>
Just right click the Project -- Properties and select Resource on the left side menu.
You can now change the Text-file encoding to whatever you wish.
My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:
CREATE TABLE book (
id INT AUTO_INCREMENT NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL,
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This what I always use:
The default behaviour implemented in Gson is that null object fields are ignored.
Means Gson object does not serialize fields with null values to JSON. If a field in a Java object is null, Gson excludes it.
You can use this function to convert some object to null or well set by your own
/**
* convert object to json
*/
public String toJson(Object obj) {
// Convert emtpy string and objects to null so we don't serialze them
setEmtpyStringsAndObjectsToNull(obj);
return gson.toJson(obj);
}
/**
* Sets all empty strings and objects (all fields null) including sets to null.
*
* @param obj any object
*/
public void setEmtpyStringsAndObjectsToNull(Object obj) {
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
Object fieldObj = field.get(obj);
if (fieldObj != null) {
Class fieldType = field.getType();
if (fieldType.isAssignableFrom(String.class)) {
if(fieldObj.equals("")) {
field.set(obj, null);
}
} else if (fieldType.isAssignableFrom(Set.class)) {
for (Object item : (Set) fieldObj) {
setEmtpyStringsAndObjectsToNull(item);
}
boolean setFielToNull = true;
for (Object item : (Set) field.get(obj)) {
if(item != null) {
setFielToNull = false;
break;
}
}
if(setFielToNull) {
setFieldToNull(obj, field);
}
} else if (!isPrimitiveOrWrapper(fieldType)) {
setEmtpyStringsAndObjectsToNull(fieldObj);
boolean setFielToNull = true;
for (Field f : fieldObj.getClass().getDeclaredFields()) {
f.setAccessible(true);
if(f.get(fieldObj) != null) {
setFielToNull = false;
break;
}
}
if(setFielToNull) {
setFieldToNull(obj, field);
}
}
}
} catch (IllegalAccessException e) {
System.err.println("Error while setting empty string or object to null: " + e.getMessage());
}
}
}
private void setFieldToNull(Object obj, Field field) throws IllegalAccessException {
if(!Modifier.isFinal(field.getModifiers())) {
field.set(obj, null);
}
}
private boolean isPrimitiveOrWrapper(Class fieldType) {
return fieldType.isPrimitive()
|| fieldType.isAssignableFrom(Integer.class)
|| fieldType.isAssignableFrom(Boolean.class)
|| fieldType.isAssignableFrom(Byte.class)
|| fieldType.isAssignableFrom(Character.class)
|| fieldType.isAssignableFrom(Float.class)
|| fieldType.isAssignableFrom(Long.class)
|| fieldType.isAssignableFrom(Double.class)
|| fieldType.isAssignableFrom(Short.class);
}
If you are using NodeJS, you can use the build-in util function:
import * as util from "util";
util.format('My string: %s', 'foo');
Document can be found here: https://nodejs.org/api/util.html#util_util_format_format_args
Using Maven
First of all you should install android libraries to your local maven repository using Maven Android SDK Deployer
Then you can add dependency to your pom like this:
<dependency>
<groupId>android.support</groupId>
<artifactId>compatibility-v7-appcompat</artifactId>
<version>${compatibility.version}</version>
<type>apklib</type>
</dependency>
<dependency>
<groupId>android.support</groupId>
<artifactId>compatibility-v7-appcompat</artifactId>
<version>${compatibility.version}</version>
<type>jar</type>
</dependency>
Check if the user has scrolled past the header ad, then display the footer ad.
if($(your header ad).position().top < 0) { $(your footer ad).show() }
Am I correct at what you are looking for?
For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:
public boolean compare(String s1, String s2) {
return StringUtils.equals(s1, s2);
}
If you dont want to add the library, just copy the source code of the StringUtils#equals
method and apply it when you need it.
I have done a very simple thing to enable or disable command button. Below is my grid
<asp:GridView ID="grdOrderProduct" runat="server" TabIndex="1" BackColor="White" BorderColor="#CEC9EF" CssClass="table table-striped dataTable table-bordered"
OnRowEditing="grdOrderProduct_RowEditing" OnRowUpdating="grdOrderProduct_RowUpdating" OnRowDeleting="grdOrderProduct_RowDeleting" OnRowDataBound="grdOrderProduct_RowDataBound"
Width="100%" CellPadding="3" CellSpacing="1" BorderWidth="0" AutoGenerateColumns="False">
<HeaderStyle />
<AlternatingRowStyle />
<Columns>
<asp:BoundField DataField="ProductSKU" ReadOnly="true" HeaderText="Product SKU" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="ProductName" ReadOnly="true" HeaderText="ProductName" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="QTY" HeaderText="QTY" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="Discount" HeaderText="Discount %" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="TPrice" HeaderText="MRP" ReadOnly="true" HeaderStyle-CssClass="headTb4" />
<asp:CommandField ShowEditButton="true" ButtonType="Image" EditImageUrl="~/Images/edit.png"
UpdateImageUrl="~/Images/gear.png" CancelText=" " HeaderStyle-CssClass="headTb4"
ShowDeleteButton="true" DeleteImageUrl="~/Images/delete.png"
HeaderText="Action" ItemStyle-HorizontalAlign="Center">
<HeaderStyle CssClass="headTb4" />
<ItemStyle HorizontalAlign="Center" />
</asp:CommandField>
</Columns>
<AlternatingRowStyle CssClass="odd" />
<PagerStyle HorizontalAlign="Center" VerticalAlign="Top" Wrap="False" />
In the following method i have done the changes
protected void grdOrderProduct_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (ImageButton button in e.Row.Cells[5].Controls.OfType<ImageButton>())
{
if (button.CommandName == "Delete")
{
button.Visible = false;
}
}
}
}
FC works great by in my case it was not helpful as I wanted just the lines that are changed. And FC give additional data like file name, same lines and bilateral comparison.
>fc data.txt data.txt.bak
***** DATA.TXT
####09
####09
####09
***** DATA.TXT.BAK
####09
####08
####09
but in my case I wanted only the lines that have changed and wanted those lines to be exported to different file, without any other header or data.
So I used "findstr" to compare the file :
findstr /V /G:data.txt.bak data.txt >DiffResult.txt
where :
data.txt.bak
is the name of old file
data.txt
is the name of new file
DiffResult.txt
contains the data that is changed i.e just one line ####09
Ajax.ActionLink only sends an ajax request to the server. What happens ahead really depends upon type of data returned and what your client side script does with it. You may send a partial view for ajax call or json, xml etc. Ajax.ActionLink however have different callbacks and parameters that allow you to write js code on different events. You can do something before request is sent or onComplete
. similarly you have an onSuccess callback. This is where you put your JS code for manipulating result returned by server. You may simply put it back in UpdateTargetID or you can do fancy stuff with this result using jQuery or some other JS library.
you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual
You can use this example and change it's implementation like this:
[self enumerateAttribute:NSParagraphStyleAttributeName
inRange:NSMakeRange(0, self.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//add your specific settings for paragraph
//...
//...
[self removeAttribute:NSParagraphStyleAttributeName range:range];
[self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
}];
You can do this by adding following script and style
function appHeight() {
const doc = document.documentElement
doc.style.setProperty('--vh', (window.innerHeight*.01) + 'px');
}
window.addEventListener('resize', appHeight);
appHeight();
Style
.module {
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
Your composer.phar must be in Source files. I had same problem and I just cut my composer.phar into mine framework-standard-edition folder, where is my whole strong textproject.
Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.
This can be done in your application Web.Config in the
<appSettings>
section (create the section directly under<configuration>
if it doesn’t exist). Add 2 lines similar to the lines below to the section:<add key="aspnet:MaxHttpCollectionKeys" value="2000" /> <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.
This usually occurs because either of the following are true:
Try getting some information about the certificate of the server and see if you need to install any specific certs on your client to get it to work.
You can use @PropertySource
to externalize your configuration to a properties file. There is number of way to do get properties:
1.
Assign the property values to fields by using @Value
with PropertySourcesPlaceholderConfigurer
to resolve ${}
in @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.
Get the property values by using Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
Hope this can help
Well, you're going to have to check for null somewhere. You could do something like this:
from item in db.vw_Dropship_OrderItems
where (listStatus == null || listStatus.Contains(item.StatusCode))
&& (listMerchants == null || listMerchants.Contains(item.MerchantId))
select item;
Here is way to avoid absolute divs and tables if you know parent's height:
<div class="parent">
<div class="child"> <a href="#">Home</a>
</div>
</div>
CSS:
.parent {
line-height:80px;
border: 1px solid black;
}
.child {
line-height:normal;
display: inline-block;
vertical-align:bottom;
border: 1px solid red;
}
JsFiddle:
In case this is helpful to others... I had this issue because my virtualenv defaulted to python2.7 and I was calling Django using Python3 while using Ubuntu.
to check which python my virtualenv was using:
$ which python3
>> /usr/bin/python3
created new virtualenv with python3 specified (using virtualenv wrapper https://virtualenvwrapper.readthedocs.org/en/latest/):
$ mkvirtualenv --python=/usr/bin/python3 ENV_NAME
the python path should now point to the virtualenv python:
$ which python3
>> /home/user/.virtualenvs/ENV_NAME/bin/python3
The *
key will highlight all occurrences of the word that is under the cursor.
Yes, #id
selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.
However, for your example, since <script>
comes before the elements, you need a document.ready
handler, so it waits until the elements are in the DOM to go looking for them, like this:
<script>
$(function() {
$("#segement1,#segement2,#segement3").hide()
});
</script>
<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>
Be careful with setup
projects if you're using them; Visual Studio setup projects Primary Output
pulls from the obj
folder rather than the bin
.
I was releasing applications I thought were obfuscated and signed in msi
setups for quite a while before I discovered that the deployed application files were actually neither obfuscated nor signed as I as performing the post-build procedure on the bin
folder assemblies and should have been targeting the obj
folder assemblies instead.
This is far from intuitive imho, but the general setup
approach is to use the Primary Output
of the project and this is the obj
folder. I'd love it if someone could shed some light on this btw.
As noted, you could also place the legend in the plot, or slightly off it to the edge as well. Here is an example using the Plotly Python API, made with an IPython Notebook. I'm on the team.
To begin, you'll want to install the necessary packages:
import plotly
import math
import random
import numpy as np
Then, install Plotly:
un='IPython.Demo'
k='1fw3zw2o13'
py = plotly.plotly(username=un, key=k)
def sin(x,n):
sine = 0
for i in range(n):
sign = (-1)**i
sine = sine + ((x**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine
x = np.arange(-12,12,0.1)
anno = {
'text': '$\\sum_{k=0}^{\\infty} \\frac {(-1)^k x^{1+2k}}{(1 + 2k)!}$',
'x': 0.3, 'y': 0.6,'xref': "paper", 'yref': "paper",'showarrow': False,
'font':{'size':24}
}
l = {
'annotations': [anno],
'title': 'Taylor series of sine',
'xaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'yaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'legend':{'font':{'size':16},'bordercolor':'white','bgcolor':'#fcfcfc'}
}
py.iplot([{'x':x, 'y':sin(x,1), 'line':{'color':'#e377c2'}, 'name':'$x\\\\$'},\
{'x':x, 'y':sin(x,2), 'line':{'color':'#7f7f7f'},'name':'$ x-\\frac{x^3}{6}$'},\
{'x':x, 'y':sin(x,3), 'line':{'color':'#bcbd22'},'name':'$ x-\\frac{x^3}{6}+\\frac{x^5}{120}$'},\
{'x':x, 'y':sin(x,4), 'line':{'color':'#17becf'},'name':'$ x-\\frac{x^5}{120}$'}], layout=l)
This creates your graph, and allows you a chance to keep the legend within the plot itself. The default for the legend if it is not set is to place it in the plot, as shown here.
For an alternative placement, you can closely align the edge of the graph and border of the legend, and remove border lines for a closer fit.
You can move and re-style the legend and graph with code, or with the GUI. To shift the legend, you have the following options to position the legend inside the graph by assigning x and y values of <= 1. E.g :
{"x" : 0,"y" : 0}
-- Bottom Left {"x" : 1, "y" : 0}
-- Bottom Right {"x" : 1, "y" : 1}
-- Top Right {"x" : 0, "y" : 1}
-- Top Left {"x" :.5, "y" : 0}
-- Bottom Center {"x": .5, "y" : 1}
-- Top CenterIn this case, we choose the upper right, legendstyle = {"x" : 1, "y" : 1}
, also described in the documentation:
When doing a push, try specifying the refspec for the upstream master:
git push upstream upstreammaster:master
This might be helpful for whoever else faces this problem. I finally figured out a solution. Turns out, even if we use the inline for "content-disposition" and specify a file name, the browsers still do not use the file name. Instead browsers try and interpret the file name based on the Path/URL.
You can read further on this URL: Securly download file inside browser with correct filename
This gave me an idea, I just created my URL route that would convert the URL and end it with the name of the file I wanted to give the file. So for e.g. my original controller call just consisted of passing the Order Id of the Order being printed. I was expecting the file name to be of the format Order{0}.pdf where {0} is the Order Id. Similarly for quotes, I wanted Quote{0}.pdf.
In my controller, I just went ahead and added an additional parameter to accept the file name. I passed the filename as a parameter in the URL.Action method.
I then created a new route that would map that URL to the format: http://localhost/ShoppingCart/PrintQuote/1054/Quote1054.pdf
routes.MapRoute("", "{controller}/{action}/{orderId}/{fileName}",
new { controller = "ShoppingCart", action = "PrintQuote" }
, new string[] { "x.x.x.Controllers" }
);
This pretty much solved my issue. Hoping this helps someone!
Cheerz, Anup
Added this as a comment to accepted answer, but felt it deserved a longer explanation. Starting around April 2015 this will probably be raised a few times.
As of V2 of the graph api the accepted answer no longer works using a username. So now you need the userid first, and you can no longer use a username to get this. To further complicate matters, for privacy reasons, Facebook is now changing userid's per app (see https://developers.facebook.com/docs/graph-api/reference/v2.2/user/ and https://developers.facebook.com/docs/apps/upgrading/#upgrading_v2_0_user_ids ), so you will have to have some kind of proper authentication to retrieve a userid you can use. Technically the profile pic is still public and available at /userid/picture (see docs at https://developers.facebook.com/docs/graph-api/reference/v2.0/user/picture and this example user: http://graph.facebook.com/v2.2/4/picture?redirect=0) however figuring out a user's standard userid seems impossible based just on their profile - your app would need to get them to approve interaction with the app which for my use case (just showing a profile pic next to their FB profile link) is overkill.
If someone has figured out a way to get the profile pic based on username, or alternatively, how to get a userid (even an alternating one) to use to retrieve a profile pic, please share! In the meantime, the old graph url still works until April 2015.
It took me a while to implement the other responses, as I'm using Angular 8 (tested up to 10). I ended up with the following code (heavily inspired by Hasan).
Note that for the name to be set, the header Access-Control-Expose-Headers
MUST include Content-Disposition
. To set this in django RF:
http_response = HttpResponse(package, content_type='application/javascript')
http_response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
http_response['Access-Control-Expose-Headers'] = "Content-Disposition"
In angular:
// component.ts
// getFileName not necessary, you can just set this as a string if you wish
getFileName(response: HttpResponse<Blob>) {
let filename: string;
try {
const contentDisposition: string = response.headers.get('content-disposition');
const r = /(?:filename=")(.+)(?:")/
filename = r.exec(contentDisposition)[1];
}
catch (e) {
filename = 'myfile.txt'
}
return filename
}
downloadFile() {
this._fileService.downloadFile(this.file.uuid)
.subscribe(
(response: HttpResponse<Blob>) => {
let filename: string = this.getFileName(response)
let binaryData = [];
binaryData.push(response.body);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'blob' }));
downloadLink.setAttribute('download', filename);
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}
// service.ts
downloadFile(uuid: string) {
return this._http.get<Blob>(`${environment.apiUrl}/api/v1/file/${uuid}/package/`, { observe: 'response', responseType: 'blob' as 'json' })
}
The other answers are Ok, but a while loop seems more appropriate:
function setAll(array, value) {
var i = array.length;
while (i--) {
array[i] = value;
}
}
A more creative version:
function replaceAll(array, value) {
var re = new RegExp(value, 'g');
return new Array(++array.length).toString().replace(/,/g, value).match(re);
}
May not work everywhere though. :-)
Empty collection. Always.
This sucks:
if(myInstance.CollectionProperty != null)
{
foreach(var item in myInstance.CollectionProperty)
/* arrgh */
}
It is considered a best practice to NEVER return null
when returning a collection or enumerable. ALWAYS return an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.
When talking about properties, always set your property once and forget it
public List<Foo> Foos {public get; private set;}
public Bar() { Foos = new List<Foo>(); }
In .NET 4.6.1, you can condense this quite a lot:
public List<Foo> Foos { get; } = new List<Foo>();
When talking about methods that return enumerables, you can easily return an empty enumerable instead of null
...
public IEnumerable<Foo> GetMyFoos()
{
return InnerGetFoos() ?? Enumerable.Empty<Foo>();
}
Using Enumerable.Empty<T>()
can be seen as more efficient than returning, for example, a new empty collection or array.
public void GetResponseAsync (HttpWebRequest request, Action<HttpWebResponse> gotResponse)
{
if (request != null) {
request.BeginGetRequestStream ((r) => {
try { // there's a try/catch here because execution path is different from invokation one, exception here may cause a crash
HttpWebResponse response = request.EndGetResponse (r);
if (gotResponse != null)
gotResponse (response);
} catch (Exception x) {
Console.WriteLine ("Unable to get response for '" + request.RequestUri + "' Err: " + x);
}
}, null);
}
}
For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between toBe
and toEqual
; either one will work for 5
, true
, or "the cake is a lie"
.
To understand the difference between toBe
and toEqual
, let's imagine three objects.
var a = { bar: 'baz' },
b = { foo: a },
c = { foo: a };
Using a strict comparison (===
), some things are "the same":
> b.foo.bar === c.foo.bar
true
> b.foo.bar === a.bar
true
> c.foo === b.foo
true
But some things, even though they are "equal", are not "the same", since they represent objects that live in different locations in memory.
> b === c
false
Jasmine's toBe
matcher is nothing more than a wrapper for a strict equality comparison
expect(c.foo).toBe(b.foo)
is the same thing as
expect(c.foo === b.foo).toBe(true)
Don't just take my word for it; see the source code for toBe.
But b
and c
represent functionally equivalent objects; they both look like
{ foo: { bar: 'baz' } }
Wouldn't it be great if we could say that b
and c
are "equal" even if they don't represent the same object?
Enter toEqual
, which checks "deep equality" (i.e. does a recursive search through the objects to determine whether the values for their keys are equivalent). Both of the following tests will pass:
expect(b).not.toBe(c);
expect(b).toEqual(c);
Hope that helps clarify some things.
If you run ps -aux | dockerd
you should see the tcp endpoint it is running on.
You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.
const noGuest = 3;_x000D_
_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_
console.log(guest);_x000D_
});
_x000D_
Example:
renderPayments(noGuest) {
return Array(noGuest).fill(noGuest).map((guess, index) => {
return(
<View key={index}>
<View><TextInput /></View>
<View><TextInput /></View>
<View><TextInput /></View>
</View>
);
}
}
Then use it where you want it
render() {
return(
const { guest } = this.state;
...
{this.renderPayments(guest)}
);
}
Hope you got the idea.
If you want to understand this in simple Javascript check Array.prototype.fill()
Perl Code for Unix systems:
# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;
# Remove newline character
$current_date = substr($current_date,0,-1);
print $current_date, "\n";
To get the specific tag code try to create a new branch add get the tag code in it.
I have done it by command : $git checkout -b newBranchName tagName
Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML
An excellent read for those looking to leverage ORM and UML
To make everything writable by the owner, read/execute by the group, and world executable:
chmod -R 0755
To make everything wide open:
chmod -R 0777
Code For Merging PDF's in Itextsharp
public static void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
//fixed typo
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
File.Delete(file);
});
}
To make a inline-block element align center horizontally in its parent, add text-align:center
to its parent.
strong is the default. An object remains “alive” as long as there is a strong pointer to it.
weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
I guess your code relates to Windows Forms.
You call BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If BeginInvoke
is called for Delegate
type the delegate is just invoked asynchronously.
(Invoke
for the sync version.)
If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)
And to add a little to already said by others:
Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var
with lambdas: compiler needs a hint.
UPDATE:
this requires .Net v4.0 and higher
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
If you started the task from other thread and need to wait for its completition task.Wait()
will block calling thread till the end of the task.
Read more about tasks here.
this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");
Example here.
Pasted below:
This is about how to launch android application from the adb shell.
Command: am
Look for invoking path in AndroidManifest.xml
Browser app::
# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front
Settings app::
# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }
Other than using the Navigator/Proj Explorer and choosing files and doing 'Compare With'->'Each other'... I prefer opening both files in Eclipse and using 'Compare With'->'Opened Editor'->(pick the opened tab)... You can get this feature via the AnyEdit eclipse plugin located here (you can use Install Software via Eclipse->Help->Install New Software screen): http://andrei.gmxhome.de/eclipse/
Or.. Pattern#quote
:
String[] value_split = rat_values.split(Pattern.quote("|"));
This is happening because String#split
accepts a regex:
|
has a special meaning in regex.
quote
will return a String representation for the regex.
EDIT: don't use vc80 / Visual Studio 2005, but Visual Studio 2008 / vc90 versions of the CGAL library (maybe from here).
You could also compile with /Z7, so the pdb doesn't need to be used, or remove the /DEBUG linker option if you do not have .pdb files for the objects you are linking.
It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.
<input id="myFileInput" type="file" accept="image/*;capture=camera">
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
}
myInput.addEventListener('change', sendPic, false);
I'm hitting Microsoft SQL Server 2008 R2 from a single-threaded JDBC-based application and pulling back the last ID without using the RETURN_GENERATED_KEYS property or any PreparedStatement. Looks something like this:
private int insertQueryReturnInt(String SQLQy) {
ResultSet generatedKeys = null;
int generatedKey = -1;
try {
Statement statement = conn.createStatement();
statement.execute(SQLQy);
} catch (Exception e) {
errorDescription = "Failed to insert SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
try {
generatedKey = Integer.parseInt(readOneValue("SELECT @@IDENTITY"));
} catch (Exception e) {
errorDescription = "Failed to get ID of just-inserted SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
return generatedKey;
}
This blog post nicely isolates three main SQL Server "last ID" options: http://msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the-sql-server/ - haven't needed the other two yet.
Here is a way to do it in the shell:
FIELD=2
cut -f $FIELD * | sort| uniq -c |sort -nr
This is the sort of thing bash is great at.
You wan't to either change the user that the Service runs under from "System" or find a sneaky way to run your mapping as System.
The funny thing is that this is possible by using the "at" command, simply schedule your drive mapping one minute into the future and it will be run under the System account making the drive visible to your service.
This code work
pwindo = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
pwindo.setOutsideTouchable(false);
View container = (View) pwindo.getContentView().getParent();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(container, p);
If you want the results to be case insensitive, the following will work:
List<string> list1 = new List<string> { "a.dll", "b1.dll" };
List<string> list2 = new List<string> { "A.dll", "b2.dll" };
var firstNotSecond = list1.Except(list2, StringComparer.OrdinalIgnoreCase).ToList();
var secondNotFirst = list2.Except(list1, StringComparer.OrdinalIgnoreCase).ToList();
firstNotSecond
would contain b1.dll
secondNotFirst
would contain b2.dll
I checked out iterrows
after noticing Nick Crawford's answer, but found that it yields (index, Series) tuples. Not sure which would work best for you, but I ended up using the itertuples
method for my problem, which yields (index, row_value1...) tuples.
There's also iterkv
, which iterates through (column, series) tuples.
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:nil handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
// your code...
}];
delete.image = [UIImage systemImageNamed:@"trash"];
UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:[[NSArray alloc] initWithObjects:delete, nil]];
return actions;
}
Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]);
That is for people who prefer to have the constant on the left side. In most cases having the constant on the left side will prevent NullPointerException to be thrown (or having another nullcheck). For example the String method equals does also a null check. Having the constant on the left, will keep you from writing the additional check. Which, in another way is also performed later. Having the null value on the left is just being consistent.
like:
String b = null;
"constant".equals(b); // result to false
b.equals("constant"); // NullPointerException
b != null && b.equals("constant"); // result to false
Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
InputStream is = p1.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
} catch(IOException ioException) {
System.out.println(ioException.getMessage() );
}
The link here solved my problem.
http://brainof-dave.blogspot.com.au/2008/08/remote-certificate-is-invalid-according.html
I went to url of the web service (on the server that had the issue), clicked on the little security icon in IE, which brought up the certificate. I then clicked on the Details tab, clicked the Copy To File button, which allowed me to export the certifcate as a .cer file. Once I had the certificate locally, I was able to import it into the certificate store on the server using the below instructions.
Start a new MMC. File --> Add/Remove Snap-In... Click Add... Choose Certificates and click Add. Check the "Computer Account" radio button. Click Next.
Choose the client computer in the next screen. Click Finish. Click Close. Click OK. NOW install the certificate into the Trusted Root Certification Authorities certificate store. This will allow all users to trust the certificate.
First of all: I'm the author of the The Single Page Interface Manifesto cited by raganwald
As raganwald has explained very well, the most important aspect of the Single Page Interface (SPI) approach used in FaceBook and Twitter is the use of hash #
in URLs
The character !
is added only for Google purposes, this notation is a Google "standard" for crawling web sites intensive on AJAX (in the extreme Single Page Interface web sites). When Google's crawler finds an URL with #!
it knows that an alternative conventional URL exists providing the same page "state" but in this case on load time.
In spite of #!
combination is very interesting for SEO, is only supported by Google (as far I know), with some JavaScript tricks you can build SPI web sites SEO compatible for any web crawler (Yahoo, Bing...).
The SPI Manifesto and demos do not use Google's format of !
in hashes, this notation could be easily added and SPI crawling could be even easier (UPDATE: now ! notation is used and remains compatible with other search engines).
Take a look to this tutorial, is an example of a simple ItsNat SPI site but you can pick some ideas for other frameworks, this example is SEO compatible for any web crawler.
The hard problem is to generate any (or selected) "AJAX page state" as plain HTML for SEO, in ItsNat is very easy and automatic, the same site is in the same time SPI or page based for SEO (or when JavaScript is disabled for accessibility). With other web frameworks you can ever follow the double site approach, one site is SPI based and another page based for SEO, for instance Twitter uses this "double site" technique.
This is a guess. Generally recursion probably doesn't beat looping often or ever on problems of decent size if both are using really good algorithms(not counting implementation difficulty) , it may be different if used with a language w/ tail call recursion(and a tail recursive algorithm and with loops also as part of the language)-which would probably have very similar and possibly even prefer recursion some of the time.
Like this.
import java.util.Date;
import java.util.GregorianCalendar;
/**
* DateDiff -- compute the difference between two dates.
*/
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
Here is an article on Java date arithmetic.
Make sure that you actually save the file as UTF-8, alternatively use HTML entities (&#nnn;
) for the special characters.
If you want to just add a class to add the overlay:
span {_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
.green {_x000D_
background-color: green;_x000D_
color: #FFF;_x000D_
}_x000D_
_x000D_
.overlayed {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.overlayed::before {_x000D_
content: ' ';_x000D_
z-index: 1;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
background-color: #00000080;_x000D_
}_x000D_
_x000D_
.stand-out {_x000D_
position: relative;_x000D_
z-index: 2;_x000D_
}
_x000D_
<span class="green overlayed">with overlay</span>_x000D_
<span class="green">without overlay</span>_x000D_
<br>_x000D_
<br>_x000D_
<span class="green overlayed">_x000D_
<span class="stand-out">I stand out</span>_x000D_
</span>
_x000D_
Important: the element you put the overlayed
class on needs to have a position
set. If it doesn't, the ::before
element will take the size of some other parent element. In my example I've set the position to "relative" via the .overlayed
rule, but in your use case you might need "absolute" or some other value.
Also, make sure that the z-index
of the overlayed
class is higher than the ones of the eventual child elements of the container, unless you actually want for those to "stand out" and not be overlayed (as with the span with the stand-out
class, in my snippet).
PHP's string length is limited by the way strings are represented in PHP; memory does not have anything to do with it.
According to phpinternalsbook.com, strings are stored in struct { char *val; int len; } and since the maximum size of an int in C is 4 bytes, this effectively limits the maximum string size to 2GB.
maxRequestLength (length in KB) Here as ex. I took 1024 (1MB) maxAllowedContentLength (length in Bytes) should be same as your maxRequestLength (1048576 bytes = 1MB).
<system.web>
<httpRuntime maxRequestLength="1024" executionTimeout="3600" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1048576"/>
</requestFiltering>
</security>
</system.webServer>
After installation/upgrading node via brew I ran into this issue exactly: the node command worked but not the npm command.
I used these commands to fix it.
brew uninstall node
brew update
brew upgrade
brew cleanup
brew install node
sudo chown -R $(whoami) /usr/local
brew link --overwrite node
brew postinstall node
I pieced together this solution after trial and error using...
a github thread: https://github.com/npm/npm/issues/3125
this site: http://developpeers.com/blogs/fix-for-homebrew-permission-denied-issues
It should be well noted that the use of live()
in jQuery has been deprecated since version 1.7
and has been removed in jQuery 1.9
. Instead, the use of on()
is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
document.body
and passing $selector as the second argument to on()
, elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body
rather than $selector
directly, which means $selector
can be added, removed and added again and will never load the event bound to it.off()
before on()
, this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.$(function() {...})
, this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready()
does not get fired for AJAX requests, while $(function() {...})
does.Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
In addition to what @abarnert said, I today had to find out that the default cpio
utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the cpio read error: bad file format
message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:
find ./Foo.app | cpio -o --format odc | gzip -c > Payload
Office 2007
Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.
The syntax has changed in that print
is now a function. This means that the %
formatting needs to be done inside the parenthesis:1
print("%d. %s appears %d times." % (i, key, wordBank[key]))
However, since you are using Python 3.x., you should actually be using the newer str.format
method:
print("{}. {} appears {} times.".format(i, key, wordBank[key]))
Though %
formatting is not officially deprecated (yet), it is discouraged in favor of str.format
and will most likely be removed from the language in a coming version (Python 4 maybe?).
1Just a minor note: %d
is the format specifier for integers, not %s
.
"" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.
But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.
public class StringCheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "siddhartha";
String s2 = "";
String s3 = null;
System.out.println("length s1 ="+s1.length());
System.out.println("length s2 ="+s2.length());
//this piece of code will still throw nullpointerexception .
if(s3 != ""){
System.out.println("length s3 ="+s3.length());
}
}
}
One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:
var index = Artists.IndexOf(artist);
Artists.RemoveAt(index);
artist.IsFollowed = true; // change something in the item
Artists.Insert(index, artist);
All you need to do is set the PATH environment variable in Windows to point to where your java6 bin directory is instead of the java7 directory.
Right click My Computer > Advanced System Settings > Advanced > Environmental Variables
If there is a JAVA_HOME environment variable set this to point to the correct directory as well.
This command will "dry run" delete all remote (origin
) merged branches, apart from master
. You can change that, or, add additional branches after master: grep -v for-example-your-branch-here |
git branch -r --merged |
grep origin |
grep -v '>' |
grep -v master |
xargs -L1 |
awk '{sub(/origin\//,"");print}'|
xargs git push origin --delete --dry-run
If it looks good, remove the --dry-run
. Additionally, you may like to test this on a fork first.
I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:
try :
....
since python was searching for a
except Exception as e:
....
but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.
If you have a comma as decimals separator and the dot as thousands separator, you can do:
s = s.replace('.','').replace(',','.')
number = float(s)
Hope it will help
SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.
The keyword AUTOINCREMENT can be used with INTEGER field only. Syntax:
The basic usage of AUTOINCREMENT keyword is as follows:
CREATE TABLE table_name(
column1 INTEGER AUTOINCREMENT,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
For Example See Below: Consider COMPANY table to be created as follows:
sqlite> CREATE TABLE TB_COMPANY_INFO(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Now, insert following records into table TB_COMPANY_INFO:
INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );
Now Select the record
SELECT *FROM TB_COMPANY_INFO
ID NAME AGE ADDRESS SALARY
1 Manoj Kumar 40 Meerut,UP,INDIA 200000.00
I'd use the Database Diagramming feature in SQL Server Management Studio, but since you ruled that out - this worked for me in SQL Server 2008 (don't have 2005).
To get list of referring table and column names...
select
t.name as TableWithForeignKey,
fk.constraint_column_id as FK_PartNo, c.
name as ForeignKeyColumn
from
sys.foreign_key_columns as fk
inner join
sys.tables as t on fk.parent_object_id = t.object_id
inner join
sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where
fk.referenced_object_id = (select object_id
from sys.tables
where name = 'TableOthersForeignKeyInto')
order by
TableWithForeignKey, FK_PartNo
To get names of foreign key constraints
select distinct name from sys.objects where object_id in
( select fk.constraint_object_id from sys.foreign_key_columns as fk
where fk.referenced_object_id =
(select object_id from sys.tables where name = 'TableOthersForeignKeyInto')
)
Does:
Set Sheets("Output").Range("$A$1:$A$500") = Sheets(sheet_).Range("$A$1:$A$500")
...work? (I don't have Excel in front of me, so can't test.)
To display dialog box, you can use the following code. This is to display a simple AlertDialog box with multiple check boxes:
AlertDialog.Builder alertDialog= new AlertDialog.Builder(MainActivity.this); .
alertDialog.setTitle("this is a dialog box ");
alertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"ok ive wrote this 'ok' here" ,Toast.LENGTH_SHORT).show();
}
});
alertDialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "cancel ' comment same as ok'", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), items[which] +(isChecked?"clicked'again i've wrrten this click'":"unchecked"),Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
Whereas if you are using the showDialog function to display different dialog box or anything as per the arguments passed, you can create a self function and can call it under the onClickListener()
function. Something like:
public CharSequence[] items={"google","Apple","Kaye"};
public boolean[] checkedItems=new boolean[items.length];
Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button) findViewById(R.id.bt);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
display(0);
}
});
}
and add the code of dialog box given above in the function definition.
For python3 it should be pip3
on ubuntu
sudo apt install python3-pip
Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/
.tinted-image {
width: 300px;
height: 200px;
background:
/* top, transparent red */
linear-gradient(
rgba(255, 0, 0, 0.45),
rgba(255, 0, 0, 0.45)
),
/* bottom, image */
url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}
Check out this implementation of PHP's strtotime() in JavaScript!
I found that it works identically to PHP for everything that I threw at it.
Update: this function as per version 1.0.2 can't handle this case:
'2007:07:20 20:52:45'
(Note the:
separator for year and month)
This is now available as an npm
module! Simply npm install locutus
and then in your source:
var strtotime = require('locutus/php/datetime/strtotime');
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
window.location.href = "/{controller}/{action}/{params}";
else
return false;
}
I took it from ((How to control positioning of jQueryUI datepicker))
$.extend($.datepicker, {
_checkOffset: function(inst, offset, isFixed) {
return offset
}
});
it works !!!
Install the wheel
package first:
pip install wheel
The documentation isn't overly clear on this, but "the wheel project provides a bdist_wheel command for setuptools" actually means "the wheel package...".
multi group radio button covert value to array
var arr = [];_x000D_
function r(n) {_x000D_
_x000D_
_x000D_
var section = $('input:radio[name="' + n + '"]:checked').val();_x000D_
arr[n] = section;_x000D_
_x000D_
console.log(arr)_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="radio" onchange="r('b1')" class="radioID" name="b1" value="1">1_x000D_
<input type="radio" onchange="r('b1')" class="radioID" name="b1" value="2" >2_x000D_
<input type="radio" onchange="r('b1')" class="radioID" name="b1" value="3">3_x000D_
_x000D_
<br>_x000D_
_x000D_
<input type="radio" onchange="r('b2')" class="radioID2" name="b2" value="4">4_x000D_
<input type="radio" onchange="r('b2')" class="radioID2" name="b2" value="5" >5_x000D_
<input type="radio" onchange="r('b2')" class="radioID2" name="b2" value="6">6
_x000D_
1: remove dropdown-trigger:
data-toggle="dropdown"
2: add this your css
.dropdown:hover .dropdown-menu {
display: block;
}
.dropdown-menu {
margin-top: 0px;
}
posted for the people how stumbled upon this
You'd have to use reflection
public object GetPropertyValue(object car, string propertyName)
{
return car.GetType().GetProperties()
.Single(pi => pi.Name == propertyName)
.GetValue(car, null);
}
If you want to be really fancy, you could make it an extension method:
public static object GetPropertyValue(this object car, string propertyName)
{
return car.GetType().GetProperties()
.Single(pi => pi.Name == propertyName)
.GetValue(car, null);
}
And then:
string makeValue = (string)car.GetPropertyValue("Make");
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
function NumValidate(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert('Only Number ');
return false;
} return true;
} function NumValidateWithDecimal(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
alert('Only Number With desimal e.g.: 0.0');
return false;
}
else {
return true;
} } function onlyAlphabets(e) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
return true;
else
alert("Only text And White Space And . Allow");
return false;
}
catch (err) {
alert(err.Description);
}} function checkAlphaNumeric(e) {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
return true;
} else {
alert('Only Text And Number');
return false;
}}
Another easier way to print the whole string is to call values
on the dataframe.
df = pd.DataFrame({'one' : ['one', 'two',
'This is very long string very long string very long string veryvery long string']})
print(df.values)
The Output will be
[['one']
['two']
['This is very long string very long string very long string veryvery long string']]
Yes, you can find that under
Tools - > Options - > Projects and Solutions - > Track Active Item in Solution Explorer
It's off by default (as you've noticed), but once it's on, Solution Explorer will expand folders and highlight the current document as you switch between files.
an API(Application Programming Interface) is a set of defined functions and methods for interfacing with the underlying operating system or another program or service running on the computer.
It is usually used by establishing a reference to a library in your software or importing a function from a dll.
It is used in one form or another in almost all software, being explicitly called in your program or implicitly called by the compiler.
You can simulate a readonly select box using the CSS pointer-events property:
select[readonly]
{
pointer-events: none;
}
The HTML tabindex property will also prevent it from being selected by keyboard tabbing:
<select tabindex="-1">
select[readonly]_x000D_
{_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
background: #fafafa;_x000D_
border: 1px solid #ccc;_x000D_
color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
display:block;_x000D_
width: 20rem;_x000D_
padding: 0.5rem;_x000D_
margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="this is a normal text box">_x000D_
<input type="text" readonly value="this is a readonly text box">_x000D_
<select readonly tabindex="-1">_x000D_
<option>This is a readonly select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
<select>_x000D_
<option>This is a normal select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
</form>
_x000D_
Take a look at "SET ROLE" and "SET SESSION AUTHORIZATION".
group by fV.tier_id, f.form_template_id
What you have to do is to set the MinimumHeight property of the row. Not only the Height property. That's the key. Put the code bellow in the CellPainting event of the datagridview
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
foreach(DataGridViewRow x in dataGridView1.Rows)
{
x.MinimumHeight = 50;
}
}
There is build in forEach loop for array in ECMAScript 5th Edition.
var buttons = document.getElementsByClassName("navButton");
Array.prototype.forEach.call(buttons,function(button) {
button.setAttribute("class", "active");
button.setAttribute("src", "images/arrows/top_o.png");
});
Rename the closing function as 'hide', for example and it will work.
function hide() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
}
Yet another solution, assuming the number of items in the folder is not huge:
tar -czf workspace.tar.gz `ls -A`
(ls -A
prints normal and hidden files but not "." and ".." as ls -a
does.)
@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F 31 32 33 34 35 36 37 41 42 43 44 45 46 90 91 92 93 94 95 96 97 100 101 102 103 104 105 106 107
for %%x in (%NUM%) do (
for %%y in (%NUM%) do (
color %%x%%y
cls
echo Himel Sarkar
timeout 1 >nul
)
)
pause
Most Android and iPhone apps I have seen use an initial screen or dialog box to ask for credentials. I think it is cumbersome for the user to have to re-enter their name/password often, so storing that info makes sense from a usability perspective.
The advice from the (Android dev guide) is:
In general, we recommend minimizing the frequency of asking for user credentials -- to make phishing attacks more conspicuous, and less likely to be successful. Instead use an authorization token and refresh it.
Where possible, username and password should not be stored on the device. Instead, perform initial authentication using the username and password supplied by the user, and then use a short-lived, service-specific authorization token.
Using the AccountManger is the best option for storing credentials. The SampleSyncAdapter provides an example of how to use it.
If this is not an option to you for some reason, you can fall back to persisting credentials using the Preferences mechanism. Other applications won't be able to access your preferences, so the user's information is not easily exposed.
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
In terms of a Spring boot application, a bean is simply a Java object which is created by Spring framework when the application starts.
The purpose of the object can be pretty much anything - a configuration, a service, database connection factory etc. - Spring doesn't really care.
Most beans depend on other beans to work, for example an entity manager might need a database connection. Spring framework is able to figure out how the beans should be wired together automatically. From your point of an application developer, you just have to declare the beans you need and they "magically" appear in your application ready to use.
Here's a question and answer for this: Difference between screen.availHeight and window.height()
Has pics too, so you can actually see the differences. Hope this helps.
Basically, $(window).height()
give you the maximum height inside of the browser window (viewport), and$(document).height()
gives you the height of the document inside of the browser. Most of the time, they will be exactly the same, even with scrollbars.
The signature of main
is:
int main(int argc, char **argv);
argc
refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv
contains the actual arguments, starting with index 1. Index 0 is the program name.
So, if you ran your program like this:
./program hello world
Then:
You can list breakpoints with:
info break
This will list all breakpoints. Then a breakpoint can be deleted by its corresponding number:
del 3
For example:
(gdb) info b
Num Type Disp Enb Address What
3 breakpoint keep y 0x004018c3 in timeCorrect at my3.c:215
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
(gdb) del 3
(gdb) info b
Num Type Disp Enb Address What
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
# Pseudo code
# Corners in ax,ay,bx,by,dx,dy
# Point in x, y
bax = bx - ax
bay = by - ay
dax = dx - ax
day = dy - ay
if ((x - ax) * bax + (y - ay) * bay < 0.0) return false
if ((x - bx) * bax + (y - by) * bay > 0.0) return false
if ((x - ax) * dax + (y - ay) * day < 0.0) return false
if ((x - dx) * dax + (y - dy) * day > 0.0) return false
return true
If you're having problems related to dependencies not appearing in the WEB-INF/lib file when running on a Tomcat server in Eclipse, take a look at this:
You simply had to add the Maven Dependencies in Project Properties > Deployment Assembly.
I think doing this way is much simpler:
button.setBackgroundColor(Color.BLACK);
And you need to import android.graphics.Color;
not: import android.R.color;
Or you can just write the 4-byte hex code (not 3-byte) 0xFF000000
where the first byte is setting the alpha.
The accepted answer explained the problem well enough. However, the more Numpythonic approach for applying multiple conditions is to use numpy logical functions. In this case, you can use np.logical_and
:
np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))
You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.
http://jsfiddle.net/ayyadurai/GXzhZ/1/
window.onload = function() {_x000D_
var minute = 5;_x000D_
var sec = 60;_x000D_
setInterval(function() {_x000D_
document.getElementById("timer").innerHTML = minute + " : " + sec;_x000D_
sec--;_x000D_
if (sec == 00) {_x000D_
minute --;_x000D_
sec = 60;_x000D_
if (minute == 0) {_x000D_
minute = 5;_x000D_
}_x000D_
}_x000D_
}, 1000);_x000D_
}
_x000D_
Registration closes in <span id="timer">05:00<span> minutes!
_x000D_
My answer to this question might help, looks like it's similar to the one Diederik cooked up. You may also want to replace the call to NSLog()
with a static instance of your own custom logging class, that way you can add a priority flag for debug/warning/error messages, send messages to a file or database as well as the console, or pretty much whatever else you can think of.
#define DEBUG_MODE
#ifdef DEBUG_MODE
#define DebugLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self,
[[NSString stringWithUTF8String:__FILE__] lastPathComponent],
__LINE__,
[NSString stringWithFormat:(s),
##__VA_ARGS__] )
#else
#define DebugLog( s, ... )
#endif
Assuming Java (JDK + JRE) is installed in your system, do the following steps:
C:>echo %path%
C:\Program Files (x86)\Java\jdk1.6.0_27\bin;%CATALINA_HOME%\bin;
C:>echo %classpath%
C:\Program Files (x86)\Java\jdk1.6.0_27\lib\tools.jar;
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;
C:>echo %CATALINA_HOME%
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0;
C:>echo %JAVA_HOME%
C:\Program Files (x86)\Java\jdk1.6.0_27;
Now you can test whether Tomcat is setup correctly, by typing the following commands in your command prompt:
C:/>javap javax.servlet.ServletException
C:/>javap javax.servlet.http.HttpServletRequest
It should show a bunch of classes
Now start Tomcat service by double clicking on 'Tomcat7.exe' under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\bin'.
Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:
workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"
Only works if your file structure contains one instance of the text used to replace. YMMV.
In the documentaion http://contactform7.com/text-fields/#textarea
[textarea* message id:contact-message 10x2 placeholder "Your Message"]
The above will generate a textarea with cols="10" and rows="2"
<textarea name="message" cols="10" rows="2" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="contact-message" aria-required="true" aria-invalid="false" placeholder="Your Message"></textarea>
The default is Ctrl + F6. You can change it by going to Window preferences. I usually change it to Ctrl + Tab, the same we use in switching tabs in a browser and other stuff.
I saw John Myczek's solution, and its comments about Compatibility to ComboBox
and PasswordBox
, so I improved John Myczek's solution, and here it is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
/// <summary>
/// Class that provides the Watermark attached property
/// </summary>
public static class WatermarkService
{
/// <summary>
/// Watermark Attached Dependency Property
/// </summary>
public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached(
"Watermark",
typeof(object),
typeof(WatermarkService),
new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged)));
#region Private Fields
/// <summary>
/// Dictionary of ItemsControls
/// </summary>
private static readonly Dictionary<object, ItemsControl> itemsControls = new Dictionary<object, ItemsControl>();
#endregion
/// <summary>
/// Gets the Watermark property. This dependency property indicates the watermark for the control.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
/// <returns>The value of the Watermark property</returns>
public static object GetWatermark(DependencyObject d)
{
return (object)d.GetValue(WatermarkProperty);
}
/// <summary>
/// Sets the Watermark property. This dependency property indicates the watermark for the control.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
/// <param name="value">value of the property</param>
public static void SetWatermark(DependencyObject d, object value)
{
d.SetValue(WatermarkProperty, value);
}
/// <summary>
/// Handles changes to the Watermark property.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
/// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Control control = (Control)d;
control.Loaded += Control_Loaded;
if (d is TextBox || d is PasswordBox)
{
control.GotKeyboardFocus += Control_GotKeyboardFocus;
control.LostKeyboardFocus += Control_Loaded;
}
else if (d is ComboBox)
{
control.GotKeyboardFocus += Control_GotKeyboardFocus;
control.LostKeyboardFocus += Control_Loaded;
(d as ComboBox).SelectionChanged += new SelectionChangedEventHandler(SelectionChanged);
}
else if (d is ItemsControl)
{
ItemsControl i = (ItemsControl)d;
// for Items property
i.ItemContainerGenerator.ItemsChanged += ItemsChanged;
itemsControls.Add(i.ItemContainerGenerator, i);
// for ItemsSource property
DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType());
prop.AddValueChanged(i, ItemsSourceChanged);
}
}
/// <summary>
/// Event handler for the selection changed event
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="ItemsChangedEventArgs"/> that contains the event data.</param>
private static void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Control control = (Control)sender;
if (ShouldShowWatermark(control))
{
ShowWatermark(control);
}
else
{
RemoveWatermark(control);
}
}
#region Event Handlers
/// <summary>
/// Handle the GotFocus event on the control
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e)
{
Control c = (Control)sender;
if (ShouldShowWatermark(c))
{
RemoveWatermark(c);
}
}
/// <summary>
/// Handle the Loaded and LostFocus event on the control
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
private static void Control_Loaded(object sender, RoutedEventArgs e)
{
Control control = (Control)sender;
if (ShouldShowWatermark(control))
{
ShowWatermark(control);
}
}
/// <summary>
/// Event handler for the items source changed event
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param>
private static void ItemsSourceChanged(object sender, EventArgs e)
{
ItemsControl c = (ItemsControl)sender;
if (c.ItemsSource != null)
{
if (ShouldShowWatermark(c))
{
ShowWatermark(c);
}
else
{
RemoveWatermark(c);
}
}
else
{
ShowWatermark(c);
}
}
/// <summary>
/// Event handler for the items changed event
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="ItemsChangedEventArgs"/> that contains the event data.</param>
private static void ItemsChanged(object sender, ItemsChangedEventArgs e)
{
ItemsControl control;
if (itemsControls.TryGetValue(sender, out control))
{
if (ShouldShowWatermark(control))
{
ShowWatermark(control);
}
else
{
RemoveWatermark(control);
}
}
}
#endregion
#region Helper Methods
/// <summary>
/// Remove the watermark from the specified element
/// </summary>
/// <param name="control">Element to remove the watermark from</param>
private static void RemoveWatermark(UIElement control)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
// layer could be null if control is no longer in the visual tree
if (layer != null)
{
Adorner[] adorners = layer.GetAdorners(control);
if (adorners == null)
{
return;
}
foreach (Adorner adorner in adorners)
{
if (adorner is WatermarkAdorner)
{
adorner.Visibility = Visibility.Hidden;
layer.Remove(adorner);
}
}
}
}
/// <summary>
/// Show the watermark on the specified control
/// </summary>
/// <param name="control">Control to show the watermark on</param>
private static void ShowWatermark(Control control)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
// layer could be null if control is no longer in the visual tree
if (layer != null)
{
layer.Add(new WatermarkAdorner(control, GetWatermark(control)));
}
}
/// <summary>
/// Indicates whether or not the watermark should be shown on the specified control
/// </summary>
/// <param name="c"><see cref="Control"/> to test</param>
/// <returns>true if the watermark should be shown; false otherwise</returns>
private static bool ShouldShowWatermark(Control c)
{
if (c is ComboBox)
{
return (c as ComboBox).SelectedItem == null;
//return (c as ComboBox).Text == string.Empty;
}
else if (c is TextBoxBase)
{
return (c as TextBox).Text == string.Empty;
}
else if (c is PasswordBox)
{
return (c as PasswordBox).Password == string.Empty;
}
else if (c is ItemsControl)
{
return (c as ItemsControl).Items.Count == 0;
}
else
{
return false;
}
}
#endregion
}
Now, a ComboBox
can be also Editable
, and PasswordBox
can add a watermark too.
Don't forget to use JoanComasFdz's comment above to solve the margin problem.
And, of course, All the credit goes to John Myczek.
On linux, you can run this command and see the result :
ps aux | grep "java"
You need to instantiate the MainViewModel and set it as datacontext. In your statement it just consider it as string value.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
Convert your number to a Numeric
or Decimal
.
Replace your query with the following.
Sql server
Select Convert(Numeric(38, 2), Minutes/60.0) from ....
MySql:
Select Convert(Minutes/60.0, Decimal(65, 2)) from ....
The Cast
function is a wrapper for the Convert
function. Couple that with SQL being an interpreted language and the result is that even though the two functions produce the same results, there is slightly more going on behind the scenes in the Cast
function. Using the Convert
function is a small saving, but small savings multiply. The parameters for Numeric and Decimal (38, 2) and (65, 2) represent the maximum precision level and decimal places to use.
The difference is that one modifies the data-structure itself (in-place operation) b += 1
while the other just reassigns the variable a = a + 1
.
Just for completeness:
x += y
is not always doing an in-place operation, there are (at least) three exceptions:
If x
doesn't implement an __iadd__
method then the x += y
statement is just a shorthand for x = x + y
. This would be the case if x
was something like an int
.
If __iadd__
returns NotImplemented
, Python falls back to x = x + y
.
The __iadd__
method could theoretically be implemented to not work in place. It'd be really weird to do that, though.
As it happens your b
s are numpy.ndarray
s which implements __iadd__
and return itself so your second loop modifies the original array in-place.
You can read more on this in the Python documentation of "Emulating Numeric Types".
These [
__i*__
] methods are called to implement the augmented arithmetic assignments (+=
,-=
,*=
,@=
,/=
,//=
,%=
,**=
,<<=
,>>=
,&=
,^=
,|=
). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an__iadd__()
method,x += y
is equivalent tox = x.__iadd__(y)
. Otherwise,x.__add__(y)
andy.__radd__(x)
are considered, as with the evaluation ofx + y
. In certain situations, augmented assignment can result in unexpected errors (see Why doesa_tuple[i] += ["item"]
raise an exception when the addition works?), but this behavior is in fact part of the data model.
#i'm also maintaining insertion order here
Map<Integer,ArrayList> d=new LinkedHashMap<>();
for( int i=0; i<2; i++)
{
int id=s.nextInt();
ArrayList al=new ArrayList<>();
al.add(s.next()); //name
al.add(s.next()); //category
al.add(s.nextInt()); //fee
d.put(id, al);
}
var dt = new Date();
dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
Since month index are 0 based you have to increment it by 1.
Edit
For a complete list of date object functions see
getMonth()
Returns the month (0-11) in the specified date according to local time.
getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.
You can put it in a different class and then call a function. This works when ajax refresh
$(document).on("change", ".inputQty", function(e) {
//Call a function(input,input);
});
head -Line_number file_name | tail -1 |cut -c Num_of_chars
this script gives the exact number of characters from the specific line and location, e.g.:
head -5 tst.txt | tail -1 |cut -c 5-8
gives the chars in line 5 and chars 5 to 8 of line 5,
Note: tail -1
is used to select the last line displayed by the head.
df <- data.frame(a = 1:2, b = letters[1:2])
df[rep(seq_len(nrow(df)), each = 2), ]
In my recent project my task was to clean an entire database by using sql statement and each table having many constraints like Primary Key and Foreign Key. There are more than 1000 tables in database so its not possible to write a delete query on each and ever table.
By using a stored procedure named sp_MSForEachTable which allows us to easily process some code against each and every table in a single database. It means that it is used to process a single T-SQL command or a different T-SQL commands against every table in the database.
So follow the below steps to truncate all tables in a SQL Server Database:
Step 1- Disable all constraints on the database by using below sql query :
EXEC sys.sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
Step 2- Execute a Delete or truncate operation on each table of the database by using below sql command :
EXEC sys.sp_msforeachtable 'DELETE FROM ?'
Step 3- Enable all constraints on the database by using below sql statement:
EXEC sys.sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit
var thisIsObject= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object
=> {'Cat' : 'Meow', 'Dog' : 'Bark'} //result
If you want to modify the current object, assign the returning object to the current object.
thisIsObject = _.omit(thisIsObject,'Cow');
With pure JavaScript, use:
delete thisIsObject['Cow'];
Another option with pure JavaScript.
thisIsObject.cow = undefined;
thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
Epsilon is a difference between expected
and actual
values which you can accept thinking they are equal. You can set .1
for example.
The source files of your programs are compiled into object files, and then the linker links those object files together, producing an executable file including your architecture's machine codes.
Both object file and executable file involves architecture's machine code in the form of printable and non-printable characters when it's opened by a text editor.
Nonetheless, the dichotomy between the files is that the object file(s) may contain unresolved external references (such as printf
, for instance). So, it may need to be linked against other object files.. That is to say, the unresolved external references are needed to be resolved in order to get the decent runnable executable file by linking with other object files such as C/C++ runtime library's.
Just to add a couple of points:
Because the Validate()
method signature returns IEnumerable<>
, that yield return
can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.Enable)
{
// ...
if (this.Prop1 > this.Prop2)
{
yield return new ValidationResult("Prop1 must be larger than Prop2");
}
Also, if you are using MVC ModelState
, you can convert the validation result failures to ModelState
entries as follows (this might be useful if you are doing the validation in a custom model binder):
var resultsGroupedByMembers = validationResults
.SelectMany(vr => vr.MemberNames
.Select(mn => new { MemberName = mn ?? "",
Error = vr.ErrorMessage }))
.GroupBy(x => x.MemberName);
foreach (var member in resultsGroupedByMembers)
{
ModelState.AddModelError(
member.Key,
string.Join(". ", member.Select(m => m.Error)));
}
Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.
See Common Sequence Operations:
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.
Also Value Comparisons for further details:
Lexicographical comparison between built-in collections works as follows:
- For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example,
[1,2] == (1,2)
is false because the type is not the same).- Collections that support order comparison are ordered the same as their first unequal elements (for example,
[1,2,x] <= [1,2,y]
has the same value asx <= y
). If a corresponding element does not exist, the shorter collection is ordered first (for example,[1,2] < [1,2,3]
is true).
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).
Note 1: <
and >
do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).
Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.
Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.
I use the following method when sending a List<MySerializableObject>
via intent:
List<Thumbnail> thumbList = new ArrayList<>();
//Populate ...
Intent intent = new Intent(context, OtherClass.class);
intent.putExtra("ThumbArray", thumbList.toArray(new Thumbnail[0]));
//Send intent...
And retrieving it like so:
Thumbnail[] thumbArr = (Thumbnail[]) getIntent().getSerializableExtra("ThumbArray");
if (thumbArr != null) {
List<Thumbnail> thumbList = Arrays.asList(thumbArr);
}
For example:
sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
@pl_script_1.sql
@pl_script_2.sql
exit;
EOF
Maybe It is OpenJPA's bug, When rollback it reset the @Version field, but the pcVersionInit keep true. I have a AbstraceEntity which declared the @Version field. I can workaround it by reset the pcVersionInit field. But It is not a good idea. I think it not work when have cascade persist entity.
private static Field PC_VERSION_INIT = null;
static {
try {
PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
PC_VERSION_INIT.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
}
}
public T call(final EntityManager em) {
if (PC_VERSION_INIT != null && isDetached(entity)) {
try {
PC_VERSION_INIT.set(entity, false);
} catch (IllegalArgumentException | IllegalAccessException e) {
}
}
em.persist(entity);
return entity;
}
/**
* @param entity
* @param detached
* @return
*/
private boolean isDetached(final Object entity) {
if (entity instanceof PersistenceCapable) {
PersistenceCapable pc = (PersistenceCapable) entity;
if (pc.pcIsDetached() == Boolean.TRUE) {
return true;
}
}
return false;
}
Ok, you are trying to access the GUI via another thread. This, in the main, is not good practice.
The AsyncTask executes everything in doInBackground()
inside of another thread, which does not have access to the GUI where your views are.
preExecute()
and postExecute()
offer you access to the GUI before and after the heavy lifting occurs in this new thread, and you can even pass the result of the long operation to postExecute()
to then show any results of processing.
See these lines where you are later updating your TextView:
TextView txt = findViewById(R.id.output);
txt.setText("Executed");
Put them in onPostExecute()
.
You will then see your TextView text updated after the doInBackground
completes.
I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
AsyncTask<?, ?, ?> runningTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.button1);
// Because we implement OnClickListener, we only
// have to pass "this" (much easier)
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
if (runningTask != null)
runningTask.cancel(true);
runningTask = new LongOperation();
runningTask.execute();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Cancel running task(s) to avoid memory leaks
if (runningTask != null)
runningTask.cancel(true);
}
private final class LongOperation extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// We were cancelled; stop sleeping!
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// You might want to change "executed" for the returned string
// passed into onPostExecute(), but that is up to you
}
}
}
There are three ways to do what you want
This includes something like php, asp, jsp.... But you said no to that
Your server is serving up the pages so why not take advantage of the built in server side includes? Each server has its own way to do this, take advantage of it.
This solutions has you calling back to the server after page has already been loaded on the client.
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.