Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.
The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?
The big point, and the elephant in the room and all that, is that if your application can get hold of the password, then a hacker with access to the box can get hold of it too!
The only way somewhat around this, is that the application asks for the "master password" on the console using Standard Input, and then uses this to decrypt the passwords stored on file. Of course, this completely makes is impossible to have the application start up unattended along with the OS when it boots.
However, even with this level of annoyance, if a hacker manages to get root access (or even just access as the user running your application), he could dump the memory and find the password there.
The thing to ensure, is to not let the entire company have access to the production server (and thereby to the passwords), and make sure that it is impossible to crack this box!
A good article about realistic password strength estimation is:
Dropbox Tech Blog » Blog Archive » zxcvbn: realistic password strength estimation
In High Sierra, the cacerts is located at : /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/security/cacerts
Basically, with prepared statements the data coming in from a potential hacker is treated as data - and there's no way it can be intermixed with your application SQL and/or be interpreted as SQL (which can happen when data passed in is placed directly into your application SQL).
This is because prepared statements "prepare" the SQL query first to find an efficient query plan, and send the actual values that presumably come in from a form later - at that time the query is actually executed.
More great info here:
What about providing a custom N-Factor authentication mechanism?
Before combining available methods, let's assume we can perform the following:
1) Hard-code inside the Java program
2) Store in a .properties file
3) Ask user to type password from command line
4) Ask user to type password from a form
5) Ask user to load a password-file from command line or a form
6) Provide the password through network
7) many alternatives (eg Draw A Secret, Fingerprint, IP-specific, bla bla bla)
1st option: We could make things more complicated for an attacker by using obfuscation, but this is not considered a good countermeasure. A good coder can easily understand how it works if he/she can access the file. We could even export a per-user binary (or just the obfuscation part or key-part), so an attacker must have access to this user-specific file, not another distro. Again, we should find a way to change passwords, eg by recompiling or using reflection to on-the-fly change class behavior.
2nd option: We can store the password in the .properties file in an encrypted format, so it's not directly visible from an attacker (just like jasypt does). If we need a password manager we'll need a master password too which again should be stored somewhere - inside a .class file, the keystore, kernel, another file or even in memory - all have their pros and cons.
But, now users will just edit the .properties file for password change.
3rd option: type the password when running from command line e.g. java -jar /myprogram.jar -p sdflhjkiweHIUHIU8976hyd
.
This doesn't require the password to be stored and will stay in memory. However, history
commands and OS logs, may be your worst enemy here.
To change passwords on-the-fly, you will need to implement some methods (eg listen for console inputs, RMI, sockets, REST bla bla bla), but the password will always stay in memory.
One can even temporarily decrypt it only when required -> then delete the decrypted, but always keep the encrypted password in memory. Unfortunately, the aforementioned method does not increase security against unauthorized in-memory access, because the person who achieves that, will probably have access to the algorithm, salt and any other secrets being used.
4th option: provide the password from a custom form, rather than the command line. This will circumvent the problem of logging exposure.
5th option: provide a file as a password stored previously on a another medium -> then hard delete file. This will again circumvent the problem of logging exposure, plus no typing is required that could be shoulder-surfing stolen. When a change is required, provide another file, then delete again.
6th option: again to avoid shoulder-surfing, one can implement an RMI method call, to provide the password (through an encrypted channel) from another device, eg via a mobile phone. However, you now need to protect your network channel and access to the other device.
I would choose a combination of the above methods to achieve maximum security so one would have to access the .class files, the property file, logs, network channel, shoulder surfing, man in the middle, other files bla bla bla. This can be easily implemented using a XOR operation between all sub_passwords to produce the actual password.
We can't be protected from unauthorized in-memory access though, this can only be achieved by using some access-restricted hardware (eg smartcards, HSMs, SGX), where everything is computed into them, without anyone, even the legitimate owner being able to access decryption keys or algorithms. Again, one can steal this hardware too, there are reported side-channel attacks that may help attackers in key extraction and in some cases you need to trust another party (eg with SGX you trust Intel). Of course, situation may worsen when secure-enclave cloning (de-assembling) will be possible, but I guess this will take some years to be practical.
Also, one may consider a key sharing solution where the full key is split between different servers. However, upon reconstruction, the full key can be stolen. The only way to mitigate the aforementioned issue is by secure multiparty computation.
We should always keep in mind that whatever the input method, we need to ensure we are not vulnerable from network sniffing (MITM attacks) and/or key-loggers.
Here is a very simplified explanation:
Your web browser downloads the web server's certificate, which contains the public key of the web server. This certificate is signed with the private key of a trusted certificate authority.
Your web browser comes installed with the public keys of all of the major certificate authorities. It uses this public key to verify that the web server's certificate was indeed signed by the trusted certificate authority.
The certificate contains the domain name and/or ip address of the web server. Your web browser confirms with the certificate authority that the address listed in the certificate is the one to which it has an open connection.
Your web browser generates a shared symmetric key which will be used to encrypt the HTTP traffic on this connection; this is much more efficient than using public/private key encryption for everything. Your browser encrypts the symmetric key with the public key of the web server then sends it back, thus ensuring that only the web server can decrypt it, since only the web server has its private key.
Note that the certificate authority (CA) is essential to preventing man-in-the-middle attacks. However, even an unsigned certificate will prevent someone from passively listening in on your encrypted traffic, since they have no way to gain access to your shared symmetric key.
That specifies the how many digits you want it to show.
integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width.
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
It's pretty useful not to let the closing ?>
in.
The file stays valid to PHP (not a syntax error) and as @David Dorward said it allows to avoid having white space / break-line (anything that can send a header to the browser) after the ?>
.
For example,
<?
header("Content-type: image/png");
$img = imagecreatetruecolor ( 10, 10);
imagepng ( $img);
?>
[space here]
[break line here]
won't be valid.
But
<?
header("Content-type: image/png");
$img = imagecreatetruecolor ( 10, 10 );
imagepng ( $img );
will.
For once, you must be lazy to be secure.
To add to Alan Wells's elaborate answer here is a quick fix
you can serve any folder in your computer with Serve
First, navigate using the command line into the folder you'd like to serve.
Then
npx i -g serve
serve
or if you'd like to test Serve without downloading it
npx serve
and that's it! You can view your files at http://localhost:5000
As shown on Removing standard server headers on Windows Azure Web Sites page, you can remove headers with the following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
</customHeaders>
</httpProtocol>
<security>
<requestFiltering removeServerHeader="true"/>
</security>
</system.webServer>
<system.web>
<httpRuntime enableVersionHeader="false" />
</system.web>
</configuration>
This removes the Server header, and the X- headers.
This worked locally in my tests in Visual Studio 2015.
for china GFW:
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
expires_in
)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in
parameter, which is the number of seconds left in the lifetime of the token.
This only works on Windows, so if you are planning to use dotnet core cross-platform, you'll have to look elsewhere. See https://github.com/dotnet/corefx/blob/master/Documentation/architecture/cross-platform-cryptography.md
I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.
I`ve been looking for something like this for ages... So i hope this helps someone!
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;
namespace User
{
public static class UserValidation
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonProviders : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}
enum LogonTypes : uint
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
Unlock = 7,
NetworkCleartext = 8,
NewCredentials = 9
}
public const int ERROR_PASSWORD_MUST_CHANGE = 1907;
public const int ERROR_LOGON_FAILURE = 1326;
public const int ERROR_ACCOUNT_RESTRICTION = 1327;
public const int ERROR_ACCOUNT_DISABLED = 1331;
public const int ERROR_INVALID_LOGON_HOURS = 1328;
public const int ERROR_NO_LOGON_SERVERS = 1311;
public const int ERROR_INVALID_WORKSTATION = 1329;
public const int ERROR_ACCOUNT_LOCKED_OUT = 1909; //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
public const int ERROR_ACCOUNT_EXPIRED = 1793;
public const int ERROR_PASSWORD_EXPIRED = 1330;
public static int CheckUserLogon(string username, string password, string domain_fqdn)
{
int errorCode = 0;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
{
if (!pc.ValidateCredentials(username, password))
{
IntPtr token = new IntPtr();
try
{
if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
{
errorCode = Marshal.GetLastWin32Error();
}
}
catch (Exception)
{
throw;
}
finally
{
CloseHandle(token);
}
}
}
return errorCode;
}
}
For those who want to access a file from an already loaded PowerShell session, either use Unblock-File to mark the file as safe (though you already need to have set a relaxed execution policy like Unrestricted
for this to work), or change the execution policy just for the current PowerShell session:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
I prefer Verification and Permissions to Authentication and Authorization.
It is easier in my head and in my code to think of "verification" and "permissions" because the two words
Authentication is verification and Authorization is checking permission(s). Auth can mean either, but is used more often as "User Auth" i.e. "User Authentication"
You can follow this:
string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();
One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.
I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29
AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.
$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')
Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.
grant select on db_name.some_table to 'pma-user'@'app-server'
I tested lots of solutions. Dynamic password field name, multiple password fields (invisible for fake ones), changing input type from "text" to "password", autocomplete="off", autocomplete="new-password",... but nothing solved it with recent browser.
To get rid of password remember, I finally treated the password as input field, and "blur" the text typed.
It is less "safe" than a native password field since selecting the typed text would show it as clear text, but password is not remembered. It also depends on having Javascript activated.
You will have estimate the risk of using below proposal vs password remember option from navigator.
While password remember can be managed (disbaled per site) by the user, it's fine for a personal computer, not for a "public" or shared computer.
I my case it's for a ERP running on shared computers, so I'll give it a try to my solution below.
<input style="background-color: rgb(239, 179, 196); color: black; text-shadow: none;" name="password" size="10" maxlength="30" onfocus="this.value='';this.style.color='black'; this.style.textShadow='none';" onkeypress="this.style.color='transparent'; this.style.textShadow='1px 1px 6px green';" autocomplete="off" type="text">
According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.
However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.
By using the SqlCommand
and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.
Here is an example, taken from one of the articles above:
private static void UpdateDemographics(Int32 customerID,
string demoXml, string connectionString)
{
// Update the demographics for a store, which is stored
// in an xml column.
string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
+ "WHERE CustomerID = @ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("@demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
For Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\v4.0.30319 Value: SchUseStrongCrypto
You have to set the value to 1.
As you say, REST is good enough for banks so should be good enough for you.
There are two main aspects to security: 1) encryption and 2) identity.
Transmitting in SSL/HTTPS provides encryption over the wire. But you'll also need to make sure that both servers can confirm that they know who they are speaking to. This can be via SSL client certificates, shares secrets, etc.
I'm sure one could make the case that SOAP is "more secure" but probably not in any significant way. The nude motorcyclist analogy is cute but if accurate would imply that the whole internet is insecure.
Using serialize and unserialize on cookies is a security risk. Users (or attackers) can alter cookie data, then when you unserialize it, it could run PHP code on your server. Cookie data should not be trusted. Use JSON instead!
From PHP's site:
Do not pass untrusted user input to
unserialize()
regardless of theoptions
value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (viajson_decode()
andjson_encode()
) if you need to pass serialized data to the user.
If your web server supports Serlvet 3.0 spec, like tomcat 7.0+, you can use below in web.xml
as:
<session-config>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
As mentioned in docs:
HttpOnly: Specifies whether any session tracking cookies created by this web application will be marked as HttpOnly
Secure: Specifies whether any session tracking cookies created by this web application will be marked as secure even if the request that initiated the corresponding session is using plain HTTP instead of HTTPS
Please refer to how to set httponly and session cookie for java web application
The variable $token
is not being retrieved from the session when it's in there
Update:
Example from Microsoft:
Original
This is how I got client certification working and checking that a specific Root CA had issued it as well as it being a specific certificate.
First I edited <src>\.vs\config\applicationhost.config
and made this change: <section name="access" overrideModeDefault="Allow" />
This allows me to edit <system.webServer>
in web.config
and add the following lines which will require a client certification in IIS Express. Note: I edited this for development purposes, do not allow overrides in production.
For production follow a guide like this to set up the IIS:
https://medium.com/@hafizmohammedg/configuring-client-certificates-on-iis-95aef4174ddb
web.config:
<security>
<access sslFlags="Ssl,SslNegotiateCert,SslRequireCert" />
</security>
API Controller:
[RequireSpecificCert]
public class ValuesController : ApiController
{
// GET api/values
public IHttpActionResult Get()
{
return Ok("It works!");
}
}
Attribute:
public class RequireSpecificCertAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
X509Certificate2 cert = actionContext.Request.GetClientCertificate();
if (cert == null)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Client Certificate Required"
};
}
else
{
X509Chain chain = new X509Chain();
//Needed because the error "The revocation function was unable to check revocation for the certificate" happened to me otherwise
chain.ChainPolicy = new X509ChainPolicy()
{
RevocationMode = X509RevocationMode.NoCheck,
};
try
{
var chainBuilt = chain.Build(cert);
Debug.WriteLine(string.Format("Chain building status: {0}", chainBuilt));
var validCert = CheckCertificate(chain, cert);
if (chainBuilt == false || validCert == false)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Client Certificate not valid"
};
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
Debug.WriteLine(string.Format("Chain error: {0} {1}", chainStatus.Status, chainStatus.StatusInformation));
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
base.OnAuthorization(actionContext);
}
}
private bool CheckCertificate(X509Chain chain, X509Certificate2 cert)
{
var rootThumbprint = WebConfigurationManager.AppSettings["rootThumbprint"].ToUpper().Replace(" ", string.Empty);
var clientThumbprint = WebConfigurationManager.AppSettings["clientThumbprint"].ToUpper().Replace(" ", string.Empty);
//Check that the certificate have been issued by a specific Root Certificate
var validRoot = chain.ChainElements.Cast<X509ChainElement>().Any(x => x.Certificate.Thumbprint.Equals(rootThumbprint, StringComparison.InvariantCultureIgnoreCase));
//Check that the certificate thumbprint matches our expected thumbprint
var validCert = cert.Thumbprint.Equals(clientThumbprint, StringComparison.InvariantCultureIgnoreCase);
return validRoot && validCert;
}
}
Can then call the API with client certification like this, tested from another web project.
[RoutePrefix("api/certificatetest")]
public class CertificateTestController : ApiController
{
public IHttpActionResult Get()
{
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(GetClientCert());
handler.UseProxy = false;
var client = new HttpClient(handler);
var result = client.GetAsync("https://localhost:44331/api/values").GetAwaiter().GetResult();
var resultString = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return Ok(resultString);
}
private static X509Certificate GetClientCert()
{
X509Store store = null;
try
{
store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
var certificateSerialNumber= "?81 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);
//Does not work for some reason, could be culture related
//var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);
//if (certs.Count == 1)
//{
// var cert = certs[0];
// return cert;
//}
var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));
return cert;
}
finally
{
store?.Close();
}
}
}
No, they are not always.
It depends on whether you allow user input to be placed within the query itself. For example:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
would be vulnerable to SQL injections and using prepared statements in this example won't work, because the user input is used as an identifier, not as data. The right answer here would be to use some sort of filtering/validation like:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$allowedTables = array('users','admins','moderators');
if (!in_array($tableToUse,$allowedTables))
$tableToUse = 'users';
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
Note: you can't use PDO to bind data that goes outside of DDL (Data Definition Language), i.e. this does not work:
$stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');
The reason why the above does not work is because DESC
and ASC
are not data. PDO can only escape for data. Secondly, you can't even put '
quotes around it. The only way to allow user chosen sorting is to manually filter and check that it's either DESC
or ASC
.
You can use SRP to use secure passwords over an insecure channel. The advantage is that even if an attacker sniffs the traffic, or compromises the server, they can't use the passwords on a different server. https://github.com/alax/jsrp is a javascript library that supports secure passwords over HTTP in the browser, or server side (via node).
I'm assuming cross-domain iFrame since presumably the risk would be lower if you controlled it yourself.
Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.
It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.
remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.
http://en.wikipedia.org/wiki/File:IP_stack_connections.svg
that's the long way of saying, "Yes!"
The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:
ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() );
Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.
Code that does AES encyrption:
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Test
{
final String ALGORITHM = "AES"; //symmetric algorithm for data encryption
final String PADDING_MODE = "/CBC/PKCS5Padding"; //Padding for symmetric algorithm
final String CHAR_ENCODING = "UTF-8"; //character encoding
//final String CRYPTO_PROVIDER = "SunMSCAPI"; //provider for the crypto
int AES_KEY_SIZE = 256; //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files installed
private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
{
byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);
//get the symmetric key generator
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(AES_KEY_SIZE); //set the key size
//generate the key
SecretKey skey = keyGen.generateKey();
//convert to binary
byte[] rawAesKey = skey.getEncoded();
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);
//set it to encrypt mode, with the generated key
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
//get the initialization vector being used (to be returned)
byte[] aesIV = aesCipher.getIV();
//encrypt the data
byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);
//set it to decrypt mode with the AES key, and IV
aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));
//decrypt and return the data
byte[] decryptedData = aesCipherDec.doFinal(encryptedData);
return new String(decryptedData, CHAR_ENCODING);
}
public static void main(String[] args)
{
String text = "Lets encrypt me";
Test test = new Test();
try {
System.out.println(test.doCrypto(text));
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Does this code work for you?
You might also want to try specifying your bouncy castle provider in this line:
Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");
And see if it could be an error associated with bouncy castle.
I'd thoroughly recommend reading the articles Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes [dead link, copy at the Internet Archive] and How To Safely Store A Password.
Lots of coders, myself included, think they understand security and hashing. Sadly most of us just don't.
I don't understand the concept of storing encrypted stuff in a cookie when it is the encrypted version of it that you need to do your hacking. If I'm missing something, please comment.
I am thinking about taking this approach to 'Remember Me'. If you can see any issues, please comment.
Create a table to store "Remember Me" data in - separate to the user table so that I can log in from multiple devices.
On successful login (with Remember Me ticked):
a) Generate a unique random string to be used as the UserID on this machine: bigUserID
b) Generate a unique random string: bigKey
c) Store a cookie: bigUserID:bigKey
d) In the "Remember Me" table, add a record with: UserID, IP Address, bigUserID, bigKey
If trying to access something that requires login:
a) Check for the cookie and search for bigUserID & bigKey with a matching IP address
b) If you find it, Log the person in but set a flag in the user table "soft login" so that for any dangerous operations, you can prompt for a full login.
On logout, Mark all the "Remember Me" records for that user as expired.
The only vulnerabilities that I can see is;
The SSL only helps with sniffing attacks. If an attacker has access to your machine I will assume they can copy your secure cookie too.
At the very least, make sure old cookies lose their value after a while. Even a successful hijaking attack will be thwarted when the cookie stops working. If the user has a cookie from a session that logged in more than a month ago, make them reenter their password. Make sure that whenever a user clicks on your site's "log out" link, that the old session UUID can never be used again.
I'm not sure if this idea will work but here goes: Add a serial number into your session cookie, maybe a string like this:
SessionUUID, Serial Num, Current Date/Time
Encrypt this string and use it as your session cookie. Regularly change the serial num - maybe when the cookie is 5 minutes old and then reissue the cookie. You could even reissue it on every page view if you wanted to. On the server side, keep a record of the last serial num you've issued for that session. If someone ever sends a cookie with the wrong serial number it means that an attacker may be using a cookie they intercepted earlier so invalidate the session UUID and ask the user to reenter their password and then reissue a new cookie.
Remember that your user may have more than one computer so they may have more than one active session. Don't do something that forces them to log in again every time they switch between computers.
I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.
This one does not use SendKeys.
Let me know if this helps! JFV
What this means is that your web page is referring to content which is in the folder one level up from your page, but your page is already in the website's root folder, so the relative path is invalid. Judging by your exception message it looks like an image control is causing the problem.
You must have something like:
<asp:Image ImageUrl="..\foo.jpg" />
But since the page itself is in the root folder of the website, it cannot refer to content one level up, which is what the leading ..\
is doing.
Below are the steps to do revoke your JWT access token:
Please let me know if you need more details, I can share the code (Java + Spring boot) as well.
For your questions:
Q1: It's another JWT with fewer claims put in with long expiry time.
Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.
Q3: Yes, Correct
For port 80 (which was the original question), Daniel is exactly right. I recently moved to https
and had to switch from iptables
to a light nginx proxy managing the SSL certs. I found a useful answer along with a gist by gabrielhpugliese on how to handle that. Basically I
Created an SSL Certificate Signing Request (CSR) via OpenSSL
openssl genrsa 2048 > private-key.pem
openssl req -new -key private-key.pem -out csr.pem
Changed the location
in /etc/nginx/conf.d/example_ssl.conf
to
location / {
proxy_pass http://localhost:3000;
proxy_set_header X-Real-IP $remote_addr;
}
Formatted the cert for nginx by cat
-ing the individual certs together and linked to it in my nginx example_ssl.conf
file (and uncommented stuff, got rid of 'example' in the name,...)
ssl_certificate /etc/nginx/ssl/cert_bundle.cert;
ssl_certificate_key /etc/nginx/ssl/private-key.pem;
Hopefully that can save someone else some headaches. I'm sure there's a pure-node way of doing this, but nginx was quick and it worked.
OS X keychain equivalent is Credential Manager in windows.
Most of the other answers here are somewhat out-of-date with today's best practices. As such here is the application of using PBKDF2/Rfc2898DeriveBytes
to store and verify passwords. The following code is in a stand-alone class in this post: Another example of how to store a salted password hash. The basics are really easy, so here it is broken down:
STEP 1 Create the salt value with a cryptographic PRNG:
byte[] salt;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);
STEP 2 Create the Rfc2898DeriveBytes and get the hash value:
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100000);
byte[] hash = pbkdf2.GetBytes(20);
STEP 3 Combine the salt and password bytes for later use:
byte[] hashBytes = new byte[36];
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);
STEP 4 Turn the combined salt+hash into a string for storage
string savedPasswordHash = Convert.ToBase64String(hashBytes);
DBContext.AddUser(new User { ..., Password = savedPasswordHash });
STEP 5 Verify the user-entered password against a stored password
/* Fetch the stored value */
string savedPasswordHash = DBContext.GetUser(u => u.UserName == user).Password;
/* Extract the bytes */
byte[] hashBytes = Convert.FromBase64String(savedPasswordHash);
/* Get the salt */
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
/* Compute the hash on the password the user entered */
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100000);
byte[] hash = pbkdf2.GetBytes(20);
/* Compare the results */
for (int i=0; i < 20; i++)
if (hashBytes[i+16] != hash[i])
throw new UnauthorizedAccessException();
Note: Depending on the performance requirements of your specific application, the value 100000
can be reduced. A minimum value should be around 10000
.
App_Data is essentially a storage point for file-based data stores (as opposed to a SQL server database store for example). Some simple sites make use of it for content stored as XML for example, typically where hosting charges for a DB are expensive.
There is no added security.
Post data does not show up in the history and/or log files but if the data should be kept secure, you need SSL.
Otherwise, anybody sniffing the wire can read your data anyway.
Sharing my methods in case someone needs them:
/** Determines if the context calling has the required permission
* @param context - the IPC context
* @param permissions - The permissions to check
* @return true if the IPC has the granted permission
*/
public static boolean hasPermission(Context context, String permission) {
int res = context.checkCallingOrSelfPermission(permission);
Log.v(TAG, "permission: " + permission + " = \t\t" +
(res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));
return res == PackageManager.PERMISSION_GRANTED;
}
/** Determines if the context calling has the required permissions
* @param context - the IPC context
* @param permissions - The permissions to check
* @return true if the IPC has the granted permission
*/
public static boolean hasPermissions(Context context, String... permissions) {
boolean hasAllPermissions = true;
for(String permission : permissions) {
//you can return false instead of assigning, but by assigning you can log all permission values
if (! hasPermission(context, permission)) {hasAllPermissions = false; }
}
return hasAllPermissions;
}
And to call it:
boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {
android.Manifest.permission.ACCESS_WIFI_STATE,
android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.ACCESS_NETWORK_STATE,
android.Manifest.permission.INTERNET,
});
I had this error- it happened because my password expired and I had to change it. I didn't notice it, because in some programs I could still log in and everything would work normally (including windows), but I couldn't log to any sql servers.
I will suggest its not a good idea to turn off the password expiration as it can lead to possible threats to confidentiality, integrity and availability of data.
However if you want so.
If you have proper access use following SQL
SELECT username, account_status FROM dba_users;
This should give you result like this.
USERNAME ACCOUNT_STATUS
------------------------------ -----------------
SYSTEM OPEN
SYS OPEN
SDMADM OPEN
MARKETPLACE OPEN
SCHEMAOWNER OPEN
ANONYMOUS OPEN
SCHEMAOWNER2 OPEN
SDMADM2 OPEN
SCHEMAOWNER1 OPEN
SDMADM1 OPEN
HR EXPIRED(GRACE)
USERNAME ACCOUNT_STATUS
------------------------------ -----------------
APEX_PUBLIC_USER LOCKED
APEX_040000 LOCKED
FLOWS_FILES LOCKED
XS$NULL EXPIRED & LOCKED
OUTLN EXPIRED & LOCKED
XDB EXPIRED & LOCKED
CTXSYS EXPIRED & LOCKED
MDSYS EXPIRED & LOCKED
Now you can use Pedro Carriço answer https://stackoverflow.com/a/6777079/2432468
Just do it the usual way and then insert it using SecurityContextHolder.setContext()
in your test class, for example:
Controller:
Authentication a = SecurityContextHolder.getContext().getAuthentication();
Test:
Authentication authentication = Mockito.mock(Authentication.class);
// Mockito.whens() for your authorization object
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
Just document it here
on Windows you need to escape the \
character:
"e:\\directory\\-"
IF privileges are given to a user through some roles, then below SQL can be used
select * from ROLE_ROLE_PRIVS where ROLE = 'ROLE_NAME';
select * from ROLE_TAB_PRIVS where ROLE = 'ROLE_NAME';
select * from ROLE_SYS_PRIVS where ROLE = 'ROLE_NAME';
Although we should agree that ultimately you cannot prevent some form of document capture (specially through screen capture technology either through phone or computer), the goal is to prevent direct download of original document. Some suggest you turn it into images, but this is not necessary. There is clearly a way, as several cloud services allow you to share pdf files, removing the download option, without converting the PDF to images (a superior method because it retains important properties like word search). Personally, as a user of Outlook email, I use the cloud service it provides, OneDrive. I just want to share the HTML code produced by OneDrive to share PDF files without download and right-click support. I am no expert on HTMl so cannot tell you exactly how it is done, but it might still provide you some insights. Here is the code for one particular PDF I shared (without private information and other bits that seemed unnecessary to me):
<!DOCTYPE html>
<html lang="en-us" dir="ltr">
<head><meta name="GENERATOR" content="Microsoft SharePoint" /><meta http-equiv="Content-type" content="text/html; charset=utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta http-equiv="Expires" content="0" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" /><title>
OneDrive for Business
</title><link rel="shortcut icon" href="/_layouts/15/images/odbfavicon.ico?rev=47" type="image/vnd.microsoft.icon" id="favicon" /></head>
<body style="margin: 0; padding: 0;">
<script nonce= '55c3d852-fe79-49b0-927d-e793a0ba3192' >if(!spfxPerfMarks){var spfxPerfMarks = {};} var markPerfStage=function(key) {if(window.performance && typeof window.performance.now === 'function'){spfxPerfMarks[key]=window.performance.now();} else{spfxPerfMarks[key]=Date.now();} if (window.performance && typeof window.performance.mark === 'function') {window.performance.mark(key);}};</script><script type="text/javascript" id="SuiteNavShellCore" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192" crossorigin="anonymous" src="https://shellprod.msocdn.com/api/shellbootstrapper/business/oneshell">
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
window.document.getElementById('SuiteNavShellCore').addEventListener('error', function() {
var scriptElem = document.getElementById('SuiteNavShellCore');
scriptElem.parentNode.removeChild(scriptElem);
var newScript = document.createElement('script');
newScript.setAttribute('type', 'text/javascript');
newScript.setAttribute('id', 'SuiteNavShellCore');
newScript.setAttribute('src', 'https://shellprod.msocdn.com/api/shellbootstrapper/business/oneshell');
newScript.setAttribute('crossorigin', 'anonymous');
newScript.async = true;
newScript.addEventListener('load', function() { (typeof markPerfStage === 'function' && markPerfStage('suiteNavScriptAsyncEnd')); if (window.executeSuiteNavOnce) { window.executeSuiteNavOnce() } });
newScript.addEventListener('error', function() { window.o365ShellScriptLoadError = arguments[0]; (typeof markPerfStage === 'function' && markPerfStage('suiteNavScriptError')); if (window.executeSuiteNavOnce) { window.executeSuiteNavOnce() } });
document.head.appendChild(newScript); });
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
window.o365ShellLoadPromiseResolve = undefined; window.o365ShellLoadPromiseReject = undefined; window.o365ShellRenderPromiseResolve = undefined; window.o365ShellRenderPromiseReject = undefined; window.o365ShellPostRenderPromiseResolve = undefined; window.o365ShellPostRenderPromiseReject = undefined; window.o365ShellLoadPromise = new Promise(function (loadResolve, loadReject) { window.o365ShellLoadPromiseResolve = loadResolve, window.o365ShellLoadPromiseReject = loadReject }); window.o365ShellRenderPromise = new Promise(function (renderResolve, renderReject) { window.o365ShellRenderPromiseResolve = renderResolve, window.o365ShellRenderPromiseReject = renderReject }); window.o365ShellPostRenderPromise = new Promise(function (prResolve,prReject) { window.o365ShellPostRenderPromiseResolve = prResolve, window.o365ShellPostRenderPromiseReject = prReject });var executeSuiteNav = function () {var suiteNavPlaceholder = document.createElement('div');suiteNavPlaceholder.id = 'SuiteNavPlaceholder';suiteNavPlaceholder.style = "min-height: 50px";document.body.insertBefore(suiteNavPlaceholder, document.body.firstChild);if (window.o365ShellScriptLoadError) {o365ShellLoadPromiseReject(window.o365ShellScriptLoadError);o365ShellRenderPromiseReject(new Error('SuiteNavLoadError'));o365ShellPostRenderPromiseReject(new Error('SuiteNavLoadError'));return; }o365ShellLoadPromiseResolve();var themeData;try { themeData = JSON.parse(localStorage.getItem('odSuiteNavthemedata')).themeData; }catch(err) { themeData = {Primary:'#0078D4'}; }(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncStart'));O365Shell.RenderAsync({top: 'SuiteNavPlaceholder', layout: 'Mouse', enableSearchUX: true, initialSearchUXVisibility: true, initialSearchUXPlaceholderText: 'Search', initialSearchUXSearchText: "",enableDelayLoading: true, collapseO365Settings: true, disableDelayLoad: false, disableShellPlus: false, isThinHeader: false, enableLegacyResponsiveBehavior: false, expectSearchBoxSettings: true, shellDataOverrides: {}, supportShyHeaderMode: false, initialRenderData: { AppBrandTheme: themeData, Culture: 'en-US', CurrentMainLinkElementId: 'ShellDocuments', IsConsumer: false, UserDisplayName: 'JOHN DOE', UserID: '100320009e7b358d', WorkloadId: 'Sharepoint', ShellBootHost: 'https://shellprod.msocdn.com', EnableVanillaSearchBox: true }},function () {(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncEnd'));o365ShellRenderPromiseResolve();},function () {(typeof markPerfStage === 'function' && markPerfStage('suiteNavPostRender'));o365ShellPostRenderPromiseResolve();},function (error) {(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncErrorEnd'));o365ShellRenderPromiseReject(error); o365ShellPostRenderPromiseReject(error);});};
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
var params = window.location.search.substring(1).split('&') || [];
var shouldExecuteSuiteNav = true;
shouldExecuteSuiteNav &= params.indexOf('p=2') === -1;
shouldExecuteSuiteNav &= params.indexOf('cl=true') === -1;
shouldExecuteSuiteNav &= params.filter(function (x) { return x.indexOf('parent') === 0; }).length === 0;
try { shouldExecuteSuiteNav &= window.parent === window; } catch(err) { shouldExecuteSuiteNav = false; }
if (shouldExecuteSuiteNav) { executeSuiteNav(); }
</script>
</body>
<script type="text/javascript">
try {
(function() {
var a = navigator.userAgent.toLowerCase();
var i = a.indexOf("msie");
if (-1 !== i) {
var v = parseInt(a.substring(i + 5));
if (v <= 8 && Boolean(document.documentMode) && document.documentMode <= 8) {
var d = new Date(); d.setTime(d.getTime() + 31536000000);
document.cookie = "odbnu=0;expires=" + d.toUTCString() + ";path=/";
window.location.href = window.location.href.replace(/\/onedrive\.aspx/i, '/start.aspx#/Documents/Forms/All.aspx');
}
}
})();
} catch(e) {}
</script>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
SOME PRIVATE STUFF HERE
</script><link rel="preconnect" href="https://spoprod-a.akamaihd.net" crossorigin /><script type="text/javascript">
!function(){if('PerformanceLongTaskTiming' in window){var g=window.__tti={e:[]};g.o=new PerformanceObserver(function(l){g.e=g.e.concat(l.getEntries())});g.o.observe({entryTypes:['longtask']})}}();
</script><script type="text/javascript">
var g_responseEnd = new Date().getTime();window['FabricConfig'] = { fontBaseUrl: ''};window['__odsp_culture'] = 'en-us';window['__odspSriHashes'] = {"listviewdataprefetch-mini-c82c051f.js":"sha256-GCNR9Rk+cuSJfvbszuhs5ZBaUs5tQ2RdzzJTteHOXGk=","reactandknockout-mini-584215d6.js":"sha256-ICjqvvD9qHiKbj5xYFNGC/JsgNcqNRRL1t3kW4RVioI=","aria-mini-2e5a74c4.js":"sha256-CbCwYga9yHE+t1OvB+NHHDdH2rxSfY6KJkCMiUpXQjw=","spectreviewer-mini-9c641fce.js":"sha256-tqmAhKxEONjZOpZuGrbo8VdnLx6kRH+Xfhjrcchv2+4=","babylonjs-mini-22e57381.js":"sha256-T6IgL4CdkolwNC0L4tG6d+G07Bhuc7bI1pSIShdrTUk=","sp-http_odb-mini-21a5eb98.js":"sha256-mTfdqB83ALG/d2z8krhrUugjXBzFQ/bzPfUIgcayACg=","onedriveappfontsplt-mini-ce0e18ec.js":"sha256-+ockQ4cjstrmVqBPVRH8C9Z9M0ZJbyQxHQ/cm/ukBOI=","onedriveappfontsdeferred-mini-3771cbb9.js":"sha256-qXZjhCWJDNPCbbXRIwDt1cqIyqzQKqROnwdASmSsoGw=","odbonedriveapp-mini-11081db7.js":"sha256-j/CkxuEVbtMOL5PRKZ05dZURZ/aNH9tk6vnMj6ei/lk=","en-us/
</script><script type="text/javascript">
window['moduleNameMapping']={"odsp-next/providers/operation/OperationProvider":"Rq"};
</script><script type="text/javascript" data-import-link="https://spoprod-a.akamaihd.net/files/odsp-common-library-prod_2019-02-15_20190219.002/require.js" id="requireJsString">
SOME VERY LONG FUNCTION CODE
</script><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/listviewdataprefetch-mini-c82c051f.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/reactandknockout-mini-584215d6.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbonedriveapp-mini-11081db7.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbonedriveapp-mini.resx-7f957d5c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbonedrive-mini-5e8b1855.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbonedrive-mini.resx-374bb468.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbfiles-mini-9aaee23c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbfiles-mini.resx-250da06d.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbitemsscope-mini-5070e33c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbitemsscope-mini.resx-ff223e24.js" rel="preload" crossorigin="anonymous" as="script" /><script type="text/javascript" id="requireConfig">
!function(){
var backupBaseUrl = 'https://az741266.vo.msecnd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/';
window.__backupBaseUrl = backupBaseUrl;
var failOverState = window.__cdnFailOverState = {
baseUrlFailedOver: false,
modulesFalledBack: []
};
function processConfigToSupportFailOver(config) {
var paths = {};
for (var bundleId in config.bundles) {
var bundlePath = config.paths[bundleId];
var fallbackPaths = [bundlePath, backupBaseUrl + bundlePath];
for (var _i = 0, _a = config.bundles[bundleId]; _i < _a.length; _i++) {
var moduleName = _a[_i];
paths[moduleName] = fallbackPaths;
}
}
return {
paths: paths,
shim: config.shim,
deps: config.deps,
baseUrl: config.baseUrl,
waitSeconds: config.waitSeconds,
onNodeCreated: config.onNodeCreated,
enforceDefine: config.enforceDefine,
onPathFallback: function (options) {
var moduleId = options.moduleId;
var config = options.config;
if (moduleId && config && config.deps && config.deps.indexOf(moduleId) >= 0) {
var failedModules = failOverState.modulesFalledBack;
failedModules.push(moduleId);
if (!failOverState.baseUrlFailedOver && failedModules.length >= 2) {
require.config({
baseUrl: backupBaseUrl
});
failOverState.baseUrlFailedOver = true;
}
}
}
};
}
var config = {paths:{"listviewdataprefetch-mini":"listviewdataprefetch-mini-c82c051f","reactandknockout-mini":"reactandknockout-mini-584215d6","aria-mini":"aria-mini-2e5a74c4","spectreviewer-mini":"spectreviewer-mini-9c641fce","babylonjs-mini":"babylonjs-mini-22e57381","sp-http_odb-mini":"sp-http_odb-mini-21a5eb98","onedriveappfontsplt-mini":"onedriveappfontsplt-mini-ce0e18ec","onedriveappfontsdeferred-mini":"onedriveappfontsdeferred-mini-3771cbb9","odbonedriveapp-mini":"odbonedriveapp-mini-11081db7","odbonedriveapp-mini.resx":"en-us/odbonedriveapp-mini.resx-7f957d5c","odbonedrive-mini":"odbonedrive-mini-5e8b1855","odbonedrive-mini.resx":"en-us/odbonedrive-mini.resx-374bb468","odbbasepage-mini":"odbbasepage-mini-8d7dea71","odbfiles-mini":"odbfiles-mini-9aaee23c","odbfiles-mini.resx":"en-us/odbfiles-mini.resx-250da06d","odbuploadmanager-mini":"odbuploadmanager-mini-168f0ee8","odbuploadmanager-mini.resx":"en-us/odbuploadmanager-mini.resx-660b735c","odbreactcontrols-mini":"odbreactcontrols-mini-6f323ced","odbreactcontrols-mini.resx":"en-us/odbreactcontrols-mini.resx-c7ec26e2","odbdeferred-mini":"odbdeferred-mini-b9def3da","odbdeferred-mini.resx":"en-us/odbdeferred-mini.resx-d1f98f82","odblivepersonapicker-mini":"odblivepersonapicker-mini-414c6f81","odbdebugwindow-mini":"odbdebugwindow-mini-2f4ef22c","odbfilepicker-mini":"odbfilepicker-mini-2f5a2203","odbfilepicker-mini.resx":"en-us/odbfilepicker-mini.resx-3562db06","odbembed-mini":"odbembed-mini-8638d6c3","odboneup-mini":"odboneup-mini-3086899d","odboneup-mini.resx":"en-us/odboneup-mini.resx-a7d40d5e","odbpdf-mini":"odbpdf-mini-7d046eb1","odbpdf-mini.resx":"en-us/odbpdf-mini.resx-e5e07b77","odbwrs-mini":"odbwrs-mini-2c0b0a8b","odbsharepage-mini":"odbsharepage-mini-e62fc2f8","odbtextfileeditor-mini":"odbtextfileeditor-mini-000ede78","odbtextfileeditor-mini.resx":"en-us/odbtextfileeditor-mini.resx-259dbac3","odbfilerequestpage-mini":"odbfilerequestpage-mini-db0e14b3","odbfilerequestpage-mini.resx":"en-us/odbfilerequestpage-mini.resx-8e83db21","odbtiles-mini":"odbtiles-mini-a111ffa2","odbtiles-mini.resx":"en-us/odbtiles-mini.resx-4fae993b","odbsites-mini":"odbsites-mini-c5563389","odbsites-mini.resx":"en-us/odbsites-mini.resx-1b3b4aeb","odbitemvideoplayer-mini":"odbitemvideoplayer-mini-b7a61bf1","odbitemvideoplayer-mini.resx":"en-us/odbitemvideoplayer-mini.resx-983d47a8","odbexecutors-mini":"odbexecutors-mini-f93c0ada","odbexecutors-mini.resx":"en-us/odbexecutors-mini.resx-853081e6","odbdeferredcontrols-mini":"odbdeferredcontrols-mini-29643ad1","odbdeferredcontrols-mini.resx":"en-us/odbdeferredcontrols-mini.resx-d50ca5ed","odbnotifications-mini":"odbnotifications-mini-04da08b9","odbpushchannel-mini":"odbpushchannel-mini-38d90d10","odberror-mini":"odberror-mini-12596c1d","odberror-mini.resx":"en-us/odberror-mini.resx-cf31139d","odbrestore-mini":"odbrestore-mini-950ba62f","odbrestore-mini.resx":"en-us/odbrestore-mini.resx-3a5cbe8e","odbsettingsbasepage-mini":"odbsettingsbasepage-mini-d6c5acdd","odbsettingsbasepage-mini.resx":"en-us/odbsettingsbasepage-mini.resx-b5949852","odbsettings-mini":"odbsettings-mini-ddeab1d1","odbitemsscope-mini":"odbitemsscope-mini-5070e33c","odbitemsscope-mini.resx":"en-us/odbitemsscope-mini.resx-ff223e24","odbitemsscopedeferred-mini":"odbitemsscopedeferred-mini-f918897a","odbitemsscopedeferred-mini.resx":"en-us/odbitemsscopedeferred-mini.resx-af61a995","odbmobileappupsellbasepage-mini":"odbmobileappupsellbasepage-mini-723e546a","odbemptyfolderroot-mini":"odbemptyfolderroot-mini-f9f096eb","odbwinappcommunicator-mini":"odbwinappcommunicator-mini-60ab2c1a","odbcreatesite-mini":"odbcreatesite-mini-5400c9ec","odbcreatesite-mini.resx":"en-us/odbcreatesite-mini.resx-d9c236d6","odb-functional-tests-mini":"odb-functional-tests-mini-41e66bd6","odbhighcharts-mini":"odbhighcharts-mini-ce7056aa","odbclientform-mini":"odbclientform-mini-106b2b9f","odbclientform-mini.resx":"en-us/odbclientform-mini.resx-356af9e8","odbfloodgate-mini":"odbfloodgate-mini-061846b3","odbfloodgate-mini.resx":"en-us/odbfloodgate-mini.resx-610e7422","odbpowerapps-mini":"odbpowerapps-mini-c5977eac","msflowsdk":"msflowsdk-8689f64f","power-app":"power-app-86d2bb4d"},"directional-navigation":{}},deps:["bL3","f","bvB","a6o","buW","buZ","bfi"],baseUrl:"https:\u002f\u002fspoprod-a.akamaihd.net\u002ffiles\u002fodsp-next-prod-amd_2020-06-12_20200612.001\u002f",waitSeconds:0,onNodeCreated:function(n,c,m,u) {
n.setAttribute("crossorigin","anonymous");
var urlParts = u.split('/');
var fileName = urlParts[urlParts.length - 1];
var odspSriHashes = window.__odspSriHashes;
var integrity = odspSriHashes && (odspSriHashes[window.__odsp_culture + '/' + fileName] || odspSriHashes[fileName]);
if (integrity) {
n.setAttribute("integrity",integrity);
}
},enforceDefine:true};
var newConfig = processConfigToSupportFailOver(config);
require.config(newConfig);
}();
</script><script type="text/javascript">
window["_spModuleLink"]={"buildNumber":"odsp-next-prod-amd_2020-06-12_20200612.001","manifestName":"ODBOneDrive","scenarioName":"ODBOneDrive","usingRedirectCookie":false,"bugLinkFormat":null,"ulsLinkFormat":null};
</script>
</html>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
var g_duration = 92;
var g_iisLatency = 2;
var g_cpuDuration = 72;
var g_queryCount = 6;
var g_queryDuration = 18;
var g_requireJSDone = new Date().getTime();
</script><script type="text/javascript">
var _spOneDrivePageDataCache = {"SPHomeWeb:sites/feed":{"cacheContext":{"ListItemId":3,"Hash":null,"MySiteUrl":null,"Time":"2020-05-28T15:24:51.0000000Z","Version":null},"cacheValue":null},"ODBWeb.sites/feed":{"cacheContext":{"ListItemId":4,"Hash":"7iItaPeKRTNyNthQTkF2/CvVyjcOTjNOkCsKnNsKarY=","MySiteUrl":null,"Time":"2020-05-28T15:25:03.0000000Z","Version":"1.0"},"cacheValue":"{\"Items\":[],\"Type\":\"ItemsList\"}"},"ODBWeb.substrate.recommended":{"cacheContext":{"ListItemId":5,"Hash":null,"MySiteUrl":null,"Time":"2020-05-28T15:24:51.0000000Z","Version":null},"cacheValue":null}};
</script>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
var g_deferDataLoadTime = new Date().getTime();var g_payload = {"parameters":{"__metadata":{"type":"SP.RenderListDataParameters"},"RenderOptions":1513223,"AllowMultipleValueFilterForTaxonomyFields":true, "AddRequiredFields":true}}; var g_listData = {"wpq":"","Templates":{},"ListData":{ "Row" :
[] OTHER SETTINGS WITH PRIVATE STUFF...
}};if (typeof DeferredListDataComplete != "undefined" && DeferredListDataComplete) { DeferredListDataComplete(); }
</script>
I will also add my experience here in case it helps someone:
At work we commonly use the following two commands to enable IntelliJ IDEA to talk to various servers, for example our internal maven repositories:
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-printcert -rfc -sslserver maven.services.{our-company}.com:443 > public.crt
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-import -storepass changeit -noprompt -trustcacerts -alias services.{our-company}.com
-keystore lib\security\cacerts -file public.crt
Now, what sometimes happens is that the keytool -printcert
command is unable to communicate with the outside world due to temporary connectivity issues, such as the firewall preventing it, the user forgot to start his VPN, whatever. It is a fact of life that this may happen. This is not actually the problem.
The problem is that when the stupid tool encounters such an error, it does not emit the error message to the standard error device, it emits it to the standard output device!
So here is what ends up happening:
public.crt
file now contains an error message saying keytool error: java.lang.Exception: No certificate from the SSL server
.public.crt
, so it fails, saying keytool error: java.lang.Exception: Input not an X.509 certificate
.Bottom line is: after keytool -printcert ... > public.crt
always dump the contents of public.crt
to make sure it is actually a key and not an error message before proceeding to run keytool -import ... -file public.crt
Not only can you do this in your .htaccess file, you should be doing this period. You will also want to follow the steps here to get your site listed on the HSTS preload list after you implement this redirect so that any requests to the insecure http version of your website never make it past the user agent. Instead, the user agent checks the requested URI against a baked in list of https only websites and, if the requested URI is on that list, changes the protocol from http to https before transmitting the request to the server. Therefore, the insecure request never makes it out into the wild and never hits the server. Eventually when the internet changes over to https only the HSTS preload list will not be needed. Until then, every site should be using it.
In order to perform the redirect, we need to enable the rewrite engine and then redirect all traffic from the http port 80 to https.
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourwebsite.tld/$1 [L,R=301]
You can use the following:
$hashed_password = Hash::make('Your Unhashed Password');
You can find more information: here
You already got some good answers, but I guess you could see it like this: ENCRYPTION: Encryption has to be decryptable if you have the right key.
Example: Like when you send an e-mail. You might not want everyone in the world to know what you are writing to the person receiving the e-mail, but the person who receives the e-mail would probably want to be able to read it.
HASHES: hashes work similar like encryption, but it should not be able to reverse it at all.
Example: Like when you put a key in a locked door(the kinds that locks when you close them). You do not care how the lock works in detail, just as long as it unlocks itself when you use the key. If there is trouble you probably cannot fix it, instead get a new lock.(like forgetting passwords on every login, at least I do it all the time and it is a common area to use hashing).
... and I guess you could call that rainbow-algorithm a locksmith in this case.
Hope things clear up =)
In this case, ' is not a comment character. It's used to delimit string literals. The comic artist is banking on the idea that the school in question has dynamic sql somewhere that looks something like this:
$sql = "INSERT INTO `Students` (FirstName, LastName) VALUES ('" . $fname . "', '" . $lname . "')";
So now the ' character ends the string literal before the programmer was expecting it. Combined with the ; character to end the statement, an attacker can now add whatever sql they want. The -- comment at the end is to make sure any remaining sql in the original statement does not prevent the query from compiling on the server.
FWIW, I also think the comic in question has an important detail wrong: if you're thinking about sanitizing your database inputs, as the comic suggests, you're still doing it wrong. Instead, you should think in terms of quarantining your database inputs, and the correct way to do this is via parameterized queries.
To build this list I used 2 sources. A Study In Scarlet and RATS. I have also added some of my own to the mix and people on this thread have helped out.
Edit: After posting this list I contacted the founder of RIPS and as of now this tools searches PHP code for the use of every function in this list.
Most of these function calls are classified as Sinks. When a tainted variable (like $_REQUEST) is passed to a sink function, then you have a vulnerability. Programs like RATS and RIPS use grep like functionality to identify all sinks in an application. This means that programmers should take extra care when using these functions, but if they where all banned then you wouldn't be able to get much done.
"With great power comes great responsibility."
--Stan Lee
exec - Returns last line of commands output
passthru - Passes commands output directly to the browser
system - Passes commands output directly to the browser and returns last line
shell_exec - Returns commands output
`` (backticks) - Same as shell_exec()
popen - Opens read or write pipe to process of a command
proc_open - Similar to popen() but greater degree of control
pcntl_exec - Executes a program
Apart from eval
there are other ways to execute PHP code: include
/require
can be used for remote code execution in the form of Local File Include and Remote File Include vulnerabilities.
eval()
assert() - identical to eval()
preg_replace('/.*/e',...) - /e does an eval() on the match
create_function()
include()
include_once()
require()
require_once()
$_GET['func_name']($_GET['argument']);
$func = new ReflectionFunction($_GET['func_name']); $func->invoke(); or $func->invokeArgs(array());
These functions accept a string parameter which could be used to call a function of the attacker's choice. Depending on the function the attacker may or may not have the ability to pass a parameter. In that case an Information Disclosure
function like phpinfo()
could be used.
Function => Position of callback arguments
'ob_start' => 0,
'array_diff_uassoc' => -1,
'array_diff_ukey' => -1,
'array_filter' => 1,
'array_intersect_uassoc' => -1,
'array_intersect_ukey' => -1,
'array_map' => 0,
'array_reduce' => 1,
'array_udiff_assoc' => -1,
'array_udiff_uassoc' => array(-1, -2),
'array_udiff' => -1,
'array_uintersect_assoc' => -1,
'array_uintersect_uassoc' => array(-1, -2),
'array_uintersect' => -1,
'array_walk_recursive' => 1,
'array_walk' => 1,
'assert_options' => 1,
'uasort' => 1,
'uksort' => 1,
'usort' => 1,
'preg_replace_callback' => 1,
'spl_autoload_register' => 0,
'iterator_apply' => 1,
'call_user_func' => 0,
'call_user_func_array' => 0,
'register_shutdown_function' => 0,
'register_tick_function' => 0,
'set_error_handler' => 0,
'set_exception_handler' => 0,
'session_set_save_handler' => array(0, 1, 2, 3, 4, 5),
'sqlite_create_aggregate' => array(2, 3),
'sqlite_create_function' => 2,
Most of these function calls are not sinks. But rather it maybe a vulnerability if any of the data returned is viewable to an attacker. If an attacker can see phpinfo()
it is definitely a vulnerability.
phpinfo
posix_mkfifo
posix_getlogin
posix_ttyname
getenv
get_current_user
proc_get_status
get_cfg_var
disk_free_space
disk_total_space
diskfreespace
getcwd
getlastmo
getmygid
getmyinode
getmypid
getmyuid
extract - Opens the door for register_globals attacks (see study in scarlet).
parse_str - works like extract if only one argument is given.
putenv
ini_set
mail - has CRLF injection in the 3rd parameter, opens the door for spam.
header - on old systems CRLF injection could be used for xss or other purposes, now it is still a problem if they do a header("location: ..."); and they do not die();. The script keeps executing after a call to header(), and will still print output normally. This is nasty if you are trying to protect an administrative area.
proc_nice
proc_terminate
proc_close
pfsockopen
fsockopen
apache_child_terminate
posix_kill
posix_mkfifo
posix_setpgid
posix_setsid
posix_setuid
According to RATS all filesystem functions in php are nasty. Some of these don't seem very useful to the attacker. Others are more useful than you might think. For instance if allow_url_fopen=On
then a url can be used as a file path, so a call to copy($_GET['s'], $_GET['d']);
can be used to upload a PHP script anywhere on the system.
Also if a site is vulnerable to a request send via GET everyone of those file system functions can be abused to channel and attack to another host through your server.
// open filesystem handler
fopen
tmpfile
bzopen
gzopen
SplFileObject->__construct
// write to filesystem (partially in combination with reading)
chgrp
chmod
chown
copy
file_put_contents
lchgrp
lchown
link
mkdir
move_uploaded_file
rename
rmdir
symlink
tempnam
touch
unlink
imagepng - 2nd parameter is a path.
imagewbmp - 2nd parameter is a path.
image2wbmp - 2nd parameter is a path.
imagejpeg - 2nd parameter is a path.
imagexbm - 2nd parameter is a path.
imagegif - 2nd parameter is a path.
imagegd - 2nd parameter is a path.
imagegd2 - 2nd parameter is a path.
iptcembed
ftp_get
ftp_nb_get
// read from filesystem
file_exists
file_get_contents
file
fileatime
filectime
filegroup
fileinode
filemtime
fileowner
fileperms
filesize
filetype
glob
is_dir
is_executable
is_file
is_link
is_readable
is_uploaded_file
is_writable
is_writeable
linkinfo
lstat
parse_ini_file
pathinfo
readfile
readlink
realpath
stat
gzfile
readgzfile
getimagesize
imagecreatefromgif
imagecreatefromjpeg
imagecreatefrompng
imagecreatefromwbmp
imagecreatefromxbm
imagecreatefromxpm
ftp_put
ftp_nb_put
exif_read_data
read_exif_data
exif_thumbnail
exif_imagetype
hash_file
hash_hmac_file
hash_update_file
md5_file
sha1_file
highlight_file
show_source
php_strip_whitespace
get_meta_tags
I have found the browser referer implementation to be really inconsistent.
For example, an anchor element with the "download" attribute works as expected in Safari and sends the referer, but in Chrome the referer will be empty or "-" in the web server logs.
<a href="http://foo.com/foo" download="bar">click to download</a>
Is broken in Chrome - no referer sent.
Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.
From the comments:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 2:
* PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
* (See also: SDL crypto guidelines v5.1, Part III)
* Format: { 0x00, salt, subkey }
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
Do you specify a user name and password to log on? What exactly is your complete command line?
If you're running on your own box, you can either specify a username/password, or use the -E
parameter to log on with your Windows credentials (if those are permitted in your SQL server installation).
Marc
You could use this strategy described here as best practice (2006) or an updated strategy described here (2015):
This approach provides defense-in-depth. If someone manages to leak the database table, it does not give an attacker an open door for impersonating users.
old question that I stumbled into that I believe deserves an update... You can infact execute javascript from the URL, and you can get creative about it too. I recently made a members only area that I wanted to remind someone what their password was, so I was looking for a non-local alert...of course you can embed an alert into the page itself, but then its public. the difference here is I can create a link and slip some JS into the href so clicking on the link will generate the alert.
here is what I mean >>
<a href="javascript:alert('the secret is to ask.');window.location.replace('http://google.com');">You can have anything</a>
and so upon clicking the link, the user is given an alert with the info, then they are taken to the new page.
obviously you could also write an onClick, but the href works just fine when you slip it through the URL, just remember to prepend it with "javascript:"
*works in chrome, didnt check anything else.
Might be irrelevant for OP's Q, but I've tried all openssl statements with all the different flags, while trying to connect with PHP \SoapClient(...)
and after 3 days I finally found a solution that worked for me.
$ cd path/to/certificate/
$ openssl pkcs12 -in personal_certificate.pfx -out public_key.pem -clcerts
First you have to enter YOUR_CERT_PASSWORD
once, then DIFFERENT_PASSWORD!
twice. The latter will possibly be available to everyone with access to code.
<?php
$wsdlUrl = "https://example.com/service.svc?singlewsdl";
$publicKey = "rel/path/to/certificate/public_key.pem";
$password = "DIFFERENT_PASSWORD!";
$params = [
'local_cert' => $publicKey,
'passphrase' => $password,
'trace' => 1,
'exceptions' => 0
];
$soapClient = new \SoapClient($wsdlUrl, $params);
var_dump($soapClient->__getFunctions());
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
If your app server is weblogic, then make sure WLProxySSL ON entry exists(and also make sure it should not be commented) in the weblogic.conf file in webserver's conf directory. then restart web server, it will work.
If we want to make reverse engineering (almost) impossible, we can put the application on a highly tamper-resistant chip, which executes all sensitive stuff internally, and communicates with some protocol to make controlling GUI possible on the host. Even tamper-resistant chips are not 100% crack proof; they just set the bar a lot higher than software methods. Of course, this is inconvenient: the application requires some little USB wart which holds the chip to be inserted into the device.
The question doesn't reveal the motivation for wanting to protect this application so jealously.
If the aim is to improve the security of the payment method by concealing whatever security flaws the application may have (known or otherwise), it is completely wrongheaded. The security-sensitive bits should in fact be open-sourced, if that is feasible. You should make it as easy as possible for any security researcher who reviews your application to find those bits and scrutinize their operation, and to contact you. Payment applications should not contain any embedded certificates. That is to say, there should be no server appliaction which trusts a device simply because it has a fixed certificate from the factory. A payment transaction should be made on the user's credentials alone, using a correctly designed end-to-end authentication protocol which precludes trusting the application, or the platform, or the network, etc.
If the aim is to prevent cloning, short of that tamper-proof chip, there isn't anything you can do to protect the program from being reverse-engineered and copied, so that someone incorporates a compatible payment method into their own application, giving rise to "unauthorized clients". There are ways to make it difficult to develop unauthorized clients. One would be to create checksums based on snapshots of the program's complete state: all state variables, for everything. GUI, logic, whatever. A clone program will not have exactly the same internal state. Sure, it is a state machine which has similar externally visible state transitions (as can be observed by inputs and outputs), but hardly the same internal state. A server application can interrogate the program: what is your detailed state? (i.e. give me a checksum over all of your internal state variables). This can be compared against dummy client code which executes on the server in parallel, going through the genuine state transitions. A third party clone will have to replicate all of the relevant state changes of the genuine program in order to give the correct responses, which will hamper its development.
In my point of view,
If you dont use Integrated security=SSPI,then you need to hardcode the username and password in the connection string which means "relatively insecure" why because, all the employees have the access even ex-employee could use the information maliciously.
Using Google as the SSL proxy is not working currently,
If you opened any page from google, you will find there is a x-frame-options
field in the header.
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a
<frame>
,<iframe>
or<object>
. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.
(Quote from MDN)
Below is my work around for this problem:
Upload the content to AWS S3, and it will create a https link for the resource.
Notice: set the permission to the html file for allowing everyone view it.
After that, we can using it as the src
of iframe in the https websites.
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
If you have no Medium security level, then you should add your application to the Exception Site List (Java Control Panel ? Security tab).
Go to Control Panel ? Java Control Panel ? Security tab and press the Edit Site List... button.
Press the Add button, insert your path and press Enter.
Press Continue on the security warning that appears.
Open the applet again and don't forget to press Run on the pop-up window.
For XP: Start > Control Panel > Java > Security > (Set to Medium) http://www.java.com/en/download/help/java_update.xml
Generate a protected application for Mac or Windows from your Excel spreadsheet using OfficeProtect with either AppProtect or QuickLicense/AddLicense. There is a demonstation video called "Protect Excel Spreedsheet" at www.excelsoftware.com/videos.
No. You can't generically filter data without any context of what it's for. Sometimes you'd want to take a SQL query as input and sometimes you'd want to take HTML as input.
You need to filter input on a whitelist -- ensure that the data matches some specification of what you expect. Then you need to escape it before you use it, depending on the context in which you are using it.
The process of escaping data for SQL - to prevent SQL injection - is very different from the process of escaping data for (X)HTML, to prevent XSS.
If choosing between OAuth versions, go with OAuth 2.0.
OAuth bearer tokens should only be used with a secure transport.
OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.
While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.
If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.
Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
Im not very familiar with the Android sdk, but it seems that the android-sdk
comes with the BouncyCastle
provider already added to the security.
What you will have to do in the PC environment is just add it manually,
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
if you have access to the policy
file, just add an entry like:
security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider
Notice the .5
it is equal to a sequential number of the already added providers.
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
I usually use SHA1 and salt with the user ID (or some other user-specific piece of information), and sometimes I additionally use a constant salt (so I have 2 parts to the salt).
SHA1 is now also considered somewhat compromised, but to a far lesser degree than MD5. By using a salt (any salt), you're preventing the use of a generic rainbow table to attack your hashes (some people have even had success using Google as a sort of rainbow table by searching for the hash). An attacker could conceivably generate a rainbow table using your salt, so that's why you should include a user-specific salt. That way, they will have to generate a rainbow table for each and every record in your system, not just one for your entire system! With that type of salting, even MD5 is decently secure.
The version 49.0.2623.75 (64-bit) is not in beta anymore.
The command to fix the CORS issue is
google-chrome-stable --disable-web-security --user-data-dir
How about an approach that not only allows multiple domains, but allows dynamic domains.
The use case here is with a Sharepoint app part which loads our site inside of Sharepoint via an iframe. The problem is that sharepoint has dynamic subdomains such as https://yoursite.sharepoint.com. So for IE, we need to specify ALLOW-FROM https://.sharepoint.com
Tricky business, but we can get it done knowing two facts:
When an iframe loads, it only validates the X-Frame-Options on the first request. Once the iframe is loaded, you can navigate within the iframe and the header isn't checked on subsequent requests.
Also, when an iframe is loaded, the HTTP referer is the parent iframe url.
You can leverage these two facts server side. In ruby, I'm using the following code:
uri = URI.parse(request.referer)
if uri.host.match(/\.sharepoint\.com$/)
url = "https://#{uri.host}"
response.headers['X-Frame-Options'] = "ALLOW-FROM #{url}"
end
Here we can dynamically allow domains based upon the parent domain. In this case, we ensure that the host ends in sharepoint.com keeping our site safe from clickjacking.
I'd love to hear feedback on this approach.
The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:
<form action="http://someotherserver.com">
and there is no javascript involved in posting the form, then the same origin policy is not applicable.
See wikipedia for more information
Make sure that you have valid cacerts in the JRE/security, otherwise you will not bypass the invalid empty trustAnchors error.
In my Amazon EC2 Opensuse12 installation, the problem was that the file pointed by the cacerts in the JRE security directory was invalid:
$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
$ ls -l /var/lib/ca-certificates/
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem
$ ls -l /usr/lib64/jvm/jre/lib/security/
lrwxrwxrwx 1 root 37 Mar 21 00:16 cacerts -> /var/lib/ca-certificates/java-cacerts
-rw-r--r-- 1 root 2254 Jan 18 16:50 java.policy
-rw-r--r-- 1 root 15374 Jan 18 16:50 java.security
-rw-r--r-- 1 root 88 Jan 18 17:34 nss.cfg
So I solved installing an old Opensuse 11 valid certificates. (sorry about that!!)
$ ll
total 616
-rw-r--r-- 1 root 220065 Jan 31 15:48 ca-bundle.pem
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem.old
-rw-r--r-- 1 root 161555 Jan 31 15:48 java-cacerts
I understood that you could use the keytool to generate a new one (http://mail.openjdk.java.net/pipermail/distro-pkg-dev/2010-April/008961.html). I'll probably have to that soon.
regards lellis
The idea of refresh tokens is that if an access token is compromised, because it is short-lived, the attacker has a limited window in which to abuse it.
Refresh tokens, if compromised, are useless because the attacker requires the client id and secret in addition to the refresh token in order to gain an access token.
Having said that, because every call to both the authorization server and the resource server is done over SSL - including the original client id and secret when they request the access/refresh tokens - I am unsure as to how the access token is any more "compromisable" than the long-lived refresh token and clientid/secret combination.
This of course is different to implementations where you don't control both the authorization and resource servers.
Here is a good thread talking about uses of refresh tokens: OAuth Archives.
A quote from the above, talking about the security purposes of the refresh token:
Refresh tokens... mitigates the risk of a long-lived access_token leaking (query param in a log file on an insecure resource server, beta or poorly coded resource server app, JS SDK client on a non https site that puts the access_token in a cookie, etc)
The answer has already been given, but I'd like to share an issue that I discovered lately with Java standard libraries. While they take great care now of replacing password strings with char[]
everywhere (which of course is a good thing), other security-critical data seems to be overlooked when it comes to clearing it from memory.
I'm thinking of e.g. the PrivateKey class. Consider a scenario where you would load a private RSA key from a PKCS#12 file, using it to perform some operation. Now in this case, sniffing the password alone wouldn't help you much as long as physical access to the key file is properly restricted. As an attacker, you would be much better off if you obtained the key directly instead of the password. The desired information can be leaked manifold, core dumps, a debugger session or swap files are just some examples.
And as it turns out, there is nothing that lets you clear the private information of a PrivateKey
from memory, because there's no API that lets you wipe the bytes that form the corresponding information.
This is a bad situation, as this paper describes how this circumstance could be potentially exploited.
The OpenSSL library for example overwrites critical memory sections before private keys are freed. Since Java is garbage-collected, we would need explicit methods to wipe and invalidate private information for Java keys, which are to be applied immediately after using the key.
There are a variety of libraries for PHP (The LAMP Stack)
PHP
https://code.google.com/p/ga4php/
http://www.idontplaydarts.com/2011/07/google-totp-two-factor-authentication-for-php/
You should be careful when implementing two-factor auth, you need to ensure your clocks on the server and client are synchronized, that there is protection in place against brute-force attacks on the token and that the initial seed used is suitably large.
I would add the following:
Understand how different attack vectors work:
You can easily google for all of this. This will give you a good foundation. If you want to see web app vulnerabilities, there's a project called google gruyere that shows you how to exploit a working web app.
I'm going to say that it is not possible to completely prevent screen/video capture of any android app through supported means. But if you only want to block it for normal android devices, the SECURE FLAG is substantial.
1) The secure flag does block both normal screenshot and video capture.
Also documentation at this link says that
Window flag: treat the content of the window as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.
Above solution will surely prevent applications from capturing Video of your app
See the answer here.
2) There are alternative means of capturing screen content.
It may be possible to capture the screen of another app on a rooted device or through using the SDK,
which both offer little to no chance of you either blocking it or receiving notification of it.
For example: there exists software to mirror your phone screen to your computer via the SDK and so screen capture software could be used there, undiscoverable by your app.
See the answer here.
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
Well, I still find some room to answer.
In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:
Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.
Just an additional note - if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST
contains the port, while SERVER_NAME
does not.
$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'
(At least that's what I've noticed in Apache port-based virtualhosts)
As Mike has noted below, HTTP_HOST
does not contain :443
when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).
Try This one. It will generate id according to your wish.
function id()
{
// add limit
$id_length = 20;
// add any character / digit
$alfa = "abcdefghijklmnopqrstuvwxyz1234567890";
$token = "";
for($i = 1; $i < $id_length; $i ++) {
// generate randomly within given character/digits
@$token .= $alfa[rand(1, strlen($alfa))];
}
return $token;
}
This is a big gray area in cookie SOP (Same Origin Policy).
Theoretically, you can specify port number in the domain and the cookie will not be shared. In practice, this doesn't work with several browsers and you will run into other issues. So this is only feasible if your sites are not for general public and you can control what browsers to use.
The better approach is to get 2 domain names for the same IP and not relying on port numbers for cookies.
Yes, headers are encrypted. It's written here.
Everything in the HTTPS message is encrypted, including the headers, and the request/response load.
According to the documentation you need to specify the key store:
Protocol authhttps = new Protocol("https",
new AuthSSLProtocolSocketFactory(
new URL("file:my.keystore"), "mypassword",
new URL("file:my.truststore"), "mypassword"), 443);
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("localhost", 443, authhttps);
Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class provide various static methods that relax X509 certificate and
* hostname verification while using the SSL over the HTTP protocol.
*
* @author Jiramot.info
*/
public final class SSLUtilities {
/**
* Hostname verifier for the Sun's deprecated API.
*
* @deprecated see {@link #_hostnameVerifier}.
*/
private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
/**
* Thrust managers for the Sun's deprecated API.
*
* @deprecated see {@link #_trustManagers}.
*/
private static com.sun.net.ssl.TrustManager[] __trustManagers;
/**
* Hostname verifier.
*/
private static HostnameVerifier _hostnameVerifier;
/**
* Thrust managers.
*/
private static TrustManager[] _trustManagers;
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames. This method uses the old deprecated API from the
* com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHostnames()}.
*/
private static void __trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (__hostnameVerifier == null) {
__hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier
com.sun.net.ssl.HttpsURLConnection
.setDefaultHostnameVerifier(__hostnameVerifier);
} // __trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones. This method uses the
* old deprecated API from the com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHttpsCertificates()}.
*/
private static void __trustAllHttpsCertificates() {
com.sun.net.ssl.SSLContext context;
// Create a trust manager that does not validate certificate chains
if (__trustManagers == null) {
__trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager
try {
context = com.sun.net.ssl.SSLContext.getInstance("SSL");
context.init(null, __trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // __trustAllHttpsCertificates
/**
* Return true if the protocol handler property java. protocol.handler.pkgs
* is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
* one, false otherwise.
*
* @return true if the protocol handler property is set to the Sun's
* deprecated one, false otherwise.
*/
private static boolean isDeprecatedSSLProtocol() {
return ("com.sun.net.ssl.internal.www.protocol".equals(System
.getProperty("java.protocol.handler.pkgs")));
} // isDeprecatedSSLProtocol
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
private static void _trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (_hostnameVerifier == null) {
_hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
} // _trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
private static void _trustAllHttpsCertificates() {
SSLContext context;
// Create a trust manager that does not validate certificate chains
if (_trustManagers == null) {
_trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager:
try {
context = SSLContext.getInstance("SSL");
context.init(null, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // _trustAllHttpsCertificates
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
public static void trustAllHostnames() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHostnames();
} else {
_trustAllHostnames();
} // else
} // trustAllHostnames
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
public static void trustAllHttpsCertificates() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHttpsCertificates();
} else {
_trustAllHttpsCertificates();
} // else
} // trustAllHttpsCertificates
/**
* This class implements a fake hostname verificator, trusting any host
* name. This class uses the old deprecated API from the com.sun. ssl
* package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
*/
public static class _FakeHostnameVerifier implements
com.sun.net.ssl.HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, String session) {
return (true);
} // verify
} // _FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates. This
* class uses the old deprecated API from the com.sun.ssl package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
*/
public static class _FakeX509TrustManager implements
com.sun.net.ssl.X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always return true, trusting for client SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return (true);
} // checkClientTrusted
/**
* Always return true, trusting for server SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return (true);
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // _FakeX509TrustManager
/**
* This class implements a fake hostname verificator, trusting any host
* name.
*
* @author Jiramot.info
*/
public static class FakeHostnameVerifier implements HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return (true);
} // verify
} // FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*
* @author Jiramot.info
*/
public static class FakeX509TrustManager implements X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* @param chain the peer certificate chain.
* @param authType the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* @param chain the peer certificate chain.
* @param authType the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // FakeX509TrustManager
} // SSLUtilities
The right syntax of the php_flag command is
php_flag session.cookie_httponly On
And be aware, just first answer from server set the cookie and here (for example You can see the "HttpOnly" directive. So for testing delete cookies from browser after every testing request.
To include an external Javascript file you use the <script>
tag. The src
attribute points to the location of your Javascript file within your web project.
<script src="some.js" type="text/javascript"></script>
JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag. You can also include Jquery from a content distribution network such as the one hosted by Google.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
First you need to create the Hidden Field properly
<asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>
Then you need to set value to the hidden field
If you aren't using Jquery you should use it:
document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";
If you are using Jquery, this is how it should be:
$("#<%= hdntxtbxTaksit.ClientID %>").val("test");
User proper model in your controller file.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
on IOS 9, you can do this
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
From a recent discussion with the Angular guys on this very topic: For future-proofing reasons, you should not use $$phase
When pressed for the "right" way to do it, the answer is currently
$timeout(function() {
// anything you want can go here and will safely be run on the next digest.
})
I recently ran into this when writing angular services to wrap the facebook, google, and twitter APIs which, to varying degrees, have callbacks handed in.
Here's an example from within a service. (For the sake of brevity, the rest of the service -- that set up variables, injected $timeout etc. -- has been left off.)
window.gapi.client.load('oauth2', 'v2', function() {
var request = window.gapi.client.oauth2.userinfo.get();
request.execute(function(response) {
// This happens outside of angular land, so wrap it in a timeout
// with an implied apply and blammo, we're in action.
$timeout(function() {
if(typeof(response['error']) !== 'undefined'){
// If the google api sent us an error, reject the promise.
deferred.reject(response);
}else{
// Resolve the promise with the whole response if ok.
deferred.resolve(response);
}
});
});
});
Note that the delay argument for $timeout is optional and will default to 0 if left unset ($timeout calls $browser.defer which defaults to 0 if delay isn't set)
A little non-intuitive, but that's the answer from the guys writing Angular, so it's good enough for me!
In windows 7, you may have to edit this file
C:\Users\<UserName>\AppData\Roaming\Subversion\servers
[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128
You have to use the contents()
method:
$("#myiframe").contents().find("#myContent")
Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/
API Doc: https://api.jquery.com/contents/
Quit vim before "git commit".
to make vim
use other folders for backup files, (/tmp
for example):
set bdir-=.
set bdir+=/tmp
to make vim stop using current folder for .swp files:
set dir-=.
set dir+=/tmp
Use -=, +=
would be generally good, because vim has other defaults for bdir, dir, we don't want to clear all. Check vim help for more about bdir, dir:
:h bdir
:h dir
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
Once you start writing code that can return a myriad of exit statuses, you start #define
'ing all of them. In this case EXIT_SUCCESS
makes sense in context of not being a "magic number". This makes your code more readable because every other exit code will be EXIT_SOMETHING
. If you simply write a program that will return when it's done, return 0
is valid, and probably even cleaner because it suggests that there's no sophisticated return code structure.
In your Startup.Auth.cs file add this line:
LoginPath = new PathString("/Account/Login"),
Example:
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
There's a bit of code that might help:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class ModalJFrame extends JFrame {
Object currentWindow = this;
public ModalJFrame()
{
super();
super.setTitle("Main JFrame");
super.setSize(500, 500);
super.setResizable(true);
super.setLocationRelativeTo(null);
JMenuBar menuBar = new JMenuBar();
super.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
JMenuItem newAction = new JMenuItem("New");
JMenuItem openAction = new JMenuItem("Open");
JMenuItem exitAction = new JMenuItem("Exit");
JMenuItem cutAction = new JMenuItem("Cut");
JMenuItem copyAction = new JMenuItem("Copy");
JMenuItem pasteAction= new JMenuItem("Paste");
fileMenu.add(newAction);
fileMenu.add(openAction);
fileMenu.addSeparator();
fileMenu.add(exitAction);
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.addSeparator();
editMenu.add(pasteAction);
newAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JFrame popupJFrame = new JFrame();
popupJFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
((Component) currentWindow).setEnabled(true); }
});
((Component) currentWindow).setEnabled(false);
popupJFrame.setTitle("Pop up JFrame");
popupJFrame.setSize(400, 500);
popupJFrame.setAlwaysOnTop(true);
popupJFrame.setResizable(false);
popupJFrame.setLocationRelativeTo(getRootPane());
popupJFrame.setVisible(true);
popupJFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
});
exitAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
System.exit(0);
}
});
}
public static void main(String[] args) {
ModalJFrame myWindow = new ModalJFrame();
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setVisible(true);
}
}
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
You can use $.browser to detect the browser name. possible values are :
or get a boolean flag: $.browser.msie will be true if the browser is MSIE.
as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.
Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.
if you need to increase reserved memory, there are VM parameters -Xms and -Xmx, usage e.g. -Xms512m -Xmx512m . There is also parameter -XX:MaxPermSize=256m which changes memory reserved for permanent generation
If your application runs as windows service, in Control panels -> Administration tools -> Services you can add some run parameters to your service
If you don't want to use a separate JS library to create a custom control for that, you could use two confirm
dialogs to do the checks:
if (confirm("Are you sure you want to quit?") ) {
if (confirm("Save your work before leaving?") ) {
// code here for save then leave (Yes)
} else {
//code here for no save but leave (No)
}
} else {
//code here for don't leave (Cancel)
}
Generally you don't want to mix the default touch and non-touch (click) api. Once you move into the world of touch it easier to deal only with the touch related functions. Below is some pseudo code that would do what you want it to.
If you connect in the touchmove event and track the locations you can add more items in the doTouchLogic function to detect gestures and whatnot.
var touchStartTime;
var touchStartLocation;
var touchEndTime;
var touchEndLocation;
$thing.bind('touchstart'), function() {
var d = new Date();
touchStartTime = d.getTime();
touchStartLocation = mouse.location(x,y);
});
$thing.bind('touchend'), function() {
var d = new Date();
touchEndTime= d.getTime();
touchEndLocation= mouse.location(x,y);
doTouchLogic();
});
function doTouchLogic() {
var distance = touchEndLocation - touchStartLocation;
var duration = touchEndTime - touchStartTime;
if (duration <= 100ms && distance <= 10px) {
// Person tapped their finger (do click/tap stuff here)
}
if (duration > 100ms && distance <= 10px) {
// Person pressed their finger (not a quick tap)
}
if (duration <= 100ms && distance > 10px) {
// Person flicked their finger
}
if (duration > 100ms && distance > 10px) {
// Person dragged their finger
}
}
Note that WebMvcConfigurerAdapter is deprecated now (see WebMvcConfigurerAdapter). Due to Java 8 default methods, you only have to implement WebMvcConfigurer.
In my sample code, I was setting my object
to nothing, and I couldn't get the "not" part of the if statement to work with the object. I tried if My_Object is not nothing
and also if not My_Object is nothing
. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this:
if My_Object is Nothing Then
'do nothing
Else
'Do something
End if
To get the Color from Hex.
using System.Windows.Media;
Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
and then set the foreground
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color);
It seems that the problem is in eslint-plugin-react
.
It can not correctly detect what props were mentioned in propTypes
if you have annotated named objects via destructuring anywhere in the class.
There was similar problem in the past
var funcs = [];
for (var i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function(param) { // and store them in funcs
console.log("My value: " + param); // each should log its value.
};
}
for (var j = 0; j < 3; j++) {
funcs[j](j); // and now let's run each one to see with j
}
I found @Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
The normal behavior may be to say
newSelect.onchange = changeitem;
But this does not really allow you to specify that argument passed in, so instead you may do this:
newSelect.setAttribute('onchange', 'changeitem(this)');
And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange
function will be browser dependent. The second way seems to work cross-browser just fine.
Example of CSS Text Gradient
background-image: -moz-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -webkit-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -o-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -ms-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: linear-gradient(top,#E605C1 0%,#3B113B 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
position:relative;
display:inline-block; /*required*/
Online generator textgradient.com
Here is the sample code to mock log, irrespective of the version used for junit or sping, springboot.
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import org.mockito.ArgumentMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Test;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MyTest {
private static Logger logger = LoggerFactory.getLogger(MyTest.class);
@Test
public void testSomething() {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
final Appender mockAppender = mock(Appender.class);
when(mockAppender.getName()).thenReturn("MOCK");
root.addAppender(mockAppender);
//... do whatever you need to trigger the log
verify(mockAppender).doAppend(argThat(new ArgumentMatcher() {
@Override
public boolean matches(final Object argument) {
return ((LoggingEvent)argument).getFormattedMessage().contains("Hey this is the message I want to see");
}
}));
}
}
Things are pretty much simpler unless they are made confusing.
To Install GD library in Ubuntu
sudo apt-get install php5-gd
To Install Freetype in Ubuntu
sudo apt-get install libfreetype6-dev:i386
Pure Java:
urlToInputStream(url,httpHeaders);
With some success I use this method. It handles redirects and one can pass a variable number of HTTP headers asMap<String,String>
. It also allows redirects from HTTP to HTTPS.
private InputStream urlToInputStream(URL url, Map<String, String> args) {
HttpURLConnection con = null;
InputStream inputStream = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
if (args != null) {
for (Entry<String, String> e : args.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
}
con.connect();
int responseCode = con.getResponseCode();
/* By default the connection will follow redirects. The following
* block is only entered if the implementation of HttpURLConnection
* does not perform the redirect. The exact behavior depends to
* the actual implementation (e.g. sun.net).
* !!! Attention: This block allows the connection to
* switch protocols (e.g. HTTP to HTTPS), which is <b>not</b>
* default behavior. See: https://stackoverflow.com/questions/1884230
* for more info!!!
*/
if (responseCode < 400 && responseCode > 299) {
String redirectUrl = con.getHeaderField("Location");
try {
URL newUrl = new URL(redirectUrl);
return urlToInputStream(newUrl, args);
} catch (MalformedURLException e) {
URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
return urlToInputStream(newUrl, args);
}
}
/*!!!!!*/
inputStream = con.getInputStream();
return inputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Full example call
private InputStream getInputStreamFromUrl(URL url, String user, String passwd) throws IOException {
String encoded = Base64.getEncoder().encodeToString((user + ":" + passwd).getBytes(StandardCharsets.UTF_8));
Map<String,String> httpHeaders=new Map<>();
httpHeaders.put("Accept", "application/json");
httpHeaders.put("User-Agent", "myApplication");
httpHeaders.put("Authorization", "Basic " + encoded);
return urlToInputStream(url,httpHeaders);
}
Here is where you went wrong:
this.result = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result.json());
it should be:
http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result);
or
http.get('friends.json')
.subscribe(result => this.result =result.json());
You have made two mistakes:
1- You assigned the observable itself to this.result
. When you actually wanted to assign the list of friends to this.result
. The correct way to do it is:
you subscribe to the observable. .subscribe
is the function that actually executes the observable. It takes three callback parameters as follow:
.subscribe(success, failure, complete);
for example:
.subscribe(
function(response) { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
Usually, you take the results from the success callback and assign it to your variable.
the error callback is self explanatory.
the complete callback is used to determine that you have received the last results without any errors.
On your plunker, the complete callback will always be called after either the success or the error callback.
2- The second mistake, you called .json()
on .map(res => res.json())
, then you called it again on the success callback of the observable.
.map()
is a transformer that will transform the result to whatever you return (in your case .json()
) before it's passed to the success callback
you should called it once on either one of them.
In principle, you can pass any reformatting function to the labels
parameter:
+ scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %
Or
+ scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign
Reproducible example:
library(ggplot2)
df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))
ggplot(df, aes(x,y)) +
geom_point() +
scale_y_continuous(labels = function(x) paste0(x*100, "%"))
You need to distinguish between two separate concepts: function definition and symbol declaration. "extern" is a linkage modifier, a hint to the compiler about where the symbol referred to afterwards is defined (the hint is, "not here").
If I write
extern int i;
in file scope (outside a function block) in a C file, then you're saying "the variable may be defined elsewhere".
extern int f() {return 0;}
is both a declaration of the function f and a definition of the function f. The definition in this case over-rides the extern.
extern int f();
int f() {return 0;}
is first a declaration, followed by the definition.
Use of extern
is wrong if you want to declare and simultaneously define a file scope variable. For example,
extern int i = 4;
will give an error or warning, depending on the compiler.
Usage of extern
is useful if you explicitly want to avoid definition of a variable.
Let me explain:
Let's say the file a.c contains:
#include "a.h"
int i = 2;
int f() { i++; return i;}
The file a.h includes:
extern int i;
int f(void);
and the file b.c contains:
#include <stdio.h>
#include "a.h"
int main(void){
printf("%d\n", f());
return 0;
}
The extern in the header is useful, because it tells the compiler during the link phase, "this is a declaration, and not a definition". If I remove the line in a.c which defines i, allocates space for it and assigns a value to it, the program should fail to compile with an undefined reference. This tells the developer that he has referred to a variable, but hasn't yet defined it. If on the other hand, I omit the "extern" keyword, and remove the int i = 2
line, the program still compiles - i will be defined with a default value of 0.
File scope variables are implicitly defined with a default value of 0 or NULL if you do not explicitly assign a value to them - unlike block-scope variables that you declare at the top of a function. The extern keyword avoids this implicit definition, and thus helps avoid mistakes.
For functions, in function declarations, the keyword is indeed redundant. Function declarations do not have an implicit definition.
As someone that has ran into this problem constantly with java repositories on Windows, the best solution is to install Cygwin (https://www.cygwin.com/) and use its git installation under all > devel > git.
The reason this is the best solution I have come across is since Cygwin manages the long path names so other provided commands benefit. Ex: find, cp and rm. Trust me, the real problem begins when you have to delete path names that are too long in Windows.
If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.
Ex:
--id is primary key of MainTable
declare @id int
set @id = 1
declare theMain cursor for select FK from MainTable where MainID = @id
declare @fk_Id int
open theMain
fetch next from theMain into @fk_Id
while @@fetch_status=0
begin
--fkid is the foreign key
--Must delete from Main Table first then child.
delete from MainTable where fkid = @fk_Id
delete from ReferencingTable where fkid = @fk_Id
fetch next from theMain into @fk_Id
end
close theMain
deallocate theMain
hope is useful
I needed a way to do this in an AJAX return, so I wrote this piece:
<p id="num_results">Number of results: <span></span></p>
<div id="results"></div>
<script type="text/javascript">
$(function(){
ajax();
})
//Function that makes Ajax call out to receive search results
var ajax = function() {
//Setup Ajax
$.ajax({
url: '/path/to/url', //URL to load
type: 'GET', //Type of Ajax call
dataType: 'html', //Type of data to be expected on return
success: function(data) { //Function that manipulates the returned AJAX'ed data
$('#results').html(data); //Load the data into a HTML holder
var $el = $('#results'); //jQuery Object that is holding the results
setTimeout(function(){ //Custom callback function to count the number of results
callBack($el);
});
}
});
}
//Custom Callback function to return the number of results
var callBack = function(el) {
var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
$('#num_results span').text(length); //Write the counted results to the DOM
}
</script>
Obviously this is a quick example, but it may be helpful.
Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.
Try using this command to allow a port
sudo ufw allow 1701
To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:
nc -l 1701
Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.
There are 94 Unicode characters which can be represented as one byte according to the JSON spec (if your JSON is transmitted as UTF-8). With that in mind, I think the best you can do space-wise is base85 which represents four bytes as five characters. However, this is only a 7% improvement over base64, it's more expensive to compute, and implementations are less common than for base64 so it's probably not a win.
You could also simply map every input byte to the corresponding character in U+0000-U+00FF, then do the minimum encoding required by the JSON standard to pass those characters; the advantage here is that the required decoding is nil beyond builtin functions, but the space efficiency is bad -- a 105% expansion (if all input bytes are equally likely) vs. 25% for base85 or 33% for base64.
Final verdict: base64 wins, in my opinion, on the grounds that it's common, easy, and not bad enough to warrant replacement.
For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170
A generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.
>>> def myGenerator():
... yield 'These'
... yield 'words'
... yield 'come'
... yield 'one'
... yield 'at'
... yield 'a'
... yield 'time'
>>> myGeneratorInstance = myGenerator()
>>> next(myGeneratorInstance)
These
>>> next(myGeneratorInstance)
words
and so on. The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem. Generators, just like lists, are iterable, so they can be used in the same ways:
>>> for word in myGeneratorInstance:
... print word
These
words
come
one
at
a
time
Note that generators provide another way to deal with infinity, for example
>>> from time import gmtime, strftime
>>> def myGen():
... while True:
... yield strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
>>> myGeneratorInstance = myGen()
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:17:15 +0000
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:18:02 +0000
The generator encapsulates an infinite loop, but this isn't a problem because you only get each answer every time you ask for it.
Resetting IIS
a. From the Start menu, choose All Programs, and then choose Accessories. b. Right-click Command Prompt, and then choose Run as administrator.
At the command prompt, type the following command to change to the Microsoft.NET\Framework64\v4.0.30319 folder, and then press Enter.
cd\Windows\Microsoft.NET\Framework64\v4.0.30319
At the command prompt, type the following command, and then press Enter.
aspnet_regiis.exe -iru
At the command prompt, type the following command, and then press Enter. iisreset
Some more:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25
A potentially trivial solution to this is to switch to using multiprocessing.dummy
. This is a thread based implementation of the multiprocessing interface that doesn't seem to have this problem in Python 2.7. I don't have a lot of experience here, but this quick import change allowed me to call apply_async on a class method.
A few good resources on multiprocessing.dummy
:
https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy
On Windows, open command prompt and type tracert google.com
and press enter, or on Linux, open terminal and type nslookup google.com
and press enter:
Server: 127.0.1.1
Address: 127.0.1.1#53
Non-authoritative answer:
Name: google.com
Address: 74.125.236.199
Name: google.com
Address: 74.125.236.201
Name: google.com
Address: 74.125.236.194
Name: google.com
Address: 74.125.236.198
Name: google.com
Address: 74.125.236.206
Name: google.com
Address: 74.125.236.193
Name: google.com
Address: 74.125.236.196
Name: google.com
Address: 74.125.236.192
Name: google.com
Address: 74.125.236.197
Name: google.com
Address: 74.125.236.195
Name: google.com
Address: 74.125.236.200
I faced the same issues. To solve this, I used export PYTHONPATH="$PWD"
. However, in this case, you will need to modify imports in your Scripts
dir depending on the below:
Case 1: If you are in the user_management
dir, your scripts
should use this style from Modules import LDAPManager
to import module.
Case 2: If you are out of the user_management
1 level like main
, your scripts
should use this style from user_management.Modules import LDAPManager
to import modules.
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
As mentioned I think your return string data is very long. so the JSON format has been corrupted.
There's other way for this problem. You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
you need to turn off the compression:
git config --global core.compression 0
then you need to use shallow clone
git clone --depth=1 <url>
then most important step is to cd into your cloned project
cd <shallow cloned project dir>
now deopen the clone,step by step
git fetch --depth=N, with increasing N
eg.
git fetch --depth=4
then,
git fetch --depth=100
then,
git fetch --depth=500
you can choose how many steps you want by replacing this N,
and finally download all of the remaining revisions using,
git fetch --unshallow
upvote if it helps you :)
I pieced a few of the other posts together, as the workbench 'preferences' fix did not work for me. (WB 6.3)
SELECT CAST(`column` AS CHAR(10000) CHARACTER SET utf8) FROM `table`;
Try if that works
sc = spark.sparkContext
# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")
I got this working with Bitbucket's Markdown by using a empty link:
[]() |
------|------
Row 1 | row 2
To use an identity column in v10,
ALTER TABLE test
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;
For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.
For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.
For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.
I also faced the same issue...try to do this...this worked for me
.scrollBbar
{
position:fixed;
top:50px;
bottom:0;
left:0;
width:200px;
overflow-x:hidden;
overflow-y:auto;
}
I had the same handshake issue when connection to a hosted server.
I opened my Network and sharing center and enabled IPv6 on my wireless network connection.
Just go to your app/storage/logs
there logs of error
available. Go to filename of today's date time and you will find latest error
in your application.
OR
Open app/config/app.php
and change setting
'debug' => false,
To
'debug' => true,
OR
Go to .env
file to your application and change the configuratuion
APP_LOG_LEVEL=debug
def get_rounded_datetime(self, dt, freq, nearest_type='inf'):
if freq.lower() == '1h':
round_to = 3600
elif freq.lower() == '3h':
round_to = 3 * 3600
elif freq.lower() == '6h':
round_to = 6 * 3600
else:
raise NotImplementedError("Freq %s is not handled yet" % freq)
# // is a floor division, not a comment on following line:
seconds_from_midnight = dt.hour * 3600 + dt.minute * 60 + dt.second
if nearest_type == 'inf':
rounded_sec = int(seconds_from_midnight / round_to) * round_to
elif nearest_type == 'sup':
rounded_sec = (int(seconds_from_midnight / round_to) + 1) * round_to
else:
raise IllegalArgumentException("nearest_type should be 'inf' or 'sup'")
dt_midnight = datetime.datetime(dt.year, dt.month, dt.day)
return dt_midnight + datetime.timedelta(0, rounded_sec)
If your array of objects is items
, you can do:
var items = [{_x000D_
id: 1,_x000D_
name: 'john'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'jane'_x000D_
}, {_x000D_
id: 2000,_x000D_
name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
Documentation: map()
Here is the source of these column flags
http://dev.mysql.com/doc/workbench/en/wb-table-editor-columns-tab.html
If you are trying to insert the therefore symbol into a WORD DOCUMENT
Hold down the ALT key and type 8756
Hope the answer ur question Regards Al~Hash.
Copied from Web Applications:
=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")
I had the same issue (but on my local) when I was trying to add Entity Framework migration with Package Manager Console.
The way I solved it was by creating a console application where Main() had the following code:
var dbConfig = new Configuration();
var dbMigrator = new DbMigrator(dbConfig);
dbMigrator.Update();
Make sure the Configuration class is the migration Configuration of your failing project. You will need System.Data.Entity.Migrations to use DbMigrator.
Set a breakpoint in your application, and run it. The exception should be caught by Visual Studio (unless you have that exception type set to not break the debug session), and you should be able to find the info you are looking for.
The missing reference in my case was EFProviderWrapperToolkit.
Apart from the syntax, the main difference is in the scoping:
# scoping with alias_method
class User
def full_name
puts "Johnnie Walker"
end
def self.add_rename
alias_method :name, :full_name
end
end
class Developer < User
def full_name
puts "Geeky geek"
end
add_rename
end
Developer.new.name #=> 'Geeky geek'
In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias
.
class User
def full_name
puts "Johnnie Walker"
end
def self.add_rename
alias name full_name
end
end
class Developer < User
def full_name
puts "Geeky geek"
end
add_rename
end
Developer.new.name #=> 'Johnnie Walker'
With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.
This is because alias
is a keyword and it is lexically scoped. It means it treats self
as the value of self at the time the source code was read . In contrast alias_method
treats self
as the value determined at the run time.
Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html
I was using python2 but installed this: sudo apt-get install libapache2-mod-wsgi-py3
Instead of: sudo apt-get install libapache2-mod-wsgi
Correcting the installation solved the no flask problem.
It sounds like you might just need to use a view. A view allows a query to be represented as a table so it, the view, can be queried.
rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.
Use rsync -vP username@host:/path/to/file .
The -P option preserves partially downloaded files and also shows progress.
As usual check man rsync
$.ajax({
url: 'http://url.of.my.server/submit',
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'jsonp_callback'
});
jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:
url: 'http://url.of.my.server/submit?callback=?'
the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.
$.ajax({
url: 'http://url.of.my.server/submit?callback=?',
success: function (data, status) {
mySurvey.closePopup();
},
error: function (xOptions, textStatus) {
mySurvey.closePopup();
}
});
The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:
$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});
Try this instead to only select the visible elements under the tbody
:
$('tbody :visible').highlight(myArray[i]);
I know this is a bit old, but I thought I would provide another tip. In my situation, I inherited this application that I had to maintain. The VS2008 project came with the same string in C/C++->OutputFIles->"ObjectFIleName" and "Program Database File Name" (for both platforms Win32 and x64). So when I built Win32 platform, it built fine, but when I tried to build x64, I got the error:
\Debug64\Objects\common.obj : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'
Obviously, both patforms were storing common.obj at the same location, so when I tried to build x64, the linker took the existing object file, which was x86.
To fix I just replaced the existing string with the macro "$(IntDir)\" for x64 (no quotes), and made sure that the macro resolved to the correct path, as in the rest of the projects. That solved my problem.
You can use finish()
method or you can use:
android:noHistory="true"
And then there is no need to call finish()
anymore.
<activity android:name=".ClassName" android:noHistory="true" ... />
You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).
You specify sigma
and hsize
in fspecial
.
%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)
Tried above steps, didn't work on Ubuntu 20. For Ubuntu 20, remove the cmdtest and yarn like suggested above. Install yarn with below commands:
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update && sudo apt install yarn
You can use the HTML5 pattern attribute or use JavaScript.
The pattern could look for example like this:
<input id="groupidtext" type="text" pattern="(.){6,6}" style="width: 100px;" maxlength="6" />
But the pattern attribute will only work with HTML5 browsers. For old browsers you'll need JavaScript.
As suggested in the comments to add, this will only work as soon as a form is about to be submitted. If this input is not in a form and you need validation as a user types, use JavaScript.
This answer is all about authorization and it is a complement of my previous answer about authentication
Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.
@Secured
annotationBesides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.
Create an enumeration and define the roles according to your needs:
public enum Role {
ROLE_1,
ROLE_2,
ROLE_3
}
Change the @Secured
name binding annotation created before to support roles:
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
Role[] value() default {};
}
And then annotate the resource classes and methods with @Secured
to perform the authorization. The method annotations will override the class annotations:
@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id) {
// This method is not annotated with @Secured
// But it's declared within a class annotated with @Secured({Role.ROLE_1})
// So it only can be executed by the users who have the ROLE_1 role
...
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured({Role.ROLE_1, Role.ROLE_2})
public Response myOtherMethod(@PathParam("id") Long id) {
// This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
// The method annotation overrides the class annotation
// So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
...
}
}
Create a filter with the AUTHORIZATION
priority, which is executed after the AUTHENTICATION
priority filter defined previously.
The ResourceInfo
can be used to get the resource Method
and resource Class
that will handle the request and then extract the @Secured
annotations from them:
@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the resource class which matches with the requested URL
// Extract the roles declared by it
Class<?> resourceClass = resourceInfo.getResourceClass();
List<Role> classRoles = extractRoles(resourceClass);
// Get the resource method which matches with the requested URL
// Extract the roles declared by it
Method resourceMethod = resourceInfo.getResourceMethod();
List<Role> methodRoles = extractRoles(resourceMethod);
try {
// Check if the user is allowed to execute the method
// The method annotations override the class annotations
if (methodRoles.isEmpty()) {
checkPermissions(classRoles);
} else {
checkPermissions(methodRoles);
}
} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).build());
}
}
// Extract the roles from the annotated element
private List<Role> extractRoles(AnnotatedElement annotatedElement) {
if (annotatedElement == null) {
return new ArrayList<Role>();
} else {
Secured secured = annotatedElement.getAnnotation(Secured.class);
if (secured == null) {
return new ArrayList<Role>();
} else {
Role[] allowedRoles = secured.value();
return Arrays.asList(allowedRoles);
}
}
}
private void checkPermissions(List<Role> allowedRoles) throws Exception {
// Check if the user contains one of the allowed roles
// Throw an Exception if the user has not permission to execute the method
}
}
If the user has no permission to execute the operation, the request is aborted with a 403
(Forbidden).
To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext
(which should be already set in the ContainerRequestContext
) or inject it using CDI, depending on the approach you go for.
If a @Secured
annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.
Alternatively to defining the roles in the @Secured
annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed
, @PermitAll
and @DenyAll
.
JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:
@DenyAll
on the method takes precedence over @RolesAllowed
and @PermitAll
on the class.@RolesAllowed
on the method takes precedence over @PermitAll
on the class.@PermitAll
on the method takes precedence over @RolesAllowed
on the class.@DenyAll
can't be attached to classes.@RolesAllowed
on the class takes precedence over @PermitAll
on the class.So an authorization filter that checks JSR-250 annotations could be like:
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Method method = resourceInfo.getResourceMethod();
// @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
if (method.isAnnotationPresent(DenyAll.class)) {
refuseRequest();
}
// @RolesAllowed on the method takes precedence over @PermitAll
RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
return;
}
// @PermitAll on the method takes precedence over @RolesAllowed on the class
if (method.isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// @DenyAll can't be attached to classes
// @RolesAllowed on the class takes precedence over @PermitAll on the class
rolesAllowed =
resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
}
// @PermitAll on the class
if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// Authentication is required for non-annotated methods
if (!isAuthenticated(requestContext)) {
refuseRequest();
}
}
/**
* Perform authorization based on roles.
*
* @param rolesAllowed
* @param requestContext
*/
private void performAuthorization(String[] rolesAllowed,
ContainerRequestContext requestContext) {
if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
refuseRequest();
}
for (final String role : rolesAllowed) {
if (requestContext.getSecurityContext().isUserInRole(role)) {
return;
}
}
refuseRequest();
}
/**
* Check if the user is authenticated.
*
* @param requestContext
* @return
*/
private boolean isAuthenticated(final ContainerRequestContext requestContext) {
// Return true if the user is authenticated or false otherwise
// An implementation could be like:
// return requestContext.getSecurityContext().getUserPrincipal() != null;
}
/**
* Refuse the request.
*/
private void refuseRequest() {
throw new AccessDeniedException(
"You don't have permissions to perform this action.");
}
}
Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature
. If you use Jersey, you don't need to write your own filter, just use the existing implementation.
This is implementation of methods after decompiling.
public static bool IsNullOrEmpty(String value)
{
return (value == null || value.Length == 0);
}
public static bool IsNullOrWhiteSpace(String value)
{
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
So it is obvious that IsNullOrWhiteSpace method also checks if value that is being passed contain white spaces.
Whitespaces refer : https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
I had to solve a similar problem--I wanted certain styles to only apply to mobile devices in landscape mode. Essentially the fonts and line spacing looked fine in every other context, so I just needed the one exception for mobile landscape. This media query worked perfectly:
@media all and (max-width: 600px) and (orientation:landscape)
{
/* styles here */
}
is null
can be used to check whether null
data is coming from a query as in following example:
declare @Mem varchar(20),@flag int
select @mem=MemberClub from [dbo].[UserMaster] where UserID=@uid
if(@Mem is null)
begin
set @flag= 0;
end
else
begin
set @flag=1;
end
return @flag;
If the original Service .InstallLog and .InstallState files are still in the folder, you can try reinstalling the executable to replace the files, then use InstallUtil /u, then uninstall the program. It's a bit convoluted, but worked in a particular instance for me.
Ajay,
The reason that you can't see the other tables is that you need to log in as 'root' in order to see them
mysql -h localhost -u root
In this example, you may show your menu centered.
<div id="main-menu-container">
<div id="main-menu">
//your menu
</div>
</div>
.f-nav{ /* To fix main menu container */
z-index: 9999;
position: fixed;
left: 0;
top: 0;
width: 100%;
}
#main-menu-container {
text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
display: inline-block;
width: 1024px; /* Your menu's width */
}
$("document").ready(function($){
var nav = $('#main-menu-container');
$(window).scroll(function () {
if ($(this).scrollTop() > 125) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
});
According to documentation it is:
spring.jpa.show-sql=true # Enable logging of SQL statements.
Also, this can be used too.
handleChange: function(state,e) {
this.setState({[state]: e.target.value});
},
render : function() {
return (
<form>
<input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleChange.bind(this, 'email')} />
<input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handleChange.bind(this, 'password')}/>
<button type="button" onClick={this.handleLogin}>Login</button>
</form>
);
},
handleLogin: function() {
console.log("EMail: ", this.state.email);
console.log("Password: ", this.state.password);
}
Type in:
java -version // This will check your JRE version
javac -version // This will check your Java compiler version if you installed the JDK
Here's the script i used on linux for an instance Nexus 5 API 24 x86 WITHOUT GoogleApis.
#!/bin/sh
~/Android/Sdk/tools/emulator @A24x86 -no-boot-anim -writable-system & #where A24x86 is the name i gave to my instance
~/Android/Sdk/platform-tools/adb wait-for-device
~/Android/Sdk/platform-tools/adb root
~/Android/Sdk/platform-tools/adb shell stop
~/Android/Sdk/platform-tools/adb remount
~/Android/Sdk/platform-tools/adb push ~/gapps/PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleLoginService.apk /system/priv-app/GoogleLoginService/GoogleLoginService.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore /system/priv-app/GoogleServicesFramework"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService /system/priv-app/Phonesky"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService/GoogleLoginService.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/Phonesky/Phonesky.apk"
~/Android/Sdk/platform-tools/adb shell start
This one did it for me.
IMPORTANT: in order to stop the app from crashing remember to grant google play services location permissions.
Configuration->Apps->Config(Gear icon)->App permissions->Location->(Top right menú)->Show system->Enable Google Play services
First thing, you should not do any DOM manipulation in controller function. Instead, you should use directives for this purpose. directive's link function is available for those kind of stuff only.
AngularJS Docs : Creating a Directive that Manipulates the DOM
app.directive('buttonDirective', function($timeout) {
return {
scope: {
change: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
$timeout(function() {
// triggering callback
scope.change();
});
});
}
};
});
change callback can be used as listener for click event.
\s
matches any white-space character\S
matches any non-white-space character[^ ]
matches anything but a space character.Pick whichever is most appropriate.
Write a custom method like this:
public Object findByYourField(Class entityClass, String yourFieldValue)
{
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(entityClass);
Root<Object> root = criteriaQuery.from(entityClass);
criteriaQuery.select(root);
ParameterExpression<String> params = criteriaBuilder.parameter(String.class);
criteriaQuery.where(criteriaBuilder.equal(root.get("yourField"), params));
TypedQuery<Object> query = entityManager.createQuery(criteriaQuery);
query.setParameter(params, yourFieldValue);
List<Object> queryResult = query.getResultList();
Object returnObject = null;
if (CollectionUtils.isNotEmpty(queryResult)) {
returnObject = queryResult.get(0);
}
return returnObject;
}
Found an interesting and neat way to export environment variables from a file:
in env.vars
:
foo=test
test script:
eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # =>
export eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
# a better one. "--" stops processing options,
# key=value list given as params
export -- `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:
const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString); // {object Date}
from here you can extract the desired values by using Date Getters:
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);
// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s); // {object Date}
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
//auth required or redirect
app.use('/account', function(req, res, next) {
console.log(req.path);
if ( !req.session.user ) {
res.redirect('/login?ref='+req.path);
} else {
next();
}
});
req.path is / when it should be /account ??
The reason for this is that Express subtracts the path your handler function is mounted on, which is '/account'
in this case.
Why do they do this?
Because it makes it easier to reuse the handler function. You can make a handler function that does different things for req.path === '/'
and req.path === '/goodbye'
for example:
function sendGreeting(req, res, next) {
res.send(req.path == '/goodbye' ? 'Farewell!' : 'Hello there!')
}
Then you can mount it to multiple endpoints:
app.use('/world', sendGreeting)
app.use('/aliens', sendGreeting)
Giving:
/world ==> Hello there!
/world/goodbye ==> Farewell!
/aliens ==> Hello there!
/aliens/goodbye ==> Farewell!
I have changed a little bit previous answer and compose WPF version of the MessageBoxEx. This code works for me great. Feel free to notify about issues of the code.
Please note:
I use GeneralObjects.MainWindowInstance
at ctor to initialize class with my main window, but actually I use it for any window due to some kind of cache for last parent window. Therefore you can simple remove out everything from ctor.
public class MessageBoxEx
{
private static HwndSource source_ = null;
private static HwndSourceHook hook_ = null;
static MessageBoxEx()
{
try
{
// create cached
createHwndSource_(GeneralObjects.MainWindowInstance);
hook_ = new HwndSourceHook(HwndSourceHook);
}
finally
{
if (null == source_ ||
null == hook_)
{
source_ = null;
hook_ = null;
}
}
}
private static void createHwndSource_(Window owner)
{
source_ = (HwndSource)PresentationSource.FromVisual(owner);
}
public static void Initialize_(Window owner = null)
{
try
{
if (null != owner)
{
if(source_.RootVisual != owner)
{
createHwndSource_(owner);
}
}
}
finally
{
if (null == source_ ||
null == hook_)
{
source_ = null;
hook_ = null;
}
}
if (null != source_ &&
null != hook_)
{
source_.AddHook(hook_);
}
}
public static MessageBoxResult Show(string messageBoxText)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText);
}
public static MessageBoxResult Show(string messageBoxText, string caption)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption);
}
public static MessageBoxResult Show(Window owner, string messageBoxText)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult, options);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult, options);
}
private enum WM : int
{
WM_ACTIVATE = 0x0006
}
private static IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if ((int)WM.WM_ACTIVATE == msg &&
source_.Handle == hwnd &&
0 == (int)wParam)
{
try
{
CenterWindow(lParam);
}
finally
{
// remove hook at once after moved message box window.
source_.RemoveHook(hook_);
}
}
return IntPtr.Zero;
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
private static void CenterWindow(IntPtr hChildWnd)
{
System.Drawing.Rectangle recChild = new System.Drawing.Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
System.Drawing.Rectangle recParent = new System.Drawing.Rectangle(0, 0, 0, 0);
success = GetWindowRect(source_.Handle, ref recParent);
System.Drawing.Point ptCenter = new System.Drawing.Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
System.Drawing.Point ptStart = new System.Drawing.Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
// I have commented this code because of I have 2 monitors
// so If application located at 1st monitor
// message box can appear at second one.
/*
ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
*/
int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
height, false);
}
}
y_prob = model.predict(x)
y_classes = y_prob.argmax(axis=-1)
As suggested here.
Using Base64 string in JSON will be very heavy. The parser has to do a lot of heavy lifting. Currently, Fresco only supports base supports Base64. Better you put something on Amazon Cloud or Firebase Cloud. And get an image as a URL. So that you can use Picasso or Glide for caching.
This is really strange... Once set, the default Charset is cached and it isn't changed while the class is in memory. Setting the "file.encoding"
property with System.setProperty("file.encoding", "Latin-1");
does nothing. Every time Charset.defaultCharset()
is called it returns the cached charset.
Here are my results:
Default Charset=ISO-8859-1
file.encoding=Latin-1
Default Charset=ISO-8859-1
Default Charset in Use=ISO8859_1
I'm using JVM 1.6 though.
(update)
Ok. I did reproduce your bug with JVM 1.5.
Looking at the source code of 1.5, the cached default charset isn't being set. I don't know if this is a bug or not but 1.6 changes this implementation and uses the cached charset:
JVM 1.5:
public static Charset defaultCharset() {
synchronized (Charset.class) {
if (defaultCharset == null) {
java.security.PrivilegedAction pa =
new GetPropertyAction("file.encoding");
String csn = (String) AccessController.doPrivileged(pa);
Charset cs = lookup(csn);
if (cs != null)
return cs;
return forName("UTF-8");
}
return defaultCharset;
}
}
JVM 1.6:
public static Charset defaultCharset() {
if (defaultCharset == null) {
synchronized (Charset.class) {
java.security.PrivilegedAction pa =
new GetPropertyAction("file.encoding");
String csn = (String) AccessController.doPrivileged(pa);
Charset cs = lookup(csn);
if (cs != null)
defaultCharset = cs;
else
defaultCharset = forName("UTF-8");
}
}
return defaultCharset;
}
When you set the file encoding to file.encoding=Latin-1
the next time you call Charset.defaultCharset()
, what happens is, because the cached default charset isn't set, it will try to find the appropriate charset for the name Latin-1
. This name isn't found, because it's incorrect, and returns the default UTF-8
.
As for why the IO classes such as OutputStreamWriter
return an unexpected result,
the implementation of sun.nio.cs.StreamEncoder
(witch is used by these IO classes) is different as well for JVM 1.5 and JVM 1.6. The JVM 1.6 implementation is based in the Charset.defaultCharset()
method to get the default encoding, if one is not provided to IO classes. The JVM 1.5 implementation uses a different method Converters.getDefaultEncodingName();
to get the default charset. This method uses its own cache of the default charset that is set upon JVM initialization:
JVM 1.6:
public static StreamEncoder forOutputStreamWriter(OutputStream out,
Object lock,
String charsetName)
throws UnsupportedEncodingException
{
String csn = charsetName;
if (csn == null)
csn = Charset.defaultCharset().name();
try {
if (Charset.isSupported(csn))
return new StreamEncoder(out, lock, Charset.forName(csn));
} catch (IllegalCharsetNameException x) { }
throw new UnsupportedEncodingException (csn);
}
JVM 1.5:
public static StreamEncoder forOutputStreamWriter(OutputStream out,
Object lock,
String charsetName)
throws UnsupportedEncodingException
{
String csn = charsetName;
if (csn == null)
csn = Converters.getDefaultEncodingName();
if (!Converters.isCached(Converters.CHAR_TO_BYTE, csn)) {
try {
if (Charset.isSupported(csn))
return new CharsetSE(out, lock, Charset.forName(csn));
} catch (IllegalCharsetNameException x) { }
}
return new ConverterSE(out, lock, csn);
}
But I agree with the comments. You shouldn't rely on this property. It's an implementation detail.
Easier way to do it in one line of code
this.setState({ object: { ...this.state.object, objectVarToChange: newData } })
There is, alas, another use of "upstream" that the other answers here are not getting at, namely to refer to the parent-child relationship of commits within a repo. Scott Chacon in the Pro Git book is particularly prone to this, and the results are unfortunate. Do not imitate this way of speaking.
For example, he says of a merge resulting a fast-forward that this happens because
the commit pointed to by the branch you merged in was directly upstream of the commit you’re on
He wants to say that commit B is the only child of the only child of ... of the only child of commit A, so to merge B into A it is sufficient to move the ref A to point to commit B. Why this direction should be called "upstream" rather than "downstream", or why the geometry of such a pure straight-line graph should be described "directly upstream", is completely unclear and probably arbitrary. (The man page for git-merge
does a far better job of explaining this relationship when it says that "the current branch head is an ancestor of the named commit." That is the sort of thing Chacon should have said.)
Indeed, Chacon himself appears to use "downstream" later to mean exactly the same thing, when he speaks of rewriting all child commits of a deleted commit:
You must rewrite all the commits downstream from 6df76 to fully remove this file from your Git history
Basically he seems not to have any clear idea what he means by "upstream" and "downstream" when referring to the history of commits over time. This use is informal, then, and not to be encouraged, as it is just confusing.
It is perfectly clear that every commit (except one) has at least one parent, and that parents of parents are thus ancestors; and in the other direction, commits have children and descendants. That's accepted terminology, and describes the directionality of the graph unambiguously, so that's the way to talk when you want to describe how commits relate to one another within the graph geometry of a repo. Do not use "upstream" or "downstream" loosely in this situation.
[Additional note: I've been thinking about the relationship between the first Chacon sentence I cite above and the git-merge
man page, and it occurs to me that the former may be based on a misunderstanding of the latter. The man page does go on to describe a situation where the use of "upstream" is legitimate: fast-forwarding often happens when "you are tracking an upstream repository, you have committed no local changes, and now you want to update to a newer upstream revision." So perhaps Chacon used "upstream" because he saw it here in the man page. But in the man page there is a remote repository; there is no remote repository in Chacon's cited example of fast-forwarding, just a couple of locally created branches.]
I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.divIWantedToHide').hide();
} else {
$('.divIWantedToHide').show();
}
});
Try this:
counter=0
while true; do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
break
elif [[ "$counter" -gt 20 ]]; then
echo "Counter limit reached, exit script."
exit 1
else
let counter++
echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
Explanation
break
- if files are present, it will break and allow the script to process the files.[[ "$counter" -gt 20 ]]
- if the counter variable is greater than 20, the script will exit.let counter++
- increments the counter by 1 at each pass.If you don't know which checkboxes your page has (ex: if you are creating them dynamically) you can simply put a hidden field with the same name and 0 value right above the checkbox.
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
This way you will get 1 or 0 based on whether the checkbox is selected or not.
This is what I achieved, but had to set width, and it cannot be percentual.
.trunc{_x000D_
width:250px; _x000D_
white-space: nowrap; _x000D_
overflow: hidden; _x000D_
text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
_x000D_
<tr>_x000D_
<td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
<td>_x000D_
<div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/
readonly="true"
is invalid HTML5, readonly="readonly"
is valid.
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#attr-input-readonly :
The readonly attribute is a boolean attribute
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="text" readonly />
<input type="text" readonly="" />
<input type="text" readonly="readonly" />
<input type="text" readonly="ReAdOnLy" />
The following are invalid:
<input type="text" readonly="0" />
<input type="text" readonly="1" />
<input type="text" readonly="false" />
<input type="text" readonly="true" />
The absence of the attribute is the only valid syntax for false:
<input type="text"/>
Recommendation
If you care about writing valid XHTML, use readonly="readonly"
, since <input readonly>
is invalid and other alternatives are less readable. Else, just use <input readonly>
as it is shorter.
For me This was the solution on macOS ReInstall the psql
brew install postgres
Start PostgreSQL server
pg_ctl -D /usr/local/var/postgres start
Initialize DB
initdb /usr/local/var/postgres
If this command throws an error the rm the old database file and re-run the above command
rm -r /usr/local/var/postgres
Create a new database
createdb postgres_test
psql -W postegres_test
You will be logged into this db and can create a user in here to login
This may be contentious but the “includes are always and extends are sometimes” is a very common misconception which has almost taken over now as the de-facto meaning. Here’s a correct approach (in my view, and checked against Jacobson, Fowler, Larmen and 10 other references).
The key to Include and extend use case relationships is to realize that, common with the rest of UML, the dotted arrow between use cases is a dependency relationship. I’ll use the terms ‘base’, ‘included’ and ‘extending’ to refer to the use case roles.
A base use case is dependent on the included use case(s); without it/them the base use case is incomplete as the included use case(s) represent sub-sequences of the interaction that may happen always OR sometimes. (This is contrary to a popular misconception about this, what your use case suggests always happens in the main scenario and sometimes happens in alternate flows simply depends on what you choose as your main scenario; use cases can easily be restructured to represent a different flow as the main scenario and this should not matter).
In the best practice of one way dependency the base use case knows about (and refers to) the included use case, but the included use case shouldn’t ‘know’ about the base use case. This is why included use cases can be: a) base use cases in their own right and b) shared by a number of base use cases.
The extending use case is dependent on the base use case; it literally extends the behavior described by the base use case. The base use case should be a fully functional use case in its own right (‘include’s included of course) without the extending use case’s additional functionality.
Extending use cases can be used in several situations:
One important aspect to consider is that the extending use case can ‘insert’ behavior in several places in the base use case’s flow, not just in a single place as an included use case does. For this reason, it is highly unlikely that an extending use case will be suitable to extend more than one base use case.
As to dependency, the extending use case is dependent on the base use case and is again a one-way dependency, i.e. the base use case doesn’t need any reference to the extending use case in the sequence. That doesn’t mean you can’t demonstrate the extension points or add a x-ref to the extending use case elsewhere in the template, but the base use case must be able to work without the extending use case.
I hope I’ve shown that the common misconception of “includes are always, extends are sometimes” is either wrong or at best simplistic. This version actually makes more sense if you consider all the issues about the directionality of the arrows the misconception presents – in the correct model it’s just dependency and doesn’t potentially change if you refactor the use case contents.
I have three answers to this question:
It is against user experience UX best practice to use BLOB and CLOB data types in string and retrieving binary data from an SQL database thus it is advised that you use the technique that involves storing the URL for the image( or any Binary file in the database). This URL will help the user application to retrieve and use this binary file.
Second the BLOB and CLOB data types are only available to a number of SQL versions thus functions such as LOAD_FILE or the datatypes themselves could miss in some versions.
Third DON'T USE BLOB OR CLOB. Store the URL; let the user application access the binary file from a folder in the project directory.
According to the answers here and on other 'flows, I've made a version that looks like the one of Google Chrome, with css3 transition. JS Fiddle
Lets start eazy, since we have the js above on this page, we can worry about the css and layout. The layout that we will be using is an <a>
element with a <img>
element or a font awesome icon (<i class="fa fa-flag"></i>
) and a <span>
to show the keyboard shortcuts. So this is the structure:
<a href="#" onclick="doSomething()">
<img src="path/to/image.gif" />
This is a menu option
<span>Ctrl + K</span>
</a>
We will put these in a div and show that div on the right-click. Let's style them like in Google Chrome, shall we?
#menu a {
display: block;
color: #555;
text-decoration: no[...]
Now we will add the code from the accepted answer, and get the X and Y value of the cursor. To do this, we will use e.clientX
and e.clientY
. We are using client, so the menu div has to be fixed.
var i = document.getElementById("menu").style;
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
var posX = e.clientX;
var posY = e.client[...]
And that is it! Just add the css transisions to fade in and out, and done!
var i = document.getElementById("menu").style;_x000D_
if (document.addEventListener) {_x000D_
document.addEventListener('contextmenu', function(e) {_x000D_
var posX = e.clientX;_x000D_
var posY = e.clientY;_x000D_
menu(posX, posY);_x000D_
e.preventDefault();_x000D_
}, false);_x000D_
document.addEventListener('click', function(e) {_x000D_
i.opacity = "0";_x000D_
setTimeout(function() {_x000D_
i.visibility = "hidden";_x000D_
}, 501);_x000D_
}, false);_x000D_
} else {_x000D_
document.attachEvent('oncontextmenu', function(e) {_x000D_
var posX = e.clientX;_x000D_
var posY = e.clientY;_x000D_
menu(posX, posY);_x000D_
e.preventDefault();_x000D_
});_x000D_
document.attachEvent('onclick', function(e) {_x000D_
i.opacity = "0";_x000D_
setTimeout(function() {_x000D_
i.visibility = "hidden";_x000D_
}, 501);_x000D_
});_x000D_
}_x000D_
_x000D_
function menu(x, y) {_x000D_
i.top = y + "px";_x000D_
i.left = x + "px";_x000D_
i.visibility = "visible";_x000D_
i.opacity = "1";_x000D_
}
_x000D_
body {_x000D_
background: white;_x000D_
font-family: sans-serif;_x000D_
color: #5e5e5e;_x000D_
}_x000D_
_x000D_
#menu {_x000D_
visibility: hidden;_x000D_
opacity: 0;_x000D_
position: fixed;_x000D_
background: #fff;_x000D_
color: #555;_x000D_
font-family: sans-serif;_x000D_
font-size: 11px;_x000D_
-webkit-transition: opacity .5s ease-in-out;_x000D_
-moz-transition: opacity .5s ease-in-out;_x000D_
-ms-transition: opacity .5s ease-in-out;_x000D_
-o-transition: opacity .5s ease-in-out;_x000D_
transition: opacity .5s ease-in-out;_x000D_
-webkit-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
-moz-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
padding: 0px;_x000D_
border: 1px solid #C6C6C6;_x000D_
}_x000D_
_x000D_
#menu a {_x000D_
display: block;_x000D_
color: #555;_x000D_
text-decoration: none;_x000D_
padding: 6px 8px 6px 30px;_x000D_
width: 250px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#menu a img,_x000D_
#menu a i.fa {_x000D_
height: 20px;_x000D_
font-size: 17px;_x000D_
width: 20px;_x000D_
position: absolute;_x000D_
left: 5px;_x000D_
top: 2px;_x000D_
}_x000D_
_x000D_
#menu a span {_x000D_
color: #BCB1B3;_x000D_
float: right;_x000D_
}_x000D_
_x000D_
#menu a:hover {_x000D_
color: #fff;_x000D_
background: #3879D9;_x000D_
}_x000D_
_x000D_
#menu hr {_x000D_
border: 1px solid #EBEBEB;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<h2>CSS3 and JAVASCRIPT custom menu.</h2>_x000D_
<em>Stephan Stanisic | Lisence free</em>_x000D_
<p>Right-click anywhere on this page to open the custom menu. Styled like the Google Chrome contextmenu. And yes, you can use <i class="fa fa-flag"></i>font-awesome</p>_x000D_
<p style="font-size: small">_x000D_
<b>Lisence</b>_x000D_
<br /> "THE PIZZA-WARE LICENSE" (Revision 42):_x000D_
<br /> You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a Pizza in return._x000D_
<br />_x000D_
<a style="font-size:xx-small" href="https://github.com/KLVN/UrbanDictionary_API#license">https://github.com/KLVN/UrbanDictionary_API#license</a>_x000D_
</p>_x000D_
<br />_x000D_
<br />_x000D_
<small>(The white body background is just because I hate the light blue editor background on the result on jsfiddle)</small>_x000D_
<div id="menu">_x000D_
<a href="#">_x000D_
<img src="http://puu.sh/nr60s/42df867bf3.png" /> AdBlock Plus <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
<a href="#">_x000D_
<img src="http://puu.sh/nr5Z6/4360098fc1.png" /> SNTX <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
<hr />_x000D_
<a href="#">_x000D_
<i class="fa fa-fort-awesome"></i> Fort Awesome <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
<a href="#">_x000D_
<i class="fa fa-flag"></i> Font Awesome <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
</div>
_x000D_
I am writing an application which can run on both x86 and x64 platform for Windows 7 and querying the below variable just pulls the right program files folder path on any platform.
Environment.GetEnvironmentVariable("PROGRAMFILES")
I don't recall the exact syntax, but you may set the table column to be case insensitive. But be careful because then you won't be able to match based on case anymore and if you WANT 'cool' to not match 'CoOl' it will no longer be possible.
You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.
while running:
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(6) # with the port open, the response will be buffered
# so wait a bit longer for response here
# Serial read section
msg = ard.read(ard.inWaiting()) # read everything in the input buffer
print ("Message from arduino: ")
print (msg)
The Python Serial.read
function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.
On the Arduino side, you should consider what happens in your loop
function when no data is available.
void loop()
{
// serial read section
while (Serial.available()) // this will be skipped if no data present, leading to
// the code sitting in the delay function below
{
delay(30); //delay to allow buffer to fill
if (Serial.available() >0)
{
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
}
}
Instead, wait at the start of the loop
function until data arrives:
void loop()
{
while (!Serial.available()) {} // wait for data to arrive
// serial read section
while (Serial.available())
{
// continue as before
EDIT 2
Here's what I get when interfacing with your Arduino app from Python:
>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'
So that seems to be working fine.
In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:
#!/usr/bin/python
import serial
import syslog
import time
#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X
ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino
i = 0
while (i < 4):
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
ard.flush()
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(1) # I shortened this to match the new value in your Arduino code
# Serial read section
msg = ard.read(ard.inWaiting()) # read all characters in buffer
print ("Message from arduino: ")
print (msg)
i = i + 1
else:
print "Exiting"
exit()
Here's the output of the above now:
$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Exiting
When you say you are Forking a repository you are basically creating a copy of the repository under your GitHub ID. The main point to note here is that any changes made to the original repository will be reflected back to your forked repositories(you need to fetch and rebase). However, if you make any changes to your forked repository you will have to explicitly create a pull request to the original repository. If your pull request is approved by the administrator of the original repository, then your changes will be committed/merged with the existing original code-base. Until then, your changes will be reflected only in the copy you forked.
In short:
The Fork & Pull Model lets anyone fork an existing repository and push changes to their personal fork without requiring access be granted to the source repository. The changes must then be pulled into the source repository by the project maintainer.
Note that after forking you can clone your repository (the one under your name) locally on your machine. Make changes in it and push it to your forked repository. However, to reflect your changes in the original repository your pull request must be approved.
Couple of other interesting dicussions -
Easiest way:
param_a = 1
param_b = 2
result = param_a === param_b ? 'Same!' : 'Not same!'
since param_a
is not equal to param_b
then the result
's value will be Not same!
I think the most clear answer is AmanKow's one. It boils down to how u want to organize your code. You can write everything as module level functions which are wrapped in the namespace of the module i.e
module.py (file 1)
---------
def f1() : pass
def f2() : pass
def f3() : pass
usage.py (file 2)
--------
from module import *
f1()
f2()
f3()
def f4():pass
def f5():pass
usage1.py (file 3)
-------------------
from usage import f4,f5
f4()
f5()
The above procedural code is not well organized, as you can see after only 3 modules it gets confusing, what is each method do ? You can use long descriptive names for functions(like in java) but still your code gets unmanageable very quick.
The object oriented way is to break down your code into manageable blocks i.e Classes & objects and functions can be associated with objects instances or with classes.
With class functions you gain another level of division in your code compared with module level functions. So you can group related functions within a class to make them more specific to a task that you assigned to that class. For example you can create a file utility class :
class FileUtil ():
def copy(source,dest):pass
def move(source,dest):pass
def copyDir(source,dest):pass
def moveDir(source,dest):pass
//usage
FileUtil.copy("1.txt","2.txt")
FileUtil.moveDir("dir1","dir2")
This way is more flexible and more maintainable, you group functions together and its more obvious to what each function do. Also you prevent name conflicts, for example the function copy may exist in another imported module(for example network copy) that you use in your code, so when you use the full name FileUtil.copy() you remove the problem and both copy functions can be used side by side.
You can get a JSON file that maps country codes to phone codes from http://country.io/phone.json:
...
BD: "880",
BE: "32",
BF: "226",
BG: "359",
BA: "387",
...
If you want country names then http://country.io/names.json will give you that:
...
"AL": "Albania",
"AM": "Armenia",
"AO": "Angola",
"AQ": "Antarctica",
"AR": "Argentina",
...
See http://country.io/data for more details.
If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.
REM Get argument values. If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )
REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name = %DatabaseName%
Here's another example. I wrote a method that finds the median of the values in two sorted arrays. The method assumes the arrays are already sorted. For performance reasons, it should NOT sort the arrays first, or even check to ensure they're sorted. However, it's a serious bug to call this method with unsorted data, and we want those bugs to get caught early, in the development phase. So here's how I handled those seemingly conflicting goals:
public static int medianOf(int[] a, int[] b) {
assert assertionOnlyIsSorted(a); // Assertion is order n
assert assertionOnlyIsSorted(b);
... // rest of implementation goes here. Algorithm is order log(n)
}
public static boolean assertionOnlyIsSorted(int[] array) {
for (int i=1; i<array.length; ++i) {
if (array[i] < array[i-1]) {
return false;
}
return true;
}
}
This way, the test, which is slow, is only performed during the development phase, where speed is less important than catching bugs. You want the medianOf()
method to have log(n) performance, but the "is sorted" test is order n. So I put it inside an assertion, to limit its use to the development phase, and I give it a name that makes it clear it's not suitable for production.
This way I have the best of both worlds. In development, I know that any method that calls this incorrectly will get caught and fixed. And I know that the slow test to do so won't affect performance in production. (It's also a good illustration of why you want to leave assertions off in production, but turn them on in development.)
$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.
It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.
EDIT: I don't think I explained this well enough originally, but $resource
does some funky stuff with returns. Todo.get()
and Todo.query()
both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save()
before the get()
callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then()
or the callback method.
var Todo = $resource('/api/1/todo/:id');
//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();
//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();
//which is basically the same as...
Todo.get({id: 123}, function(todo) {
todo.foo += '!';
todo.$save();
});
//get a list of todos
Todo.query(function(todos) {
//do something with todos
angular.forEach(todos, function(todo) {
todo.foo += ' something';
todo.$save();
});
});
//delete a todo
Todo.$delete({id: 123});
Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):
var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();
I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource
, you should probably just be using $http
on it's own.
As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.
To leverage promises with $resource
, you need to use the $promise
property on the returned value.
var Todo = $resource('/api/1/todo/:id');
Todo.get({id: 123}).$promise.then(function(todo) {
// success
$scope.todos = todos;
}, function(errResponse) {
// fail
});
Todo.query().$promise.then(function(todos) {
// success
$scope.todos = todos;
}, function(errResponse) {
// fail
});
Just keep in mind that the $promise
property is a property on the same values it was returning above. So you can get weird:
var todo = Todo.get({id: 123}, function() {
$scope.todo = todo;
});
Todo.get({id: 123}, function(todo) {
$scope.todo = todo;
});
Todo.get({id: 123}).$promise.then(function(todo) {
$scope.todo = todo;
});
var todo = Todo.get({id: 123});
todo.$promise.then(function() {
$scope.todo = todo;
});
Here is what i did and it works.
I just used a stringified object.
$scope.thread = [
{
mostRecent:{text:'hello world',timeStamp:12345678 }
allMessages:[]
}
{MoreThreads...}
{etc....}
]
<div ng-repeat="message in thread | orderBy : '-mostRecent.timeStamp'" >
if i wanted to sort by text i would do
orderBy : 'mostRecent.text'
In Swift, you can overload existing operators:
func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}
func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}
Then, you can compare NSDates directly with <
, >
, and ==
(already supported).
Try this code, you can set loading image with it, so the users knows that your app is loading an image from url:
UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]];
[yourImageView setContentMode:UIViewContentModeScaleAspectFit];
//Request image data from the URL:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://yourdomain.com/yourimg.png"]];
dispatch_async(dispatch_get_main_queue(), ^{
if (imgData)
{
//Load the data into an UIImage:
UIImage *image = [UIImage imageWithData:imgData];
//Check if your image loaded successfully:
if (image)
{
yourImageView.image = image;
}
else
{
//Failed to load the data into an UIImage:
yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
}
}
else
{
//Failed to get the image data:
yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
}
});
});
For beginner try this too.
class Visibility extends StatefulWidget {
@override
_VisibilityState createState() => _VisibilityState();
}
class _VisibilityState extends State<Visibility> {
bool a = true;
String mText = "Press to hide";
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Visibility",
home: new Scaffold(
body: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
onPressed: _visibilitymethod, child: new Text(mText),),
a == true ? new Container(
width: 300.0,
height: 300.0,
color: Colors.red,
) : new Container(),
],
)
),
);
}
void _visibilitymethod() {
setState(() {
if (a) {
a = false;
mText = "Press to show";
} else {
a = true;
mText = "Press to hide";
}
});
}
}
Maybe this can help
string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));
answer from msdn.
The "proper conversion" between byte[]
and String
is to explicitly state the encoding you want to use. If you start with a byte[]
and it does not in fact contain text data, there is no "proper conversion". String
s are for text, byte[]
is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.
If you really must use a String
to hold binary data then the safest way is to use Base64 encoding.
Rather than use Ajax / XMLHttpRequest / $http to invoke your WebApi method, use an html form. That way the browser saves the file using the filename and content type information in the response headers, and you don't need to work around javascript's limitations on file handling. You might also use a GET method rather than a POST as the method returns data. Here's an example form:
<form name="export" action="/MyController/Export" method="get" novalidate>
<input name="id" type="id" ng-model="id" placeholder="ID" />
<input name="fileName" type="text" ng-model="filename" placeholder="file name" required />
<span class="error" ng-show="export.fileName.$error.required">Filename is required!</span>
<button type="submit" ng-disabled="export.$invalid">Export</button>
</form>
Depending on distribution, using "cron reload" might do nothing. To paste a snippet out of init.d/cron (debian squeeze):
reload|force-reload) log_daemon_msg "Reloading configuration files for periodic command scheduler" "cron"
# cron reloads automatically
log_end_msg 0
;;
Some developer/maintainer relied on it reloading, but doesn't, and in this case there's not a way to force reload. I'm generating my crontab files as part of a deploy, and unless somehow the length of the file changes, the changes are not reloaded.
Utilizing the "dynamic table" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following. If your platform doesn't offer an equivalent to the "dynamic table" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the "dynamic table" to a temp table, and then performing a subsequent select on the temp table.
DECLARE @T TABLE(
[contract] INT,
project INT,
activity INT
)
INSERT INTO @T VALUES( 1000, 8000, 10 )
INSERT INTO @T VALUES( 1000, 8000, 20 )
INSERT INTO @T VALUES( 1000, 8001, 10 )
INSERT INTO @T VALUES( 2000, 9000, 49 )
INSERT INTO @T VALUES( 2000, 9001, 49 )
INSERT INTO @T VALUES( 3000, 9000, 79 )
INSERT INTO @T VALUES( 3000, 9000, 78 )
SELECT
[contract],
[Activity] = max (activity)
FROM
(
SELECT
[contract],
[Activity]
FROM
@T
GROUP BY
[contract],
[Activity]
) t
GROUP BY
[contract]
HAVING count (*) = 1
UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate
guard. I'm degrading to my old method, ie:
this answer
UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.
UPDATE1: I wrote this answer in the era of Old-Router
, when there used to be only one event route-changed
notified via router.subscribe()
. I also felt overload of the below approach and tried to do it using only router.subscribe()
, and it backfired because there was no way to detect canceled navigation
. So I had to revert back to lengthy approach(double work).
If you know your way around in Angular2, this is what you'll need
Boot.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';
bootstrap(MyApp, [SpinnerService]);
Root Component- (MyApp)
import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
selector: 'my-app',
directives: [SpinnerComponent],
template: `
<spinner-component></spinner-component>
<router-outlet></router-outlet>
`
})
export class MyApp { }
Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)
import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
selector: 'spinner-component',
'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
public active: boolean;
public constructor(spinner: SpinnerService) {
spinner.status.subscribe((status: boolean) => {
this.active = status;
});
}
}
Spinner-Service (bootstrap this service)
Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';
@Injectable()
export class SpinnerService {
public status: Subject<boolean> = new Subject();
private _active: boolean = false;
public get active(): boolean {
return this._active;
}
public set active(v: boolean) {
this._active = v;
this.status.next(v);
}
public start(): void {
this.active = true;
}
public stop(): void {
this.active = false;
}
}
All Other Routes' Components
(sample):
import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {
constructor(public spinner: SpinnerService){}
ngOnInit(){
this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
}
ngOnDestroy(){
this.spinner.start();
}
}
Implemented in JavaScript (ES6):
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
Usage:
const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
function draw( x, y ){
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.beginPath();
ctx.strokeStyle = "orange";
ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
ctx.lineWidth = 3;
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "indigo";
ctx.arc( x, y, 6, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
let angle = 0; // In degrees
setInterval(function(){
const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
console.log( x, y );
draw( x, y );
document.querySelector("#degrees").innerHTML = angle + "°";
document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
Q:How to access name array text field
<input type="text" id="task" name="task[]" />
Answer - Using Input name array :
$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()
Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url
# 1: Pause timeout and page loading
self.timeout.pause()
sleep(1)
# 2: Check for internet connection (Really lazy way)
while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)
# 3:Try again
if self.url == self.page().mainFrame().url():
self.page().action(QWebPage.Reload)
self.timeout.resume(60)
else:
self.page().action(QWebPage.Stop)
self.page().mainFrame().load(self.url)
self.timeout.resume(30)
return False
The SyntaxError: unexpected EOF while parsing
means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100):
and requires at least one line afterwards that contains code that should be in it.
It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3
but not for code blocks like for loops. See the following example:
In [1]: for i in range(100):
File "<ipython-input-1-ece1e5c2587f>", line 1
for i in range(100):
^
SyntaxError: unexpected EOF while parsing
To avoid this error, you have to enter the whole code block as a single input:
In [2]: for i in range(5):
...: print(i, end=', ')
0, 1, 2, 3, 4,
This happened to me when I tried to use my older code in new android with androidx implementations. change your XML definition to;
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:titleTextColor="@android:color/white" />
then in your java code;
import androidx.appcompat.widget.Toolbar;
If someone notices this behavior coming out of left field, check to make sure you don't have any breakpoints set in web.config. I must have set one with a stray mouse click, and it really slowed down all debug operations.
You can use:
System.getProperty("os.name")
P.S. You may find this code useful:
class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}
All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)
Changes to be committed: (use "git reset HEAD ..." to unstage)
It's a C heritage, in C, if you do :
enum TokenType
{
blah1 = 0x00000000,
blah2 = 0X01000000,
blah3 = 0X02000000
};
you'll have to use it doing something like :
enum TokenType foo;
But if you do this :
typedef enum e_TokenType
{
blah1 = 0x00000000,
blah2 = 0X01000000,
blah3 = 0X02000000
} TokenType;
You'll be able to declare :
TokenType foo;
But in C++, you can use only the former definition and use it as if it were in a C typedef.
For a []string
, you can use strings.Join()
:
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz
You have two possibilities (for an IPv4 address) :
varchar(15)
, if your want to store the IP address as a string
192.128.0.15
for instanceinteger
(4 bytes), if you convert the IP address to an integer
3229614095
for the IP I used before
The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).
About those manipulations, see the ip2long()
and long2ip()
functions, on the PHP-side, or inet_aton()
and inet_ntoa()
on the MySQL-side.
You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
host = host.substring(idx); //remove scheme if present
}
#Pure css method
Place this at the top of your code (before header tag)
<style> .loader {_x000D_
position: fixed;_x000D_
background-color: #FFF;_x000D_
opacity: 1;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 10;_x000D_
}_x000D_
</style>
_x000D_
<div class="loader">_x000D_
Your Content For Load Screen_x000D_
</div>
_x000D_
And This At The Bottom after all other code (except /html tag)
<style>_x000D_
.loader {_x000D_
-webkit-animation: load-out 1s;_x000D_
animation: load-out 1s;_x000D_
-webkit-animation-fill-mode: forwards;_x000D_
animation-fill-mode: forwards;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes load-out {_x000D_
from {_x000D_
top: 0;_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
to {_x000D_
top: 100%;_x000D_
opacity: 0;_x000D_
}_x000D_
}_x000D_
_x000D_
@keyframes load-out {_x000D_
from {_x000D_
top: 0;_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
to {_x000D_
top: 100%;_x000D_
opacity: 0;_x000D_
}_x000D_
}_x000D_
</style>
_x000D_
This always works for me 100% of the time
Here's another solution using the bin_data()
function from the mltools package.
library(mltools)
# Resulting bins have an equal number of observations in each group
das[, "wt2"] <- bin_data(das$wt, bins=3, binType = "quantile")
# Resulting bins are equally spaced from min to max
das[, "wt3"] <- bin_data(das$wt, bins=3, binType = "explicit")
# Or if you'd rather define the bins yourself
das[, "wt4"] <- bin_data(das$wt, bins=c(-Inf, 250, 322, Inf), binType = "explicit")
das
anim wt wt2 wt3 wt4
1 1 181.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
2 2 179.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
3 3 180.5 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
4 4 201.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
5 5 201.5 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
6 6 245.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
7 7 246.4 [245.466666666667, 394] [179, 250.666666666667) [-Inf, 250)
8 8 189.3 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
9 9 301.0 [245.466666666667, 394] [250.666666666667, 322.333333333333) [250, 322)
10 10 354.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
11 11 369.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
12 12 205.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
13 13 199.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
14 14 394.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
15 15 231.3 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
Best try for windows:
Open up cmd.
run the following command:
C:\wamp64\bin\apache\apache2.4.17\bin\httpd.exe -d C:/wamp64/bin/apache/apache2.4.17
C:\wamp64\bin\apache\apache2.4.17\bin\ Should be replaced with the path where your Apache is installed.
you use \ because \ is an escape character ;)
If the service could not start it will return the error.
For me it was the DocumentRoot was invalid :)
Do you mean like this
int index = 2;
string s = "hello";
Console.WriteLine(s[index]);
string also implements IEnumberable<char>
so you can also enumerate it like this
foreach (char c in s)
Console.WriteLine(c);
When you create a cookie via PHP die Default Value is 0, from the manual:
If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes)
Otherwise you can set the cookies lifetime in seconds as the third parameter:
http://www.php.net/manual/en/function.setcookie.php
But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).
don't give this in file input value="123".
$(document).ready(function(){
var img = $('#uploadPicture').val();
});
This may come a bit too late, but I have written something for this very purpose. My library will mock out the basic crud repository methods for you as well as interpret most of the functionalities of your query methods. You will have to inject functionalities for your own native queries, but the rest are done for you.
Take a look:
https://github.com/mmnaseri/spring-data-mock
UPDATE
This is now in Maven central and in pretty good shape.
from __future__ import division
somelist = [1,12,2,53,23,6,17]
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)
If you want to manually find the minimum as a function:
somelist = [1,12,2,53,23,6,17]
def my_min_function(somelist):
min_value = None
for value in somelist:
if not min_value:
min_value = value
elif value < min_value:
min_value = value
return min_value
Python 3.4 introduced the statistics
package, which provides mean
and additional stats:
from statistics import mean, median
somelist = [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)
I have been running some time comparisons between the abovementioned versions:
function[0] = 42;
function.insert(std::map<int, int>::value_type(0, 42));
function.insert(std::pair<int, int>(0, 42));
function.insert(std::make_pair(0, 42));
Turns out that time differences between the insert versions are tiny.
#include <map>
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time;
class Widget {
public:
Widget() {
m_vec.resize(100);
for(unsigned long it = 0; it < 100;it++) {
m_vec[it] = 1.0;
}
}
Widget(double el) {
m_vec.resize(100);
for(unsigned long it = 0; it < 100;it++) {
m_vec[it] = el;
}
}
private:
std::vector<double> m_vec;
};
int main(int argc, char* argv[]) {
std::map<int,Widget> map_W;
ptime t1 = boost::posix_time::microsec_clock::local_time();
for(int it = 0; it < 10000;it++) {
map_W.insert(std::pair<int,Widget>(it,Widget(2.0)));
}
ptime t2 = boost::posix_time::microsec_clock::local_time();
time_duration diff = t2 - t1;
std::cout << diff.total_milliseconds() << std::endl;
std::map<int,Widget> map_W_2;
ptime t1_2 = boost::posix_time::microsec_clock::local_time();
for(int it = 0; it < 10000;it++) {
map_W_2.insert(std::make_pair(it,Widget(2.0)));
}
ptime t2_2 = boost::posix_time::microsec_clock::local_time();
time_duration diff_2 = t2_2 - t1_2;
std::cout << diff_2.total_milliseconds() << std::endl;
std::map<int,Widget> map_W_3;
ptime t1_3 = boost::posix_time::microsec_clock::local_time();
for(int it = 0; it < 10000;it++) {
map_W_3[it] = Widget(2.0);
}
ptime t2_3 = boost::posix_time::microsec_clock::local_time();
time_duration diff_3 = t2_3 - t1_3;
std::cout << diff_3.total_milliseconds() << std::endl;
std::map<int,Widget> map_W_0;
ptime t1_0 = boost::posix_time::microsec_clock::local_time();
for(int it = 0; it < 10000;it++) {
map_W_0.insert(std::map<int,Widget>::value_type(it,Widget(2.0)));
}
ptime t2_0 = boost::posix_time::microsec_clock::local_time();
time_duration diff_0 = t2_0 - t1_0;
std::cout << diff_0.total_milliseconds() << std::endl;
system("pause");
}
This gives respectively for the versions (I ran the file 3 times, hence the 3 consecutive time differences for each):
map_W.insert(std::pair<int,Widget>(it,Widget(2.0)));
2198 ms, 2078 ms, 2072 ms
map_W_2.insert(std::make_pair(it,Widget(2.0)));
2290 ms, 2037 ms, 2046 ms
map_W_3[it] = Widget(2.0);
2592 ms, 2278 ms, 2296 ms
map_W_0.insert(std::map<int,Widget>::value_type(it,Widget(2.0)));
2234 ms, 2031 ms, 2027 ms
Hence, results between different insert versions can be neglected (didn't perform a hypothesis test though)!
The map_W_3[it] = Widget(2.0);
version takes about 10-15 % more time for this example due to an initialization with the default constructor for Widget.
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn't have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()
+1 to him.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
$ResidentialData = $pdo->prepare($sql);
$ResidentialData->execute(array($lapi));
$ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
$CommercialData = $pdo->prepare($sql);
$CommercialData->execute(array($lapi));
$CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);
$Prospects = array_merge($ResidentialProspects,$CommercialProspects);
echo '<pre>';
var_dump($Prospects);
echo '</pre>';
Maybe this will help someone else out.
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
Use the Resource like
ResourceBundle rb = ResourceBundle.getBundle("com//sudeep//internationalization//MyApp",locale);
or
ResourceBundle rb = ResourceBundle.getBundle("com.sudeep.internationalization.MyApp",locale);
Just give the qualified path .. Its working for me!!!
Another method through re
module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.
>>> import re
>>> s = "many fancy word \nhello \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']
Above regex would match one or more non-space characters.
There are TCP proxies out there, like iprelay and Sloppy, that do bandwidth shaping to simulate slow connections. You can also do bandwidth shaping and simulate packet loss using IP filtering tools like ipfw and iptables.
I've been plagued by the same issue for quite some time now and finally decided to look into this. It turned out the issue is that my project had a dependency on http-builder-0.5.2.jar which bundled a log4j.xml file within itself. And sure enough, the log level for org.apache.http.wire was DEBUG! The way I found it was just to go through all the jar files in my dependencies and do "jar tvf" and grepping for log4j.
While this discovery led to the eventual solution of upping the version of my http-builder dependency to 0.6, it still baffles me what must have gone through the developer's mind when bundling the log4j.xml file into the jar file. Anyway, that's probably not relevant to this thread for now. But I figured it's useful to mention this solution I found given that when I was searching for a solution before now, mine never came up. Hopefully someone will find this useful.
Generic List<T>
have the Where<T>(Func<T, Boolean>)
extension method that can be used to filter data.
In your case with a row array:
var rows = rowsArray.Where(row => row["LastName"].ToString().StartsWith("a"));
If you are using DataRowCollection
, you need to cast it first.
var rows = dataTableRows.Cast<DataRow>().Where(row => row["LastName"].ToString().StartsWith("a"));
Per the Android docs SystemClock.elapsedRealtime()
is the recommend basis for general purpose interval timing. This is because, per the documentation, elapsedRealtime() is guaranteed to be monotonic, [...], so is the recommend basis for general purpose interval timing.
The SystemClock documentation has a nice overview of the various time methods and the applicable use cases for them.
SystemClock.elapsedRealtime()
and SystemClock.elapsedRealtimeNanos()
are the best bet for calculating general purpose elapsed time.SystemClock.uptimeMillis()
and System.nanoTime()
are another possibility, but unlike the recommended methods, they don't include time in deep sleep. If this is your desired behavior then they are fine to use. Otherwise stick with elapsedRealtime()
.System.currentTimeMillis()
as this will return "wall" clock time. Which is unsuitable for calculating elapsed time as the wall clock time may jump forward or backwards. Many things like NTP clients can cause wall clock time to jump and skew. This will cause elapsed time calculations based on currentTimeMillis()
to not always be accurate.When the game starts:
long startTime = SystemClock.elapsedRealtime();
When the game ends:
long endTime = SystemClock.elapsedRealtime();
long elapsedMilliSeconds = endTime - startTime;
double elapsedSeconds = elapsedMilliSeconds / 1000.0;
Also, Timer() is a best effort timer and will not always be accurate. So there will be an accumulation of timing errors over the duration of the game. To more accurately display interim time, use periodic checks to System.currentTimeMillis()
as the basis of the time sent to setText(...)
.
Also, instead of using Timer
, you might want to look into using TimerTask
, this class is designed for what you want to do. The only problem is that it counts down instead of up, but that can be solved with simple subtraction.
I had the same error turns out the only thing i did wrong was to name my 'templates' folder,'template' without 's'. After changing that it worked fine,dont know why its a thing but it is.
They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:
select EmpNo, SampleText
from test
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');
One alternative without using zip
:
list_c = [(p1, p2) for idx1, p1 in enumerate(list_a) for idx2, p2 in enumerate(list_b) if idx1==idx2]
In case one wants to get not only tuples 1st with 1st, 2nd with 2nd... but all possible combinations of the 2 lists, that would be done with
list_d = [(p1, p2) for p1 in list_a for p2 in list_b]
This should work, at least according to the Search Filter Syntax article on MSDN network.
The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.
You may also try separating the filter into two parts:
(|(displayName=*searchstring)(displayName=searchstring*))
nor does it appear in the list of environments that can be added when I click the "Add" button. All I see is the J2EE Runtime Library.
Go get "Eclipse for Java EE developers". Note the extra "EE". This includes among others the Web Tools Platform with among others a lot of server plugins with among others the one for Apache Tomcat 5.x. It's also logically; JSP/Servlet is part of the Java EE API.
If your numbers are a, b and c then:
int a = 1;
int b = 2;
int c = 3;
int d = a > b ? a : b;
return c > d ? c : d;
This could turn into one of those "how many different ways can we do this" type questions!
I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).
String.prototype.splice = function(startIndex,length,insertString){
return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
};
You can use it like this:
var creditCardNumber = "5500000000000004";
var cardSuffix = creditCardNumber.splice(0,12,'****');
console.log(cardSuffix); // output: ****0004
See Test Results: https://jsfiddle.net/0quz9q9m/5/
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
Nested fragments are not currently supported. Trying to put a fragment within the UI of another fragment will result in undefined and likely broken behavior.
Update: Nested fragments are supported as of Android 4.2 (and Android Support Library rev 11) : http://developer.android.com/about/versions/android-4.2.html#NestedFragments
NOTE (as per this docs): "Note: You cannot inflate a layout into a fragment when that layout includes a <fragment>
. Nested fragments are only supported when added to a fragment dynamically."
How to make the HTML link activated by clicking on the <li> ?
By making your link as big as your li: just move the instruction
display: block;
from li to a and you are done.
That is:
#menu li
{
/* no more display:block; on list item */
list-style: none;
background: #e8eef4 url(arrow.gif) 2% 50% no-repeat;
border: 1px solid #b2b2b2;
padding: 0;
margin-top: 5px;
}
#menu li a
{
display:block; /* moved to link */
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
padding-right:.5em;
color: #696969;
}
Side note: you can remove "ul" from your two selectors: #menu is a sufficient indication except if you need to give weight to these two rules in order to override other instructions.
Revisited in 2015:
<img src="http://imageurl" style="width: auto; height: auto;max-width: 120px;max-height: 100px">
I've revisited it as all common browsers now have working auto suggested by Cherif above, so that works even better as you don't need to know if image is wider than taller.
older version: If you are limited by box of 120x100 for example you can do
<img src="http://image.url" height="100" style="max-width: 120px">
You can accomplish this two ways, both of which need to be done through editing your template files.
The first one is just to add an html link to your navigation where ever you want it to show up.
The second (and my guess, the one you're looking for) is to create a new page template, which isn't too difficult if you have the ability to create a new .php file in your theme/template directory. Something like the below code should do:
<?php /*
Template Name: Page Redirect
*/
header('Location: http://www.nameofnewsite.com');
exit();
?>
Where the template name is whatever you want to set it too and the url in the header function is the new url you want to direct a user to. After you modify the above code to meet your needs, save it in a php file in your active theme folder to the template name. So, if you leave the name of your template "Page Redirect" name the php file page-redirect.php.
After that's been saved, log into your WordPress backend, and create a new page. You can add a title and content to the body if you'd like, but the important thing to note is that on the right hand side, there should be a drop down option for you to choose which page template to use, with default showing first. In that drop down list, there should be the name of the new template file to use. Select the new template, publish the page, and you should be golden.
Also, you can do this dynamically as well by using the Custom Fields section below the body editor. If you're interested, let me know and I can paste the code for that guy in a new response.
The comment in your code is wrong. INADDR_ANY
doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.
$('#select_id option:eq(0)').prop('selected', 'selected');
its good
Without using 'length' you can do it like this:
if ($('input[type=checkbox]').is(":checked")) {
//any one is checked
}
else {
//none is checked
}
If you have some panels or groupboxes reset fields should be recursive.
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
RecursiveResetForm(control);
}
}
private void RecursiveResetForm(Control control)
{
if (control.HasChildren)
{
foreach (Control subControl in control.Controls)
{
RecursiveResetForm(subControl);
}
}
switch (control.GetType().Name)
{
case "TextBox":
TextBox textBox = (TextBox)control;
textBox.Text = null;
break;
case "ComboBox":
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
break;
case "CheckBox":
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
break;
case "ListBox":
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
break;
case "NumericUpDown":
NumericUpDown numericUpDown = (NumericUpDown)control;
numericUpDown.Value = 0;
break;
}
}
}
I would use the element.addEventListener
method to link it to a function. From that function you can call multiple functions.
The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.
This worked for me: social.msdn.microsoft.com/Forums/en/transactsql/thread/02c6da90-954d-487d-a823-e24b891ec1b0?prof=required
if exists (
select * from tempdb.dbo.sysobjects o
where o.xtype in ('U')
and o.id = object_id(N'tempdb..#tempTable')
)
DROP TABLE #tempTable;
spark-csv is part of core Spark functionality and doesn't require a separate library. So you could just do for example
df = spark.read.format("csv").option("header", "true").load("csvfile.csv")
In scala,(this works for any format-in delimiter mention "," for csv, "\t" for tsv etc)
val df = sqlContext.read.format("com.databricks.spark.csv")
.option("delimiter", ",")
.load("csvfile.csv")
actionbar_background.xml
<item>
<shape>
<solid android:color="@color/black" />
<corners android:radius="2dp" />
<gradient
android:startColor="@color/black"
android:centerColor="@color/black"
android:endColor="@color/white"
android:angle="270" />
</shape>
</item>
<item android:bottom="3dp" >
<shape>
<solid android:color="#ffffff" />
<corners android:radius="1dp" />
</shape>
</item>
</layer-list>
add to actionbar_style background
<style name="Theme.ActionBar" parent="style/Widget.AppCompat.Light.ActionBar.Solid">
<item name="background">@drawable/actionbar_background</item>
<item name="android:elevation">0dp</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:layout_marginBottom">5dp</item>
name="displayOptions">useLogo|showHome|showTitle|showCustom
add to Basetheme
<style name="BaseTheme" parent="Theme.AppCompat.Light">
<item name="android:homeAsUpIndicator">@drawable/home_back</item>
<item name="actionBarStyle">@style/Theme.ActionBar</item>
</style>
It's a syntactically valid request, but not a satisfiable request. If you look further in that section you see:
If a syntactically valid byte-range-set includes at least one byte- range-spec whose first-byte-pos is less than the current length of the entity-body, or at least one suffix-byte-range-spec with a non- zero suffix-length, then the byte-range-set is satisfiable. Otherwise, the byte-range-set is unsatisfiable. If the byte-range-set is unsatisfiable, the server SHOULD return a response with a status of 416 (Requested range not satisfiable). Otherwise, the server SHOULD return a response with a status of 206 (Partial Content) containing the satisfiable ranges of the entity-body.
So I think in your example, the server should return a 416 since it's not a valid byte range for that file.
Open gradle-wrapper.properties
Change the version there on distributionUrl
line
I had a similar problem that I solved by using the following sequence:
use the CELL("filename")
function to get the full path to the current sheet of the current file.
use the SEARCH()
function to find the start of the [FileName]SheetName string of your current excel file and the sheet.
use the LEFT
function to extract the full path name of the directory that contains your current file.
Concatenate the directory path name found in step #3 with the name of the file, the name of the worksheet, and the cell reference that you want to access.
use the INDIRECT()
function to access the CellPathName
that you created in step #4.
Note: these same steps can also be used to access cells in files whose names are created dynamically. In step #4, use a text string that is dynamically created from the contents of cells, the current date or time, etc. etc.
A cell reference example (with each piece assembled separately) that includes all of these steps is:
=INDIRECT("'" & LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "[" & "OtherFileName" & "]" & "OtherSheetName" & "'!" & "$OtherColumn$OtherRow" & "'")
Note that LibreOffice uses a slightly different CellPatnName syntax, as in the following example:
=INDIRECT(LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "OtherFileName" & "'#$" & "OtherSheetName" & "." & "$OtherColumn$OtherRow")
Recently, I've started to get an error:
npm ERR! install Couldn't read dependencies
npm ERR! Error: Invalid version: "1.0"
So, you may need to specify version
of your package with 3 numbers, e.g. 1.0.0
instead of 1.0
if you get similar error.
For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…
The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.
The problem with s += "stuff"
is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff"
is extremely costly.
If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:
StringBuilder sb = new StringBuilder(5000);
for (; ; )
{
sb.Append("stuff");
}
StringBuilder
will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.
The example, I have used today:
import PIL
import numpy
from PIL import Image
def resize_image(numpy_array_image, new_height):
# convert nympy array image to PIL.Image
image = Image.fromarray(numpy.uint8(numpy_array_image))
old_width = float(image.size[0])
old_height = float(image.size[1])
ratio = float( new_height / old_height)
new_width = int(old_width * ratio)
image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
# convert PIL.Image into nympy array back again
return array(image)
it depends on how you trigger the event. the key you are looking is textbox.clientid.
x.aspx code
<script type="text/javascript">
function disable_textbox(tid) {
var mytextbox = document.getElementById(tid);
mytextbox.disabled=false
}
</script>
code behind x.aspx.cs
string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID ");</script>";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);
If you are using Sql Server Management Studio, you can obtain a list of all schemas, create your own schema or remove an existing one by browsing to:
Databases - [Your Database] - Security - Schemas
[
NOTE:
line
someButton.setTitle("New Title", forState: .normal)
works only when Title type is Plain.
Flexbox? You can use flexbox.
.box {_x000D_
display: -ms-flexbox;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
_x000D_
-webkit-justify-content: center;_x000D_
justify-content: center;_x000D_
_x000D_
}_x000D_
_x000D_
.box div {_x000D_
border:1px solid grey;_x000D_
flex: 0 1 auto;_x000D_
align-self: auto;_x000D_
background: grey;_x000D_
}
_x000D_
<div class="box">_x000D_
<div class="A">I'm horizontally centered.</div>_x000D_
</div>
_x000D_
I would like to suggest additional solution to fix this issue. So, I recommend to reinstall/install the latest Windows SDK
. In my case it has helped me to fix the issue when using Qt
with MSVC
compiler to debug a program.
As an alternative to the webservices, you can use the put document call from the FrontPage RPC API. This has the additional benefit of enabling you to provide meta-data (columns) in the same request as the file data. The obvious drawback is that the protocol is a bit more obscure (compared to the very well documented webservices).
For a reference application that explains the use of Frontpage RPC, see the SharePad project on CodePlex.
There are a number of steps you have to go through to create an installer and it varies for each Operating System. For Example:
.pkg
, there are instructions on how to do that here: https://coolaj86.com/articles/how-to-create-an-osx-pkg-installer.html.deb
, there are instruction on how to do that here: https://coolaj86.com/articles/how-to-create-a-debian-installer.html.exe
or .msi
, there are instruction on how do that using the innosetup installer here: https://coolaj86.com/articles/how-to-create-an-innosetup-installer.htmlYou should add namespace if you are not using it:
System.Windows.Forms.MessageBox.Show("Some text", "Some title",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
Alternatively, you can add at the begining of your file:
using System.Windows.Forms
and then use (as stated in previous answers):
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
The performance should be the same; it's much more important to have the correct indexes and clustering applied on your tables (there exist some good resources on that topic).
(Edited to reflect the updated question)
If can't rely on the process name like python scripts which will always have python.exe as process name. If found this method very handy
import psutil
psutil.pid_exists(pid)
check docs for further info http://psutil.readthedocs.io/en/latest/#psutil.pid_exists
using json.loads
will turn your data into a python dictionary.
Dictionaries values are accessed using ['key']
resp_str = {
"name" : "ns1:timeSeriesResponseType",
"declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
"scope" : "javax.xml.bind.JAXBElement$GlobalScope",
"value" : {
"queryInfo" : {
"creationTime" : 1349724919000,
"queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
"criteria" : {
"locationParam" : "[ALL:103232434]",
"variableParam" : "[00060, 00065]"
},
"note" : [ {
"value" : "[ALL:103232434]",
"title" : "filter:sites"
}, {
"value" : "[mode=LATEST, modifiedSince=null]",
"title" : "filter:timeRange"
}, {
"value" : "sdas01",
"title" : "server"
} ]
}
},
"nil" : false,
"globalScope" : true,
"typeSubstituted" : false
}
would translate into a python diction
resp_dict = json.loads(resp_str)
resp_dict['name'] # "ns1:timeSeriesResponseType"
resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
Try this: Set your image crop dimensions and use this line in your CSS:
object-fit: cover;
For those who want isoWeek
to be the default you can modify moment's behaviour as such:
const moment = require('moment');
const proto = Object.getPrototypeOf(moment());
const {startOf, endOf} = proto;
proto.startOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return startOf.call(this, period);
};
proto.endOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return endOf.call(this, period);
};
Now you can simply use someDate.startOf('week')
without worrying you'll get sunday or having to think about whether to use isoweek
or isoWeek
etc.
Plus you can store this in a variable like const period = 'week'
and use it safely in subtract()
or add()
operations, e.g. moment().subtract(1, period).startOf(period);
. This won't work with period being isoWeek
.
You've already discovered the simplest way to specify a shallow clone in Git-SVN, by specifying the SVN revision number that you want to start your clone at ( -r$REV:HEAD
).
For example: git svn clone -s -r1450:HEAD some/svn/repo
Git's data structure is based on pointers in a directed acyclic graph (DAG), which makes it trivial to walk back n
commits. But in SVN ( and therefore in Git-SVN) you will have to find the revision number yourself.
Just a note. If you want to compare a string with ""
,in your case, use
If LEN(str) > 0 Then
or even just
If LEN(str) Then
instead.
I have always used OLEDB
for this, something like...
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
The ACE.OLEDB
provider will read both .xls
and .xlsx
files and I have always found the speed quite good.
I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.
Basically:
In HTML, create container divs to position the table header row and the table body, also create a "mask" div to hide the table body as it scrolls past the header
In CSS, convert the table parts to blocks
In Javascript, get the table width and match the mask's width... get the height of the page content... measure scroll position... manipulate CSS to set the table header row position and the mask height
Here's the javascript and a jsFiddle DEMO.
// get table width and match the mask width
function setMaskWidth() {
if (document.getElementById('mask') !==null) {
var tableWidth = document.getElementById('theTable').offsetWidth;
// match elements to the table width
document.getElementById('mask').style.width = tableWidth + "px";
}
}
function fixTop() {
// get height of page content
function getScrollY() {
var y = 0;
if( typeof ( window.pageYOffset ) == 'number' ) {
y = window.pageYOffset;
} else if ( document.body && ( document.body.scrollTop) ) {
y = document.body.scrollTop;
} else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
y = document.documentElement.scrollTop;
}
return [y];
}
var y = getScrollY();
var y = y[0];
if (document.getElementById('mask') !==null) {
document.getElementById('mask').style.height = y + "px" ;
if (document.all && document.querySelector && !document.addEventListener) {
document.styleSheets[1].rules[0].style.top = y + "px" ;
} else {
document.styleSheets[1].cssRules[0].style.top = y + "px" ;
}
}
}
window.onscroll = function() {
setMaskWidth();
fixTop();
}
Another example:
Dim myPath As String = """" & Path.Combine(part1, part2) & """"
Good luck!
Please try this:
<input class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2" type="text" name="name" value="" placeholder="Your Name" style="background-color:blue;"/>
You basically put all the CSS inside the style part of the input tag and it works.