If the requested resource of the server is using Flask. Install Flask-CORS.
add these tag in your view
app:layout_constraintCircleRadius="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
and you can right click in design mode and choose center.
You can also pass events down into child components with something like this:
<CustomComponent
@keyup.enter="handleKeyUp"
/>
...
<template>
<div>
<input
type="text"
v-on="$listeners"
>
</div>
</template>
<script>
export default {
name: 'CustomComponent',
mounted() {
console.log('listeners', this.$listeners)
},
}
</script>
That works well if you have a pass-through component and want the listeners to go onto a specific element.
Just copy this code to all components that you will drag.
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
example:
<TextView
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:text="To:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="7dp"
tools:layout_editor_absoluteY="4dp"
android:id="@+id/textTo"/>
In Spring 5
@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam MultiValueMap body ) {
// import org.springframework.util.MultiValueMap;
String datax = (String) body .getFirst("datax");
}
You seem to be passing the From
address as emailAddress
, which is not a proper email address. For Office365 the From
needs to be a real address on the Office365 system.
You can validate that if you hardcode your email address as the From
and your Office 365 password.
Don't leave it there though of course.
All of these answers are turned off the logging at creation time.
But what if we need to turn off the logging on runtime ?
By runtime i mean after initializing the sequelize
object using new Sequelize(..
function.
I peeked into the github source, found a way to turn off logging in runtime.
// Somewhere your code, turn off the logging
sequelize.options.logging = false
// Somewhere your code, turn on the logging
sequelize.options.logging = true
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
The answer I have finally found is that the SMTP service on the server is not using the same certificate as https.
The diagnostic steps I had read here make the assumption they use the same certificate and every time I've tried this in the past they have done and the diagnostic steps are exactly what I've done to solve the problem several times.
In this case those steps didn't work because the certificates in use were different, and the possibility of this is something I had never come across.
The solution is either to export the actual certificate from the server and then install it as a trusted certificate on my machine, or to get a different valid/trusted certificate for the SMTP service on the server. That is currently with our IT department who administer the servers to decide which they want to do.
As suggested by Adam Miller in the comments, I'll add another solution.
The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:
MailMessage Msg = new MailMessage(fromMail, addresses);
In this particular case, we can replace the ';' for ',' and still make use of the constructor.
MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));
Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.
dont put break-point before await smtp.SendMailAsync(mail);
:)
when it waits with a break point giving this error when i remove break point it has worked
Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.
Here is the code - The code is in asp.net core 2.0 but should work in above versions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
namespace UnityAssets.Website.Services
{
public class EmailSender : IEmailSender
{
public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
{
var email = new MimeMessage();
email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
email.Subject = subject;
var body = new BodyBuilder
{
HtmlBody = htmlMessage
};
email.Body = body.ToMessageBody();
using (var client = new SmtpClient())
{
//provider specific settings
await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);
await client.SendAsync(email).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
}
}
If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.
I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/
<div ng-app="myApp">
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">
First name: <br/><input type="text" name="form.firstname">
<br/><br/>
Email Address: <br/><input type="text" ng-model="form.emailaddress">
<br/><br/>
<textarea rows="3" cols="25">
Describe your reason for submitting this form ...
</textarea>
<br/>
<input type="radio" ng-model="form.gender" value="female" />Female
<input type="radio" ng-model="form.gender" value="male" />Male
<br/><br/>
<input type="checkbox" ng-model="form.member" value="true"/> Already a member
<input type="checkbox" ng-model="form.member" value="false"/> Not a member
<br/>
<input type="file" ng-model="form.file_profile" id="file_profile">
<br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar">
<br/><br/>
<input type="submit">
</form>
</div>
Here I'm using lots of angular directives(ng-controller
, ng-model
, ng-submit
) where you were using basic html form submission.
Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission
BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.
For general advice on angular form submission see the cookbook examples
UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission
The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.
Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.
In my case, It was returning one output parameter and was not Returning any value.
So changed it to
param.Direction = ParameterDirection.Output;
command.ExecuteScalar();
and then it was throwing size error. so had to set the size as well
SqlParameter param = new SqlParameter("@Name",SqlDbType.NVarChar);
param.Size = 10;
In your github account
Click on the image on the top corner of the page that contains your profile picture ->
Settings ->
In the side menu ->
Developer Settings ->
Personal access Tokens ->
Generate new token.
$ git push
Username: <your username>
Password: <the access token>
Now I do not have to type username and password every time I push changes.
I just type git push
and press Enter, And changes will be pushed.
I have used the steps in this question and it worked for me.
My issue was that G suite didn't consider my password as strong and after changing it it worked perfectly.
SEND Button logic:
string fromaddr = "[email protected]";
string toaddr = TextBox1.Text;//TO ADDRESS HERE
string password = "YOUR PASSWROD";
MailMessage msg = new MailMessage();
msg.Subject = "Username &password";
msg.From = new MailAddress(fromaddr);
msg.Body = "Message BODY";
msg.To.Add(new MailAddress(TextBox1.Text));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
NetworkCredential nc = new NetworkCredential(fromaddr,password);
smtp.Credentials = nc;
smtp.Send(msg);
This code work 100%. If you have antivirus in your system or firewall that restrict sending mails from your system so disable your antivirus and firewall. After this run this code... In this above code TextBox1.Text
control is used for TOaddress
.
Try Html.EditorFor
helper method instead of Html.TextBoxFor
.
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control",@placeholder = "Name" })
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
The API doc for IllegalArgumentException
:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
From looking at how it is used in the JDK libraries, I would say:
It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.
It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).
I would use IllegalArgumentException
to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException
. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.
I am having the same issue, I overcome using
npm config set proxy http://my-proxy.com:1080
npm config set https-proxy http://my-proxy.com:1080
Additionally info at node-doc
Rather than using sub queries in where condition which will increase the query time where records are huge.
I would suggest to use Inner Join as a better option to this problem.
Considering the same table this could give the result
SELECT EmailAddress, CustomerName FROM Customers as a
Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress
For still better results I would suggest you to use CustomerID
or any unique field of your table. Duplication of CustomerName
is possible.
So, my company just switched to Node.js v12.x.
I was using NODE_TLS_REJECT_UNAUTHORIZED
, and it stopped working.
After some digging, I started using NODE_EXTRA_CA_CERTS=A_FILE_IN_OUR_PROJECT
that has a PEM format of our self signed cert and all my scripts are working again.
So, if your project has self signed certs, perhaps this env var will help you.
Ref: https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file
Here's what I ended up using.
I'm very new to AngularJS, so would love to see better / alternative solutions.
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {},
link: function(scope, element, attrs)
{
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.html(htmlText);
}
}
})
Example usage:
<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>
The question specifically states the performance needs to be improved for ad-hoc queries, and that indexes can't be added. So taking that at face value, what can be done to improve performance on any table?
Since we're considering ad-hoc queries, the WHERE clause and the ORDER BY clause can contain any combination of columns. This means that almost regardless of what indexes are placed on the table there will be some queries that require a table scan, as seen above in query plan of a poorly performing query.
Taking this into account, let's assume there are no indexes at all on the table apart from a clustered index on the primary key. Now let's consider what options we have to maximize performance.
Defragment the table
As long as we have a clustered index then we can defragment the table using DBCC INDEXDEFRAG (deprecated) or preferably ALTER INDEX. This will minimize the number of disk reads required to scan the table and will improve speed.
Use the fastest disks possible. You don't say what disks you're using but if you can use SSDs.
Optimize tempdb. Put tempdb on the fastest disks possible, again SSDs. See this SO Article and this RedGate article.
As stated in other answers, using a more selective query will return less data, and should be therefore be faster.
Now let's consider what we can do if we are allowed to add indexes.
If we weren't talking about ad-hoc queries, then we would add indexes specifically for the limited set of queries being run against the table. Since we are discussing ad-hoc queries, what can be done to improve speed most of the time?
Edit
I've run some tests on a 'large' table of 22 million rows. My table only has six columns but does contain 4GB of data. My machine is a respectable desktop with 8Gb RAM and a quad core CPU and has a single Agility 3 SSD.
I removed all indexes apart from the primary key on the Id column.
A similar query to the problem one given in the question takes 5 seconds if SQL server is restarted first and 3 seconds subsequently. The database tuning advisor obviously recommends adding an index to improve this query, with an estimated improvement of > 99%. Adding an index results in a query time of effectively zero.
What's also interesting is that my query plan is identical to yours (with the clustered index scan), but the index scan accounts for 9% of the query cost and the sort the remaining 91%. I can only assume your table contains an enormous amount of data and/or your disks are very slow or located over a very slow network connection.
@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)
IF @AA> 0
BEGIN
SET @UserId = 0
END
ELSE
BEGIN
INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
SELECT SCOPE_IDENTITY()
END
END
SEND TO EMAIL CLIENTS ONLY - WITH MULTIPLE ATTACHMENTS
There are many solutions but all work partially.
mailto properly filters email apps but it has the inability of not sending streams/files.
message/rfc822 opens up hell of apps along with email clients
so, the solution for this is to use both.
private void share()
{
Intent queryIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
Intent dataIntent = getDataIntent();
Intent targetIntent = getSelectiveIntentChooser(context, queryIntent, dataIntent);
startActivityForResult(targetIntent);
}
Build the required data intent which is filled with required data to share
private Intent getDataIntent()
{
Intent dataIntent = buildIntent(Intent.ACTION_SEND, null, "message/rfc822", null);
// Set subject
dataIntent.putExtra(Intent.EXTRA_SUBJECT, title);
//Set receipient list.
dataIntent.putExtra(Intent.EXTRA_EMAIL, toRecipients);
dataIntent.putExtra(Intent.EXTRA_CC, ccRecipients);
dataIntent.putExtra(Intent.EXTRA_BCC, bccRecipients);
if (hasAttachments())
{
ArrayList<Uri> uris = getAttachmentUriList();
if (uris.size() > 1)
{
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
dataIntent.putExtra(Intent.EXTRA_STREAM, uris);
}
else
{
dataIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris.get(0));
}
}
return dataIntent;
}
protected ArrayList<Uri> getAttachmentUriList()
{
ArrayList<Uri> uris = new ArrayList();
for (AttachmentInfo eachAttachment : attachments)
{
uris.add(eachAttachment.uri);
}
return uris;
}
Utitlity class for filtering required intents based on query intent
// Placed in IntentUtil.java
public static Intent getSelectiveIntentChooser(Context context, Intent queryIntent, Intent dataIntent)
{
List<ResolveInfo> appList = context.getPackageManager().queryIntentActivities(queryIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent finalIntent = null;
if (!appList.isEmpty())
{
List<android.content.Intent> targetedIntents = new ArrayList<android.content.Intent>();
for (ResolveInfo resolveInfo : appList)
{
String packageName = resolveInfo.activityInfo != null ? resolveInfo.activityInfo.packageName : null;
Intent allowedIntent = new Intent(dataIntent);
allowedIntent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
allowedIntent.setPackage(packageName);
targetedIntents.add(allowedIntent);
}
if (!targetedIntents.isEmpty())
{
//Share Intent
Intent startIntent = targetedIntents.remove(0);
Intent chooserIntent = android.content.Intent.createChooser(startIntent, "");
chooserIntent.putExtra(android.content.Intent.EXTRA_INITIAL_INTENTS, targetedIntents.toArray(new Parcelable[]{}));
chooserIntent.addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION);
finalIntent = chooserIntent;
}
}
if (finalIntent == null) //As a fallback, we are using the sent data intent
{
finalIntent = dataIntent;
}
return finalIntent;
}
MailAddress fromAddress = new MailAddress (fromMail,fromName);
MailAddress toAddress = new MailAddress(toMail,toName);
MailMessage message = new MailMessage(fromAddress,toAddress);
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient()
{
Host = host, Port = port,
enabHost = "smtp.gmail.com",
Port = 25,
EnableSsl = true,
UseDefaultCredentials = true,
Credentials = new NetworkCredentials (fromMail, password)
};
smtp.send(message);
Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:
;WITH DistinctMails AS
(
SELECT ID, MailID, EMailAddress, NAME,
ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'
FROM dbo.YourMailTable
)
SELECT *
FROM DistinctMails
WHERE RowNum = 1
This works on SQL Server 2005 and newer (you didn't mention what version you're using...)
<FORM Action="mailto:xyz?Subject=Test_Post" METHOD="POST">
mailto: protocol test:
<Br>Subject:
<INPUT name="Subject" value="Test Subject">
<Br>Body: 
<TEXTAREA name="Body">
kfdskfdksfkds
</TEXTAREA>
<BR>
<INPUT type="submit" value="Submit">
</FORM>
Solved the problem by upgrading to JDK 8.
Finally, Works!
Put smtpClient.UseDefaultCredentials = false;
after smtpClient.Credentials = credentials;
then problem resolved!
SmtpClient smtpClient = new SmtpClient(smtpServerName);
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpUName, smtpUNamePwd);
smtpClient.Credentials = credentials;
smtpClient.UseDefaultCredentials = false; <-- Set This Line After Credentials
smtpClient.Send(mailMsg);
smtpClient = null;
mailMsg.Dispose();
On Android 2.2+ use this:
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
for example:
EditText emailid = (EditText) loginView.findViewById(R.id.login_email);
String getEmailId = emailid.getText().toString();
// Check if email id is valid or not
if (!isEmailValid(getEmailId)){
new CustomToast().Show_Toast(getActivity(), loginView,
"Your Email Id is Invalid.");
}
I get the same error in Chrome after pasting code copied from jsfiddle.
If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.
I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:
ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);
LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();
localServer.start();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (X509Certificate cert: chain) {
System.err.println(cert);
}
return false;
}
};
SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
trustStrategy, new AllowAllHostnameVerifier());
Scheme https = new Scheme("https", 443, sslsf);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
InetSocketAddress address = localServer.getServiceAddress();
HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
HttpGet httpget1 = new HttpGet("/random/100");
HttpResponse response1 = httpclient.execute(target1, httpget1);
System.err.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
HttpGet httpget2 = new HttpGet("/");
HttpResponse response2 = httpclient.execute(target2, httpget2);
System.err.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
} finally {
localServer.stop();
}
Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.
Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.
[
[
Version: V1
Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
Key: Sun DSA Public Key
Parameters:DSA
p: fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
q: 9760508f 15230bcc b292b982 a2eb840b f0581cf5
g: f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a
y:
f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e
Validity: [From: Sat Dec 11 14:48:35 CET 2004,
To: Tue Dec 09 14:48:35 CET 2014]
Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
SerialNumber: [ 41bafab3]
]
Algorithm: [SHA1withDSA]
Signature:
0000: 30 2D 02 15 00 85 BE 6B D0 91 EF 34 72 05 FF 1A 0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14 27 02 14 37 8D E8 CB AC .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1 2D 6F 80 5F 58 AE 33 Nl.... .-o._X.3
]
HTTP/1.1 200 OK
[
[
Version: V3
Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 2048 bits
modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
public exponent: 65537
Validity: [From: Wed May 26 02:00:00 CEST 2010,
To: Sat May 26 01:59:59 CEST 2012]
Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
SerialNumber: [ 53d2bef9 24a7245e 83ca01e4 6caa2477]
Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
[accessMethod: 1.3.6.1.5.5.7.48.1
accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]
...
]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...
You are looking for the android:layout_weight
attribute. It will allow you to use percentages to define your layout.
In the following example, the left button uses 70% of the space, and the right button 30%.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:text="left"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".70" />
<Button
android:text="right"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30" />
</LinearLayout>
It works the same with any kind of View, you can replace the buttons with some EditText to fit your needs.
Be sure to set the layout_width
to 0dp
or your views may not be scaled properly.
Note that the weight sum doesn't have to equal 1, I just find it easier to read like this. You can set the first weight to 7 and the second to 3 and it will give the same result.
From a button in view call .click(call some java script). From there call controller method by window.location.href = 'Controller/Method';
In controller either do the database call and get the datatable or call some method get the data from database table to a datatable and then do following,
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport"+DateTime.Now+".csv");
Response.Charset = "";
//Response.ContentType = "application/text";
Response.ContentType = "application/x-msexcel";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
This worked for me,
$recipient_email = '[email protected],[email protected]';
$success = mail($recipient_email, $subject, $body, $headers);
From a Windows Server OS execute the following command for a dump of the entire Active Director:
csvde -f test.csv
This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:
csvde -f test.csv -r objectClass=user
You can further restrict the command to give you only the fields you need relevant to the search requested such as:
csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf
If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.
each
passes into your function index
and element
. Check index
against the length of the set and you're good to go:
var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
thisVal = $(this).val();
if(parseInt(thisVal) !== 0) {
console.log('Valid Field: ' + thisVal);
if (index === (length - 1)) {
console.log('Last field, submit form here');
}
}
});
In EntityFramework Core 2.x there is no need for Attach
:
// get a tracked entity
var entity = context.User.Find(userId);
entity.someProp = someValue;
// other property changes might come here
context.SaveChanges();
Tried this in SQL Server and profiling it:
exec sp_executesql N'SET NOCOUNT ON;
UPDATE [User] SET [someProp] = @p0
WHERE [UserId] = @p1;
SELECT @@ROWCOUNT;
',N'@p1 int,@p0 bit',@p1=1223424,@p0=1
Find ensures that already loaded entities do not trigger a SELECT and also automatically attaches the entity if needed (from the docs):
/// Finds an entity with the given primary key values. If an entity with the given primary key values
/// is being tracked by the context, then it is returned immediately without making a request to the
/// database. Otherwise, a query is made to the database for an entity with the given primary key values
/// and this entity, if found, is attached to the context and returned. If no entity is found, then
/// null is returned.
The server name should be same as the first/last name which you give while create a certificate
The length of a base64 encoded string is always a multiple of 4. If it is not a multiple of 4, then =
characters are appended until it is. A query string of the form ?name=value
has problems when the value
contains =
charaters (some of them will be dropped, I don't recall the exact behavior). You may be able to get away with appending the right number of =
characters before doing the base64 decode.
Edit 1
You may find that the value of UserNameToVerify
has had "+"
's changed to " "
's so you may need to do something like so:
a = a.Replace(" ", "+");
This should get the length right;
int mod4 = a.Length % 4;
if (mod4 > 0 )
{
a += new string('=', 4 - mod4);
}
Of course calling UrlEncode
(as in LukeH's answer) should make this all moot.
Native method:
$("#myform").validate({
// options...
});
$.validator.methods.email = function( value, element ) {
return this.optional( element ) || /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}/.test( value );
}
Source: https://jqueryvalidation.org/jQuery.validator.methods/
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("[email protected]", "gmail_password",
"[email protected]", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->Encoding = "16bit";
Thanks for spotting this I was about to add strings thinking the same as you that they'd get added to end of collection. It appears the params are:
msg.to.Add(<MailAddress>) adds MailAddress to the end of the collection
msg.to.Add(<string>) add a list of emails to the collection
Slightly different actions depending on param type, I think this is pretty bad form i'd have prefered split methods AddStringList of something.
This error can appear when the web server can't access the mail server. Make sure the web server can reach the mail server, for instance pinging it.
While it's possible that this is due to a jar file missing from your classpath, it may not be.
It is important to keep two or three different exceptions strait in our head in this case:
java.lang.ClassNotFoundException
This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError
This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying again, but we're not even going to try to load it, because we failed loading it earlier. The earlier failure could be a ClassNotFoundException
or an ExceptionInInitializerError
(indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError
is not necessarily a classpath problem.
I would look at the source for javax.mail.Authenticator
, and see what it is doing in it's static initializer. (Look at static variable initialization and the static block, if there is one.) If you aren't getting a ClassNotFoundException
prior to the NoClassDefFoundError
, you're almost guaranteed that it's a static initialization problem.
I have seen similar errors quite frequently when the hosts file incorrectly defines the localhost address, and the static initialization block relies on InetAddress.getLocalHost()
. 127.0.0.1 should point to 'localhost' (and probably also localhost.localdomain). It should NOT point to the actual host name of the machine (although for some reason, many older RedHat Linux installers liked to set it incorrectly).
You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx.
It is possible to make implicit connections without having to use the now obsolete System.Web.Mail namespace, but you have to access the Microsoft CDO (Collaborative Data Object). I have supplied an example of how to use the CDO in another discussion (GMail SMTP via C# .Net errors on all ports).
Hope this helps!
Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.
Why?
Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..
Example:
How to use it?
The easiest way is to download and include verimail.jquery.js on your page. After that, hookup Verimail by running the following function on the input-box that needs the validation:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean [email protected]?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.
For a reusable React hook solution
import React, { useEffect } from 'react';
const useEscape = (onEscape) => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27)
onEscape();
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
}
export default useEscape
Usage:
const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false))
Just in case anyone still stumbles upon this old question:
The code was theoretically almost correct in a sense, the problem was the use of $('this') instead of $(this), therefore telling jQuery to look for a tag.
$(document).ready(function(){
$("#frame").click(function () {
$(this).load("http://www.google.com/");
});
});
The script itself woudln't work as it is right now though because the load() function itself is an AJAX function, and google does not seem to specifically allow the use of loading this page with AJAX, but this method should be easy to use in order to load pages from your own domain by using relative paths.
$ pip3 install pypiwin32
Sometimes using pip3
also works if just pip
by itself is not working.
There is one more similarity measure which I once implemented in our system and was giving satisfactory results :-
Use Case
There is a user query which needs to be matched against a set of documents.
Algorithm
For every keyword extracted from user query :-
In essence, if first keyword appears 4 times in the document, the score will be calculated as :-
Total similarity score = 1 + 1/2 + 1/3 + 1/4 = 2.083
Similarly, we calculate it for other keywords in user query.
Finally, the total score will represent the extent of similarity between user query and given document.
A php.ini file is not installed by default with Wordpress. You may have one already installed by your web host. Look in your root directory or ask your web host or read your web host's documentation on how to install one.
Look for max_execution_time
in your php.ini file and change to 60 or 90
Why? One almost never needs to update the statistics. Rebuilding an index is even more rarely needed.
OPTIMIZE TABLE tbl;
will rebuild the indexes and do ANALYZE
; it takes time.
ANALYZE TABLE tbl;
is fast for InnoDB to rebuild the stats. With 5.6.6 it is even less needed.
How to break out in java??
Ans: Best way: System.exit(0);
Java language provides three jump statemnts that allow you to interrupt the normal flow of program.
These include break , continue ,return ,labelled break statement for e.g
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
outerLoop://Label
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break outerLoop;
}
System.out.println();
}
System.out.println();
}
}
}
Output: 1
Now Note below Program:
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break ;
}
}
System.out.println();
}
}
}
output:
1
11
111
1111
and so on upto
1111111111
Similarly you can use continue statement just replace break with continue in above example.
Things to Remember :
A case label cannot contain a runtime expressions involving variable or method calls
outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved
As BalusC indicated, the actionListener
by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.
This happens through a call like this:
context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,
new ExceptionQueuedEventContext(context, exception, source, phaseId)
);
The default listener for this event is the ExceptionHandler
which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl
. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.
This ExceptionHandler
can be replaced however in faces-config.xml with a custom implementation:
<exception-handlerfactory>
com.foo.myExceptionHandler
</exception-handlerfactory>
Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:
@ManagedBean
@RequestScoped
public class MyBean {
public void actionMethod(ActionEvent event) {
FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
throw new RuntimeException(content.getException());
}
@Override
public boolean isListenerForSource(Object source) {
return true;
}
});
throw new RuntimeException("test");
}
}
(note, this is not how one should normally code listeners, this is only for demonstration purposes!)
Calling this from a Facelet like this:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h:form>
<h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
</h:form>
</h:body>
</html>
Will result in an error page being displayed.
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
How about this one-liner?
var isAndroid = /(android)/i.test(navigator.userAgent);
The i
modifier is used to perform case-insensitive matching.
Technique taken from Cordova AdMob test project: https://github.com/floatinghotpot/cordova-admob-pro/wiki/00.-How-To-Use-with-PhoneGap-Build
Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!
Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use
string s = Char.ConvertFromUtf32(56);
which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.
And if you mean select the ID of the last record inserted, its
SELECT @@IDENTITY FROM table
Other solutions may work. This is the 10 pound gorilla approach that has the advantage of being broadly applicable in this and similar cases:
Styles.xml:
<style name="AppTheme.FloatingAccentButtonOverlay" >
<item name="colorAccent">@color/colorFloatingActionBarAccent</item>
</style>
your layout xml:
<android.support.design.widget.FloatingActionButton
android:theme="AppTheme.FloatingAccentButtonOverlay"
...
</android.support.design.widget.FloatingActionButton>
Berkelium is a C++ tool for making chrome embeddable.
AwesomiumDotNet is a wrapper around both Berkelium and Awesomium
BTW, the link here to Awesomium appears to be more current.
If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you
I encountered the same problem when I built an application on a Windows 7 box that had previously been maintained on an XP machine.
The program ran fine when built for Debug, but failed with this error when built for Release. I found the answer on the project's Properties page. Go to the "Build" tab and try changing the Platform Target from "Any CPU" to "x86".
The up-to-date right way to do this asynchronously using ES 2016 standards of async and await (as of Node 7) would be the following:
const crypto = require('crypto');
function generateToken({ stringBase = 'base64', byteLength = 48 } = {}) {
return new Promise((resolve, reject) => {
crypto.randomBytes(byteLength, (err, buffer) => {
if (err) {
reject(err);
} else {
resolve(buffer.toString(stringBase));
}
});
});
}
async function handler(req, res) {
// default token length
const newToken = await generateToken();
console.log('newToken', newToken);
// pass in parameters - adjust byte length
const shortToken = await generateToken({byteLength: 20});
console.log('newToken', shortToken);
}
This works out of the box in Node 7 without any Babel transformations
You could simply make use of application.yml/application.properties only. There is no need to explicitly create any DataSource
Bean
You need to exclude tomcat-jdbc as mentioned by ydemartino
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
As you won't create DataSource
bean, you have to explicitly specify using Hikari through spring.datasource.type
with value com.zaxxer.hikari.HikariDataSource
in application.yml / application.properties
spring:
datasource:
hikari:
connection-test-query: SELECT 1 FROM DUAL
minimum-idle: 1
maximum-pool-size: 5
pool-name: yourPoolName
auto-commit: false
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/myDb
username: login
password: password
type: com.zaxxer.hikari.HikariDataSource
In your application.yml / application.properties, you could configure Hikari specific parameters such as pool size etc in spring.datasource.hikari.*
.Scroll {
height:600px;
overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>
<h1>Smooth Scroll</h1>
<div class="Scroll">
<div class="main" id="section1">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section3">
<h2>Section 3</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section4">
<h2>Section 4</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section5">
<h2>Section 5</h2>
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
<div class="main" id="section6">
<h2>Section 6</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section7">
<h2>Section 7</h2>
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
</div>
</body>
</html>
_x000D_
YES it is almost possible to forced you have to call to methods in the same order and at the same time this ones are:
System.gc ();
System.runFinalization ();
even if is just one object to clean the use of this two methods at the same time force the garbage collector to use the finalise()
method of unreachable object freeing the memory assigned and doing what the finalize()
method states.
HOWEVER it is a terrible practice to use the garbage collector because the use of it could introduce an over load to the software that may be even worst than on the memory, the garbage collector has his own thread which is not possible to control plus depending on the algorithm used by the gc could take more time and is consider very inefficient, you should check your software if it worst with the help of the gc because it is definitely broke, a good solution must not depend on the gc.
NOTE: just to keep on mind this will works only if in the finalize method is not a reassignment of the object, if this happens the object will keep alive an it will have a resurrection which is technically possible.
You're looking for implode()
$string = implode(",", $array);
I use this extension class:
public static class StreamExtensions
{
public static byte[] ReadAllBytes(this Stream instream)
{
if (instream is MemoryStream)
return ((MemoryStream) instream).ToArray();
using (var memoryStream = new MemoryStream())
{
instream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
Just copy the class to your solution and you can use it on every stream:
byte[] bytes = myStream.ReadAllBytes()
Works great for all my streams and saves a lot of code! Of course you can modify this method to use some of the other approaches here to improve performance if needed, but I like to keep it simple.
@media queries serve this purpose. Here's an example:
@media only screen and (max-width: 991px) and (min-width: 769px){
/* CSS that should be displayed if width is equal to or less than 991px and larger
than 768px goes here */
}
@media only screen and (max-width: 991px){
/* CSS that should be displayed if width is equal to or less than 991px goes here */
}
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
here is my solution:
install SDKMan
$ curl -s "https://get.sdkman.io" | bash
setting your bash_profile
$ source "$HOME/.sdkman/bin/sdkman-init.sh
$ source ~/.bash_profile
find java sdk, and select want to install version
$ sdk ls java
$ sdk install java 8.0.192-zulu
copy your flutter doctor warning message to update sdkmanager
$ /Users/YourUserName/Library/Android/sdk/tools/bin/sdkmanager --update
after 1~4, redo it
$ flutter doctor --android-licenses
Given that ECMA is a 'class-free' language, implementing classical composition doesn't - in my eyes - make a lot of sense. The danger is that, in so doing, you are effectively attempting to re-engineer the language (and, if one feels strongly about that, there are excellent holistic solutions such as the aforementioned TypeScript that mitigate reinventing the wheel)
Now that isn't to say that composition is out of the question however in Plain Old JS. I researched this at length some time ago. The strongest candidate I have seen for handling composition within the object prototypal paradigm is stampit, which I now use across a wide range of projects. And, importantly, it adheres to a well articulated specification.
more information on stamps here
Using Spring's UriComponentsBuilder:
UriComponentsBuilder
.fromUriString(url)
.build()
.encode()
.toUri()
Just change your syntax ever so slightly:
CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
ELSE '"DECLINED"'
END
If you don't put the field expression before the CASE
statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.
Front :
<Image Name="camImage"/>
Back:
public async void Base64ToImage(string base64String)
{
// read stream
var bytes = Convert.FromBase64String(base64String);
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
camImage.Source = output;
}
While the accepted answer is good in general I don't think it emphasises that when dealing with Angular Components you almost always want to use an Observable because it supports cancelation. Promises cannot be cancelled and will resolve even if your component is destroyed. Angular tends to be forgiving until it's not.
For example any manual change detection on a destroyed component will cause an exception:
ngOnInit() {
// promise api
this.service.getData().then(d => {
this.data = d;
this.changeDetectorRef.detectChanges();
});
// observable api
this.service.getData().pipe(takeUntil(this.unsubscribe)).subscribe((d) => {
this.data = d;
this.changeDetectorRef.detectChanges();
});
}
If your component is destroyed before the promise is resolved, you'll get an attempt to use destroyed view
error when the promise is resolved.
Alternatively, if you use observables with the takeUntil pattern, then as soon as your component is destroyed the subscription will be cancelled.
This is a bit of a contrived example but executing code for a component that is destroyed is probably going to lead to bugs. Unless you actually want to do that for some reason :p
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
This is a sample spark code which can read the files present on s3
val hadoopConf = sparkContext.hadoopConfiguration
hadoopConf.set("fs.s3.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
hadoopConf.set("fs.s3.awsAccessKeyId", s3Key)
hadoopConf.set("fs.s3.awsSecretAccessKey", s3Secret)
var jobInput = sparkContext.textFile("s3://" + s3_location)
I had a similar problem and I fixed with
$('#CompId').select2({
dropdownParent: $('#AssetsModal')
});
and modal with select
<div class="modal fade" id="AssetsModal" role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true" style="overflow:hidden;" >
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle" >?????? ??????</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form role="form" action="?action=dma_act_documents_assets_insert&Id=<?=$ID?>"
method="post" name="dma_act_documents_assets_insert"
id="dma_act_documents_assets_insert">
<div class="form-group col-sm-12">
<label for="recipient-name" class="col-form-label">?????:</label>
<span style="color: red">*</span>
<select class="form-control js-example-basic-single col-sm-12"
name="CompId" id="CompId">
<option></option>
</select>
</div>
</form>
</div>
</div>
</div>
but I don't know why the select menu is smaller than other fields
and it starting like that when start using select2. When I remove it, all is ok.
Is there some one to share some experince about that.
Thanks.
If the jar's in your classpath, and you know its Main class, you can just invoke the main class. Using DITA-OT as an example:
import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')
Note this will make the subordinate jar share memory space and a classpath with your jar, with all the potential for interference that can cause. If you don't want that stuff polluted, you have other options, as mentioned above - namely:
Runtime.getRuntime.exec(...)
(which wholly isolates the jar, but has the normal "find the application", "escape your strings right", "platform-specific WTF", and "OMG System Threads" pitfalls of running system commands.You can use putAll function for Map as explained in the code below
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
map1.put("a", 1);
map1.put("b", 2);
map1.put("c", 3);
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
map1.put("aa", 11);
map1.put("bb", 12);
HashMap<String, Integer> map3 = new HashMap<String, Integer>();
map3.putAll(map1);
map3.putAll(map2);
map3.keySet().stream().forEach(System.out::println);
map3.values().stream().forEach(System.out::println);
<html>
<head>
<style type="text/css">
#wrapper{ width:100%; float:left; height:auto; border:1px solid #5694cf;}
</style>
</head>
<div id="wrapper">
<object data="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf" width="100%" height="100%">
<p>Your web browser doesn't have a PDF Plugin. Instead you can <a href="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf"> Click
here to download the PDF</a></p>
</object>
</div>
</html>
try the following code:
this.cloneArray= [...this.OriginalArray]
Suppose your dataframe is df and you want to change gender from 2 to 1 in participant id 5 then you should determine the row by writing "==" as you can see
df["rowName", "columnName"] <- value
df[df$serial.id==5, "gender"] <- 1
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
When using the 'mat-form-field' MatInputModule needs to be imported also
import {
MatToolbarModule,
MatButtonModule,
MatSidenavModule,
MatIconModule,
MatListModule ,
MatStepperModule,
MatInputModule
} from '@angular/material';
It became a popular question and I got a notification. I am sorry, I forgot to answer before which I should have done. I solved it long back.
net use \\10.100.110.120\C$ MyPassword /user:domain\username /persistent:Yes
Run it in a batch file and you should get what you are looking for.
In Eclipse go to Project--> click on build automatically after that u try to execute
Please make sure that id datatype is Long instead of String, if that will be string then @GeneratedValue annotation will not work and the sql generating for
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
create table VMS_AUDIT_RECORDS (id **varchar(255)** not null auto_increment primary key (id))
that needs to be
create table VMS_AUDIT_RECORDS (id **bigint** not null auto_increment primary key (id))
To literally fix your example you would use this:
Sub Normalize()
Dim Ticker As Range
Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy
Sheets("Sheet2").Select
Cells(1, 1).PasteSpecial xlPasteAll
End Sub
To Make slight improvments on it would be to get rid of the Select and Activates:
Sub Normalize()
With Sheets("Sheet1")
.Range(.Cells(2, 1), .Cells(65, 1)).Copy Sheets("Sheet2").Cells(1, 1)
End With
End Sub
but using the clipboard takes time and resources so the best way would be to avoid a copy and paste and just set the values equal to what you want.
Sub Normalize()
Dim CopyFrom As Range
Set CopyFrom = Sheets("Sheet1").Range("A2", [A65])
Sheets("Sheet2").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value
End Sub
To define the CopyFrom
you can use anything you want to define the range, You could use Range("A2:A65")
, Range("A2",[A65])
, Range("A2", "A65")
all would be valid entries. also if the A2:A65 Will never change the code could be further simplified to:
Sub Normalize()
Sheets("Sheet2").Range("A1:A65").Value = Sheets("Sheet1").Range("A2:A66").Value
End Sub
I added the Copy from range, and the Resize
property to make it slightly more dynamic in case you had other ranges you wanted to use in the future.
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.
http://opt.sourceforge.net/ Java Micro Benchmark - control tasks required to determine the comparative performance characteristics of the computer system on different platforms. Can be used to guide optimization decisions and to compare different Java implementations.
Instead of using
response.sendRedirect("/demo.jsp");
Which does a permanent redirect to an absolute URL path,
Rather use RequestDispatcher
. Example:
RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);
Generics:
With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T>
class the java compiler generates Byte Code as if it was Foo<Object>
. This means casting and also boxing/unboxing will have to be done in the "background".
I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.
So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.
The Sender
header is used to identify in the message who submitted it. This is usually the same as the From
header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.
The Return-Path
header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.
For example, take a server that allows users to send mail from a web page. So, [email protected]
types in a message and submits it. The server then sends the message to its recipient with From
set to [email protected]
. The actual SMTP submission uses different credentials, something like [email protected]
. So, the sender
header is set to [email protected]
, to indicate the From
header doesn't indicate who actually submitted the message.
In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path
would also be set to [email protected]
so that any delivery reports go to it instead of the sender.
If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.
I think you should store the size somewhere.
The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.
Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.
P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.
a = dict(one=1, two=2, three=3)
Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.
NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.
Here is information about all of the isolation levels at your disposal, as well as table hints.
Before answering, I would like to give you some data from Wiki
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}sSampleStruct;
sizeof(sSampleStruct)
will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:
typedef struct
{
char Data1;
//3-Bytes Added here.
int Data2;
unsigned short Data3;
char Data4;
//1-byte Added here.
}sSampleStruct;
We can use __attribute__((packed, aligned(X)))
to insist particular(X) sized padding. X should be powers of two. Refer here
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}__attribute__((packed, aligned(1))) sSampleStruct;
so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma
#pragma pack(push, 1)
//Structure 1
......
//Structure 2
......
#pragma pack(pop)
Here's a function I wrote that takes Molly's code and some other code I've found on the internet to make slightly fancier grouped boxplots:
import numpy as np
import matplotlib.pyplot as plt
def custom_legend(colors, labels, linestyles=None):
""" Creates a list of matplotlib Patch objects that can be passed to the legend(...) function to create a custom
legend.
:param colors: A list of colors, one for each entry in the legend. You can also include a linestyle, for example: 'k--'
:param labels: A list of labels, one for each entry in the legend.
"""
if linestyles is not None:
assert len(linestyles) == len(colors), "Length of linestyles must match length of colors."
h = list()
for k,(c,l) in enumerate(zip(colors, labels)):
clr = c
ls = 'solid'
if linestyles is not None:
ls = linestyles[k]
patch = patches.Patch(color=clr, label=l, linestyle=ls)
h.append(patch)
return h
def grouped_boxplot(data, group_names=None, subgroup_names=None, ax=None, subgroup_colors=None,
box_width=0.6, box_spacing=1.0):
""" Draws a grouped boxplot. The data should be organized in a hierarchy, where there are multiple
subgroups for each main group.
:param data: A dictionary of length equal to the number of the groups. The key should be the
group name, the value should be a list of arrays. The length of the list should be
equal to the number of subgroups.
:param group_names: (Optional) The group names, should be the same as data.keys(), but can be ordered.
:param subgroup_names: (Optional) Names of the subgroups.
:param subgroup_colors: A list specifying the plot color for each subgroup.
:param ax: (Optional) The axis to plot on.
"""
if group_names is None:
group_names = data.keys()
if ax is None:
ax = plt.gca()
plt.sca(ax)
nsubgroups = np.array([len(v) for v in data.values()])
assert len(np.unique(nsubgroups)) == 1, "Number of subgroups for each property differ!"
nsubgroups = nsubgroups[0]
if subgroup_colors is None:
subgroup_colors = list()
for k in range(nsubgroups):
subgroup_colors.append(np.random.rand(3))
else:
assert len(subgroup_colors) == nsubgroups, "subgroup_colors length must match number of subgroups (%d)" % nsubgroups
def _decorate_box(_bp, _d):
plt.setp(_bp['boxes'], lw=0, color='k')
plt.setp(_bp['whiskers'], lw=3.0, color='k')
# fill in each box with a color
assert len(_bp['boxes']) == nsubgroups
for _k,_box in enumerate(_bp['boxes']):
_boxX = list()
_boxY = list()
for _j in range(5):
_boxX.append(_box.get_xdata()[_j])
_boxY.append(_box.get_ydata()[_j])
_boxCoords = zip(_boxX, _boxY)
_boxPolygon = plt.Polygon(_boxCoords, facecolor=subgroup_colors[_k])
ax.add_patch(_boxPolygon)
# draw a black line for the median
for _k,_med in enumerate(_bp['medians']):
_medianX = list()
_medianY = list()
for _j in range(2):
_medianX.append(_med.get_xdata()[_j])
_medianY.append(_med.get_ydata()[_j])
plt.plot(_medianX, _medianY, 'k', linewidth=3.0)
# draw a black asterisk for the mean
plt.plot([np.mean(_med.get_xdata())], [np.mean(_d[_k])], color='w', marker='*',
markeredgecolor='k', markersize=12)
cpos = 1
label_pos = list()
for k in group_names:
d = data[k]
nsubgroups = len(d)
pos = np.arange(nsubgroups) + cpos
label_pos.append(pos.mean())
bp = plt.boxplot(d, positions=pos, widths=box_width)
_decorate_box(bp, d)
cpos += nsubgroups + box_spacing
plt.xlim(0, cpos-1)
plt.xticks(label_pos, group_names)
if subgroup_names is not None:
leg = custom_legend(subgroup_colors, subgroup_names)
plt.legend(handles=leg)
You can use the function(s) like this:
data = { 'A':[np.random.randn(100), np.random.randn(100) + 5],
'B':[np.random.randn(100)+1, np.random.randn(100) + 9],
'C':[np.random.randn(100)-3, np.random.randn(100) -5]
}
grouped_boxplot(data, group_names=['A', 'B', 'C'], subgroup_names=['Apples', 'Oranges'], subgroup_colors=['#D02D2E', '#D67700'])
plt.show()
From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
My guess is that byteArrayIn
doesn't contain valid image data.
Please give more information though:
byteArrayIn
from, and are you sure it should contain a valid image?If redirecting stdout
works for your problem, Gringo Suave's answer is a good demonstration for how to do it.
To make it even easier, I made a version utilizing contextmanagers for a succinct generalized calling syntax using the with
statement:
from contextlib import contextmanager
import sys
@contextmanager
def redirected_stdout(outstream):
orig_stdout = sys.stdout
try:
sys.stdout = outstream
yield
finally:
sys.stdout = orig_stdout
To use it, you just do the following (derived from Suave's example):
with open('out.txt', 'w') as outfile:
with redirected_stdout(outfile):
for i in range(2):
print('i =', i)
It's useful for selectively redirecting print
when a module uses it in a way you don't like. The only disadvantage (and this is the dealbreaker for many situations) is that it doesn't work if one wants multiple threads with different values of stdout
, but that requires a better, more generalized method: indirect module access. You can see implementations of that in other answers to this question.
<iframe src="URL" frameborder="0" width="100%" height="200">
<p>Your browser does not support iframes.</p>
</iframe>
<iframe frameborder="1|0">
(OR)
<iframe src="URL" width="100%" height="300" style="border: none">Your browser
does not support iframes.</iframe>
The <iframe> frameborder attribute is not supported in HTML5. Use CSS
instead.
As for Apache running on Ubuntu, the solution was to check error log, which showed that the error was related with folder and file permission.
First, check Apache error log
nano /var/log/apache2/error.log
Then set folder permission to be executable
sudo chmod 755 /var/www/html/
Also set file permission to be readable
sudo chmod 644 /var/www/html/.htaccess
You simply need to install Crystal Report Report Run Time downloads on Deployment Server. If problem still appears, then place check asp_client folder in your project main folder.
Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.
An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.
C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.
Like this (for MySQL):
SELECT IFNULL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1
For MSSQL replace IFNULL
with ISNULL
or for Oracle use NVL
Install PAR::Packer from CPAN (it is free) and use pp utility.
Optional
api provides methods for getting the values. You can check isPresent()
for the presence of the value and then make a call to get()
or you can make a call to get()
chained with orElse()
and provide a default value.
The last thing you can try doing is using @Query()
over a custom method.
<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
{
echo('This is mobile device');
}
else
{
echo('This is Desktop/Laptop device');
}
?>
So I never get confused and avoid problems with this solution:
if(str.trim().length() <=0 ) {
// is null !
}
Ex: In web.xml file the tag
<context-param>
<param-name>chatpropertyfile</param-name>
<!-- Name of the chat properties file. It contains the name and description of rooms.-->
<param-value>chat.properties</param-value>
</context-param>
And chat.properties you can declare your properties like this
For Ex :
Jsp = Discussion about JSP can be made here.
Java = Talk about java and related technologies like J2EE.
ASP = Discuss about Active Server Pages related technologies like VBScript and JScript etc.
Web_Designing = Any discussion related to HTML, JavaScript, DHTML etc.
StartUp = Startup chat room. Chatter is added to this after he logs in.
This is the most elegant solution I've been using for a while. It doesn't require external counter variable and it provides nice degree of encapsulation.
var urls = ['http://..', 'http://..', ..];
function ajaxRequest (urls) {
if (urls.length > 0) {
$.ajax({
method: 'GET',
url: urls.pop()
})
.done(function (result)) {
ajaxRequest(urls);
});
}
}
ajaxRequest(urls);
$source = "number35"
$number=$null
$result = foreach ($_ in $source.ToCharArray()){$digit="0123456789".IndexOf($\_,0);if($digit -ne -1){$number +=$\_}}[int32]$number
Just feed it digits and it wil convert to an Int32
Blocking call: Control returns only when the call completes.
Non blocking call: Control returns immediately. Later OS somehow notifies the process that the call is complete.
Synchronous program: A program which uses Blocking calls. In order not to freeze during the call it must have 2 or more threads (that's why it's called Synchronous - threads are running synchronously).
Asynchronous program: A program which uses Non blocking calls. It can have only 1 thread and still remain interactive.
There are three states of button
button
button:hover
button:active
Normal:
.button
{
//your css
}
Active
.button:active
{
//your css
}
Hover
.button:hover
{
//your css
}
SNIPPET:
Use :active
to style the active state of button.
button:active{_x000D_
background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
Based on Abraham Mayowa Oluwasina answer provided above is the correct one. MacOS Catalina, .bash_profile is no longer apple's default shell and it won't persist your path variables instead use .zprofile instead.
In root directory,
touch .zprofile
open -e .zprofile
Add the following in file,
export ANDROID_HOME=/Users/<username>/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/platform-tools
Save and exit
To activate
source ~/. zprofile
echo $ANDROID_HOME
I would try to avoid inserting empty lists in the first place, but, would generally use:
d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty
If prior to 2.7:
d = dict( (k, v) for k,v in d.iteritems() if v )
or just:
empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
del[k]
By using getText():
Button mButton;
EditText mEdit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.edittext);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
}
It should be mentioned that the Accept
header tells the server something about what we are accepting back, whereas the relevant header in this context is Content-Type
It's often advisable to specify Content-Type
as application/json
when sending JSON. For curl the syntax is:
-H 'Content-Type: application/json'
So the complete curl command will be:
curl -H 'Content-Type: application/json' -H 'Accept: application/json' -X PUT -d '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' http://example.com/service`
Using negate
from purrr
also does the trick quickly and neatly:
`%not_in%` <- purrr::negate(`%in%`)
Then usage is, for example,
c("cat", "dog") %not_in% c("dog", "mouse")
If you're making a dictionary only to make a list of tuples, as creating dicts like you are may be a pain, you might look into using zip()
Its especialy useful if you've got one heading, and multiple rows. For instance if I assume that you want Olympics stats for countries:
headers = ['Capital', 'Food', 'Year']
countries = [
['London', 'Fish & Chips', '2012'],
['Beijing', 'Noodles', '2008'],
]
for olympics in countries:
print zip(headers, olympics)
gives
[('Capital', 'London'), ('Food', 'Fish & Chips'), ('Year', '2012')]
[('Capital', 'Beijing'), ('Food', 'Noodles'), ('Year', '2008')]
Don't know if thats the end goal, and my be off topic, but it could be something to keep in mind.
Maybe a bit late, but: instead of this:
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
Log.i( "dbg","onNewIntent");
if(extras != null){
Log.i( "dbg", "Extra6 bool: "+ extras.containsKey("net.dbg.android.fjol"));
Log.i( "dbg", "Extra6 val : "+ extras.getString("net.dbg.android.fjol"));
}
mTabsController.setActiveTab(TabsController.TAB_DOWNLOADS);
}
Use this:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("keyName");
}
You can use the "Company Search" operation in the Company Fundamentals API here: http://www.mergent.com/servius/
Indexes of two types can be added: when you define a primary key, MySQL will take it as index by default.
Explanation
Primary key as index
Consider you have a tbl_student
table and you want student_id
as primary key:
ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)
Above statement adds a primary key, which means that indexed values must be unique and cannot be NULL.
Specify index name
ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)
Above statement will create an ordinary index with student_index
name.
Create unique index
ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)
Here, student_unique_index
is the index name assigned to student_id and creates an index for which values must be unique (here null can be accepted).
Fulltext option
ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)
Above statement will create the Fulltext index name with student_fulltext_index
, for which you need MyISAM Mysql Engine.
How to remove indexes ?
DROP INDEX `student_index` ON `tbl_student`
How to check available indexes?
SHOW INDEX FROM `tbl_student`
The heading looks bold because of its large size, if you have applied bold or want to change behaviour, you can do:
h1 { font-weight:normal; }
Use can use in global
Context context;
and create a constructor and passing the context. LoginClass is name of the class
LoginClass(Context context)
{this.context=context;}
and also when we call the class then use getApplicationContext
like
LoginClass lclass = new LoginClass(getApplicationContext)
thats it.
I've come up with a new solution, which has a tiny bit of overhead, but seems to be working so far as a prototype. One assumption is that you're in an honour system environment for logging in, although this could be adapted by rerequesting a password whenever you switch tabs.
Use localStorage (or equivalent) and the HTML5 storage event to detect when a new browser tab has switched which user is active. When that happens, create a ghost overlay with a message saying you can't use the current window (or otherwise disable the window temporarily, you might not want it to be this conspicuous.) When the window regains focus, send an AJAX request logging the user back in.
One caveat to this approach: you can't have any normal AJAX calls (i.e., ones that depend on your session) happen in a window that doesn't have the focus (e.g. if you had a call happening after a delay), unless you manually make an AJAX re-login call before that. So really all you need do is have your AJAX function check first to make sure localStorage.currently_logged_in_user_id === window.yourAppNameSpace.user_id, and if not, log in first via AJAX.
Another is race conditions: if you can switch windows fast enough to confuse it, you may end up with a relogin1->relogin2->ajax1->ajax2 sequence, with ajax1 being made under the wrong session. Work around this by pushing login AJAX requests onto an array, and then onstorage and before issuing a new login request, abort all current requests.
The last gotcha to look out for is window refreshes. If someone refreshes the window while you've got an AJAX login request active but not completed, it'll be refreshed in the name of the wrong person. In this case you can use the nonstandard beforeunload event to warn the user about the potential mixup and ask them to click Cancel, meanwhile reissuing an AJAX login request. Then the only way they can botch it is by clicking OK before the request completes (or by accidentally hitting enter/spacebar, because OK is--unfortunately for this case--the default.) There are other ways to handle this case, like detecting F5 and Ctrl+R/Alt+R presses, which will work in most cases but could be thwarted by user keyboard shortcut reconfiguration or alternative OS use. However, this is a bit of an edge case in reality, and the worst case scenarios are never that bad: in an honour system configuration, you'd be logged in as the wrong person (but you can make it obvious that this is the case by personalizing pages with colours, styles, prominently displayed names, etc.); in a password configuration, the onus is on the last person who entered their password to have logged out or shared their session, or if this person is actually the current user, then there's no breach.
But in the end you have a one-user-per-tab application that (hopefully) just acts as it should, without having to necessarily set up profiles, use IE, or rewrite URLs. Make sure you make it obvious in each tab who is logged into that particular tab, though...
Since you've got both the shell that you're typing into and the shell that sudo -s
runs, you need to quote or escape twice. (EDITED fixed quoting)
sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'
or
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)
Out of curiosity, why do you need -s? Can't you just do this:
sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
What about position: relative
for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.
Here are my solutions with word boundary.
let s = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
let s_split = s.split(/\s+/);
let word_count = 0;
let result = "";
//1
for(let i = 0; word_count < 100; i++){
word_count += s_split[i].length+1;
result += (s_split[i] + " ");
}
console.log(result);
// 2
word_count = 0;
result = s_split.reduce((x,y)=>{
word_count+=(y.length+1);
if(word_count>=100) return x;
else return x+" "+y;}, "").substring(1);
console.log(result);
_x000D_
Also note that the SPOOL
output is driven by a few SQLPlus settings:
SET LINESIZE nn
- maximum line width; if the output is longer it will wrap to display the contents of each result row.
SET TRIMSPOOL OFF|ON
- if set OFF
(the default), every output line will be padded to LINESIZE
. If set ON
, every output line will be trimmed.
SET PAGESIZE nn
- number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.
Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.
SET sql_mode = 'NO_ZERO_DATE';
UPDATE `news` SET `d_stop`='2038-01-01 00:00:00' WHERE `d_stop`='0000-00-00 00:00:00'
You can't download the file directly via ajax.
You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe
and set the URL of the source of that iframe
dynamically. This way you can download the file without refreshing the page.
Here is the code
$.ajax({
url : "yourURL.php",
type : "GET",
success : function(data) {
$("#iframeID").attr('src', 'downloadFileURL');
}
});
JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
JSONObject secObject = (JSONObject) jsonChildArray.get(1);
I think this should work, but i do not have the possibility to test it at the moment..
I've used this successfully inside R script:
library("reshape2",lib.loc="/path/to/R-packages/")
useful if for whatever reason libraries are in more than one place.
U can Install package intl_phone_number_input
dependencies:
intl_phone_number_input: ^0.5.2+2
and try this code:
import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var darkTheme = ThemeData.dark().copyWith(primaryColor: Colors.blue);
return MaterialApp(
title: 'Demo',
themeMode: ThemeMode.dark,
darkTheme: darkTheme,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(title: Text('Demo')),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final TextEditingController controller = TextEditingController();
String initialCountry = 'NG';
PhoneNumber number = PhoneNumber(isoCode: 'NG');
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InternationalPhoneNumberInput(
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
onInputValidated: (bool value) {
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
backgroundColor: Colors.black,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle: TextStyle(color: Colors.black),
initialValue: number,
textFieldController: controller,
inputBorder: OutlineInputBorder(),
),
RaisedButton(
onPressed: () {
formKey.currentState.validate();
},
child: Text('Validate'),
),
RaisedButton(
onPressed: () {
getPhoneNumber('+15417543010');
},
child: Text('Update'),
),
],
),
),
);
}
void getPhoneNumber(String phoneNumber) async {
PhoneNumber number =
await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber, 'US');
setState(() {
this.number = number;
});
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
}
You can use both with relatively few issues. Twitter Bootstrap uses jQuery 1.7.1 (as of this writing), and I can't think of any reasons why you cannot integrate additional Jquery UI components into your HTML templates.
I've been using a combination of HTML5 Boilerplate & Twitter Bootstrap built at Initializr.com. This combines two awesome starter templates into one great starter project. Check out the details at http://html5boilerplate.com/ and http://www.initializr.com/ Or to get started right away, go to http://www.initializr.com/, click the "Bootstrap 2" button, and click "Download It". This will give you all the js and css you need to get started.
And don't be scared off by HTML5 and CSS3. Initializr and HTML5 Boilerplate include polyfills and IE specific code that will allow all features to work in IE 6, 7 8, and 9.
The use of LESS in Twitter Bootstrap is also optional. They use LESS to compile all the CSS that is used by Bootstrap, but if you just want to override or add your own styles, they provide an empty css file for that purpose.
There is also a blank js file (script.js) for you to add custom code. This is where you would add your handlers or selectors for additional jQueryUI components.
I was surprised in not seeing pyconcrete in any answer. Maybe because it's newer than the question?
It could be exactly what you need(ed).
Instead of obfuscating the code, it encrypts it and decrypts at load time.
From pypi page:
Protect python script work flow
- your_script.py
import pyconcrete
- pyconcrete will hook import module
- when your script do import
MODULE
, pyconcrete import hook will try to findMODULE.pye
first and then decryptMODULE.pye
via_pyconcrete.pyd
and execute decrypted data (as .pyc content)- encrypt & decrypt secret key record in
_pyconcrete.pyd
(like DLL or SO) the secret key would be hide in binary code, can’t see it directly in HEX view
You can also set the default time zone in your code by using following code.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
To Yours
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Sofia"));
Here's an example using a for
loop that iterates the list and increments or revalidates the iterator in the event of an item being removed during traversal of the list.
for(auto i = items.begin(); i != items.end();)
{
if(bool isActive = (*i)->update())
{
other_code_involving(*i);
++i;
}
else
{
i = items.erase(i);
}
}
items.remove_if(CheckItemNotActive);
Just something to watch out for......
In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below
USE [MyDatabase]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
END
GO
USE [MyDatabase]
GO
ALTER TABLE [Patient].[Detail] ADD CONSTRAINT [DEF_Detail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]
GO
Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).
The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.
To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.
(SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')
You are sending a POST AJAX request so use $albumname = $_POST['album'];
on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];
. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false
setting.
Starting from Scala 3, there is now enum keyword which can represent a set of constants (and other use cases)
enum Color:
case Red, Green, Blue
scala> val red = Color.Red
val red: Color = Red
scala> red.ordinal
val res0: Int = 0
I got it working from one I made.
<?php
$dest = imagecreatefrompng('vinyl.png');
$src = imagecreatefromjpeg('cover2.jpg');
imagealphablending($dest, false);
imagesavealpha($dest, true);
imagecopymerge($dest, $src, 10, 9, 0, 0, 181, 180, 100); //have to play with these numbers for it to work for you, etc.
header('Content-Type: image/png');
imagepng($dest);
imagedestroy($dest);
imagedestroy($src);
?>
The reason that you can't return NULL here is because you've declared your return type as Attr&
. The trailing &
makes the return value a "reference", which is basically a guaranteed-not-to-be-null pointer to an existing object. If you want to be able to return null, change Attr&
to Attr*
.
In my case, I was simply writing the fetch request URL wrong. On serverless.yml
, you set cors
to true
:
register-downloadable-client:
handler: fetch-downloadable-client-data/register.register
events:
- http:
path: register-downloadable-client
method: post
integration: lambda
cors: true
stage: ${self:custom.stage}
and then on the lambda handler you send the headers, but if you make the fetch request wrong on the frontend, you're not going to get that header on the response and you're going to get this error. So, double check your request URL on the front.
Here is how you can retrieve your user id from a username:
$url = "https://api.instagram.com/v1/users/search?q=[username]&access_token=[your_token]";
$obj = json_decode(@file_get_contents($url));
echo $obj->data[0]->id;
I recommend dynamically adding the elements, and if using jQuery or other JavaScript library, it is quite simple:
also look at prepend
and append
. Otherwise if you have an image tag like that, and you want to make it validate, then you might consider using a dummy image, such as a 1px transparent gif or png.
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
The problem here is much more complex than removing the container padding since the grid structure relies on this padding when applying negative margins for the enclosed rows.
Removing the container padding in this case will cause an x-axis overflow caused by all the rows inside of this container class, this is one of the most stupid things about the Bootstrap Grid.
Logically it should be approached by
.container
class for anything other than rows.container
class that has no padding for use with non-grid html.container
padding on mobile you can manually remove it with media queries then overflow-x: hidden;
which is not very reliable but works in most cases.If you are using LESS
the end result will look like this
@media (max-width: @screen-md-max) {
.container{
padding: 0;
overflow-x: hidden;
}
}
Change the media query to whatever size you want to target.
Final thoughts, I would highly recommend using the Foundation Framework
Grid as its way more advanced
you can use this:
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(String.valueOf(yourChar)))
note that you do not need to create a separate String with the letters A-Z.
Here is a working example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class j4496359 {
public static void main(String[] args) {
try {
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
Date result = df.parse(target);
System.out.println(result);
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
Will print:
Thu Sep 28 13:29:30 CEST 2000
Events are pretty easy in C#, but the MSDN docs in my opinion make them pretty confusing. Normally, most documentation you see discusses making a class inherit from the EventArgs
base class and there's a reason for that. However, it's not the simplest way to make events, and for someone wanting something quick and easy, and in a time crunch, using the Action
type is your ticket.
1. Create your event on your class right after your class
declaration.
public event Action<string,string,string,string>MyEvent;
2. Create your event handler class method in your class.
private void MyEventHandler(string s1,string s2,string s3,string s4)
{
Console.WriteLine("{0} {1} {2} {3}",s1,s2,s3,s4);
}
3. Now when your class is invoked, tell it to connect the event to your new event handler. The reason the +=
operator is used is because you are appending your particular event handler to the event. You can actually do this with multiple separate event handlers, and when an event is raised, each event handler will operate in the sequence in which you added them.
class Example
{
public Example() // I'm a C# style class constructor
{
MyEvent += new Action<string,string,string,string>(MyEventHandler);
}
}
4. Now, when you're ready, trigger (aka raise) the event somewhere in your class code like so:
MyEvent("wow","this","is","cool");
The end result when you run this is that the console will emit "wow this is cool". And if you changed "cool" with a date or a sequence, and ran this event trigger multiple times, you'd see the result come out in a FIFO sequence like events should normally operate.
In this example, I passed 4 strings. But you could change those to any kind of acceptable type, or used more or less types, or even remove the <...>
out and pass nothing to your event handler.
And, again, if you had multiple custom event handlers, and subscribed them all to your event with the +=
operator, then your event trigger would have called them all in sequence.
But what if you want to identify the caller to this event in your event handler? This is useful if you want an event handler that reacts with conditions based on who's raised/triggered the event. There are a few ways to do this. Below are examples that are shown in order by how fast they operate:
Option 1. (Fastest) If you already know it, then pass the name as a literal string to the event handler when you trigger it.
Option 2. (Somewhat Fast) Add this into your class and call it from the calling method, and then pass that string to the event handler when you trigger it:
private static string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string s = null) => s;
Option 3. (Least Fast But Still Fast) In your event handler when you trigger it, get the calling method name string with this:
string callingMethod = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().ReflectedType.Name.Split('<', '>')[1];
You may have a scenario where your custom event has multiple event handlers, but you want to remove one special one out of the list of event handlers. To do so, use the -=
operator like so:
MyEvent -= MyEventHandler;
A word of minor caution with this, however. If you do this and that event no longer has any event handlers, and you trigger that event again, it will throw an exception. (Exceptions, of course, you can trap with try/catch blocks.)
Okay, let's say you're through with events and you don't want to process any more. Just set it to null like so:
MyEvent = null;
The same caution for Unsubscribing events is here, as well. If your custom event handler no longer has any events, and you trigger it again, your program will throw an exception.
Assuming that Test is a class with a defined constructor, there's no difference. The latter form makes it a little clearer that Test's constructor is running, but that's about it.
You can try this method:
Get the total number of records in the collection with
db.dbcollection.count()
Then use skip:
db.dbcollection.find().skip(db.dbcollection.count() - 1).pretty()
You need to use a date formatting function for example to_char http://www.postgresql.org/docs/current/static/functions-formatting.html
GitHub now has an import option that lets you choose whatever you want your new imported repository public or private
The simplest way to put an image into a button:
<button onclick="myFunction()"><img src="your image name here.png"></button>
This will automatically resize the button to the size of the image.
Alternatively, you can use enumerate
. It gives you the column number and the column values as well.
for num, column in enumerate(array.T):
some_function(column) # column: Gives you the column value as asked in the question
some_function(num) # num: Gives you the column number
We can install any PHP7 Extensions which we are needed at the time of install Magento just use related command which you get error at the time of installin Magento
sudo apt-get install php7.0-curl
sudo apt-get install php7.0-dom
sudo apt-get install php7.0-mcrypt
sudo apt-get install php7.0-simplexml
sudo apt-get install php7.0-spl
sudo apt-get install php7.0-xsl
sudo apt-get install php7.0-intl
sudo apt-get install php7.0-mbstring
sudo apt-get install php7.0-ctype
sudo apt-get install php7.0-hash
sudo apt-get install php7.0-openssl
sudo apt-get install php7.0-zip
sudo apt-get install php7.0-xmlwriter
sudo apt-get install php7.0-gd
sudo apt-get install php7.0-iconv
Thanks! Hope this will help you
Google Apps KitKat for Genymotion.
Download the Google Apps ZIP file from the link which contain the essential Google Apps such as Play Store, Gmail, YouTube, etc.
https://www.mediafire.com/?qbbt4lhyu9q10ix
After finishing booting, drag and drop the ZIP file we downloaded named update-gapps-4-4-2-signed.zip to the Genymotion Window. It starts installing the Google Apps, and it asks for your confirmation. Confirm it.
OFFSET is what you are looking for.
SELECT * FROM table LIMIT 10 OFFSET 10
phpMyAdmin provides a GUI for this within the structure view of a table. Check to select the column you want to move and click the change action at the bottom of the column list. You can then change all of the column properties and you'll find the 'move column' function at the far right of the screen.
Of course this is all just building the queries in the perfectly good top answer but GUI fans might appreciate the alternative.
my phpMyAdmin version is 4.1.7
this code worked for me..
//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
For this to work, you must have the following permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Use array or common container for objects only if they have default and copy constructors.
Store pointers otherwise (or smart pointers, but may meet some issues in this case).
PS: Always define own default and copy constructors otherwise auto-generated will be used
If you know you want to convert from List<T1>
to List<T2>
then List<T>.ConvertAll
will be slightly more efficient than Select
/ToList
because it knows the exact size to start with:
target = orig.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });
In the more general case when you only know about the source as an IEnumerable<T>
, using Select
/ToList
is the way to go. You could also argue that in a world with LINQ, it's more idiomatic to start with... but it's worth at least being aware of the ConvertAll
option.
.loader{_x000D_
position: fixed;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
z-index: 9999;_x000D_
background: url('//upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Phi_fenomeni.gif/50px-Phi_fenomeni.gif') _x000D_
50% 50% no-repeat rgb(249,249,249);_x000D_
}
_x000D_
<div class="loader"></div>
_x000D_
\i /path/to/yourfile.sql
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
I do not believe there is a way to do this strictly with CSS. The reason is your "important" qualifier to the question: forcing the parent element to expand with the contents of its child.
My guess is that you will have to use some bits of JavaScript to find the height of the child, and make adjustments.
So, with this HTML:
<div class="parentElement">
<div class="childElement">
...Some Contents...
</div>
</div>
This CSS:
.parentElement { position:relative; width:960px; } .childElement { position:absolute; top:50%; left:50%; }
This jQuery might be useful:
$('.childElement').each(function(){
// determine the real dimensions of the element: http://api.jquery.com/outerWidth/
var x = $(this).outerWidth();
var y = $(this).outerHeight();
// adjust parent dimensions to fit child
if($(this).parent().height() < y) {
$(this).parent().css({height: y + 'px'});
}
// offset the child element using negative margins to "center" in both axes
$(this).css({marginTop: 0-(y/2)+'px', marginLeft: 0-(x/2)+'px'});
});
Remember to load the jQ properly, either in the body below the affected elements, or in the head inside of $(document).ready(...)
.
for me I was still getting
'adb' is not recognized as an internal or external command,
operable program or batch file.
even after setting the path in environment variables...... restarting Android Studio solved the problem.
Simply put the following one. This works for me.
$('.className').datepicker('setDate', 'now');
I followed the answers by @wize and @mdelolmo and I got the solution. Thanks Tons. But, I tuned these solutions a little bit to improve the memory consumption.
Problems I observed:
They save the instance of Fragment
which is replaced. In my case, it is a Fragment which holds MapView
and I thought its costly. So, I am maintaining the FragmentPagerPositionChanged (POSITION_NONE or POSITION_UNCHANGED)
instead of Fragment
itself.
Here is my implementation.
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
private SwitchFragListener mSwitchFragListener;
private Switch mToggle;
private int pagerAdapterPosChanged = POSITION_UNCHANGED;
private static final int TOGGLE_ENABLE_POS = 2;
public DemoCollectionPagerAdapter(FragmentManager fm, Switch toggle) {
super(fm);
mToggle = toggle;
mSwitchFragListener = new SwitchFragListener();
mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSwitchFragListener.onSwitchToNextFragment();
}
});
}
@Override
public Fragment getItem(int i) {
switch (i)
{
case TOGGLE_ENABLE_POS:
if(mToggle.isChecked())
{
return TabReplaceFragment.getInstance();
}else
{
return DemoTab2Fragment.getInstance(i);
}
default:
return DemoTabFragment.getInstance(i);
}
}
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
return "Tab " + (position + 1);
}
@Override
public int getItemPosition(Object object) {
// This check make sures getItem() is called only for the required Fragment
if (object instanceof TabReplaceFragment
|| object instanceof DemoTab2Fragment)
return pagerAdapterPosChanged;
return POSITION_UNCHANGED;
}
/**
* Switch fragments Interface implementation
*/
private final class SwitchFragListener implements
SwitchFragInterface {
SwitchFragListener() {}
public void onSwitchToNextFragment() {
pagerAdapterPosChanged = POSITION_NONE;
notifyDataSetChanged();
}
}
/**
* Interface to switch frags
*/
private interface SwitchFragInterface{
void onSwitchToNextFragment();
}
}
Demo link here.. https://youtu.be/l_62uhKkLyM
For demo purpose, used 2 fragments TabReplaceFragment
and DemoTab2Fragment
at position two. In all the other cases I'm using DemoTabFragment
instances.
Explanation:
I'm passing Switch
from Activity to the DemoCollectionPagerAdapter
. Based on the state of this switch we will display correct fragment. When the switch check is changed, I'm calling the SwitchFragListener
's onSwitchToNextFragment
method, where I'm changing the value of pagerAdapterPosChanged
variable to POSITION_NONE
. Check out more about POSITION_NONE. This will invalidate the getItem and I have logics to instantiate the right fragment over there. Sorry, if the explanation is a bit messy.
Once again big thanks to @wize and @mdelolmo for the original idea.
Hope this is helpful. :)
Let me know if this implementation has any flaws. That will be greatly helpful for my project.
Please provide the exact image name(including the extension) as specified in the images folder. A mismatch can trigger this exception.
Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.
It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.
With perl, as my example, I'd be able to do something like:
@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );
The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)
import sys
sys.stderr.write()
Is my choice, just more readable and saying exactly what you intend to do and portable across versions.
Edit: being 'pythonic' is a third thought to me over readability and performance... with these two things in mind, with python 80% of your code will be pythonic. list comprehension being the 'big thing' that isn't used as often (readability).
To scroll data in text view you can use this to your text view. and add and for anything other layout you can just add scroll view on layout as people are saying above.
/** android:scrollable=true at textview in xml layout.
TextView txtScroll = (TextView) findViewById(R.id.txt1);
txtScroll.setMovementMethod(new ScrollingMovementMethod());
*//
You may be able to use absolute positioning.
The container box should be set to position: relative
.
The top-right text should be set to position: absolute; top: 0; right: 0
.
The bottom-right text should be set to position: absolute; bottom: 0; right: 0
.
You'll need to experiment with padding
to stop the main contents of the box from running underneath the absolute positioned elements, as they exist outside the normal flow of the text contents.
May be useful:
The code that calls the Trigger should go after the event is called.
For example, I have some code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
$(function() {
$("#expense_tickets").change(function() {
// code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
});
// now we trigger the change event
$("#expense_tickets").trigger("change");
})
ADD go /usr/local/
will copy the contents of your local go
directory in the /usr/local/
directory of your docker image.
To copy the go
directory itself in /usr/local/
use:
ADD go /usr/local/go
or
COPY go /usr/local/go
Try this simple select:
select *
from artists
where name like "a%"
In addition to the border-image
property, there are a few other ways to create a dashed border with control over the length of the stroke and the distance between them. They are described below:
We can create the dashed border by using a path
or a polygon
element and setting the stroke-dasharray
property. The property takes two parameters where one defines the size of the dash and the other determines the space between them.
Pros:
border-radius
involved. We would just have replace the path
with a circle
like in this answer (or) convert the path
into a circle.Cons:
vector-effect='non-scaling-stroke'
(as in the second box) but the browser support for this property is nil in IE..dashed-vector {_x000D_
position: relative;_x000D_
height: 100px;_x000D_
width: 300px;_x000D_
}_x000D_
svg {_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
path{_x000D_
fill: none;_x000D_
stroke: blue;_x000D_
stroke-width: 5;_x000D_
stroke-dasharray: 10, 10;_x000D_
}_x000D_
span {_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
_x000D_
/* just for demo */_x000D_
_x000D_
div{_x000D_
margin-bottom: 10px;_x000D_
transition: all 1s;_x000D_
}_x000D_
div:hover{_x000D_
height: 100px;_x000D_
width: 400px;_x000D_
}
_x000D_
<div class='dashed-vector'>_x000D_
<svg viewBox='0 0 300 100' preserveAspectRatio='none'>_x000D_
<path d='M0,0 300,0 300,100 0,100z' />_x000D_
</svg>_x000D_
<span>Some content</span>_x000D_
</div>_x000D_
_x000D_
<div class='dashed-vector'>_x000D_
<svg viewBox='0 0 300 100' preserveAspectRatio='none'>_x000D_
<path d='M0,0 300,0 300,100 0,100z' vector-effect='non-scaling-stroke'/>_x000D_
</svg>_x000D_
<span>Some content</span>_x000D_
</div>
_x000D_
We can use multiple linear-gradient
background images and position them appropriately to create a dashed border effect. This can also be done with a repeating-linear-gradient
but there is not much improvement because of using a repeating gradient as we need each gradient to repeat in only one direction.
.dashed-gradient{_x000D_
height: 100px;_x000D_
width: 200px;_x000D_
padding: 10px;_x000D_
background-image: linear-gradient(to right, blue 50%, transparent 50%), linear-gradient(to right, blue 50%, transparent 50%), linear-gradient(to bottom, blue 50%, transparent 50%), linear-gradient(to bottom, blue 50%, transparent 50%);_x000D_
background-position: left top, left bottom, left top, right top;_x000D_
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;_x000D_
background-size: 20px 3px, 20px 3px, 3px 20px, 3px 20px;_x000D_
}_x000D_
_x000D_
.dashed-repeating-gradient {_x000D_
height: 100px;_x000D_
width: 200px;_x000D_
padding: 10px;_x000D_
background-image: repeating-linear-gradient(to right, blue 0%, blue 50%, transparent 50%, transparent 100%), repeating-linear-gradient(to right, blue 0%, blue 50%, transparent 50%, transparent 100%), repeating-linear-gradient(to bottom, blue 0%, blue 50%, transparent 50%, transparent 100%), repeating-linear-gradient(to bottom, blue 0%, blue 50%, transparent 50%, transparent 100%);_x000D_
background-position: left top, left bottom, left top, right top;_x000D_
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;_x000D_
background-size: 20px 3px, 20px 3px, 3px 20px, 3px 20px;_x000D_
}_x000D_
_x000D_
/* just for demo */_x000D_
_x000D_
div {_x000D_
margin: 10px;_x000D_
transition: all 1s;_x000D_
}_x000D_
div:hover {_x000D_
height: 150px;_x000D_
width: 300px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>_x000D_
<div class='dashed-gradient'>Some content</div>_x000D_
<div class='dashed-repeating-gradient'>Some content</div>
_x000D_
Pros:
Cons:
border-radius
is involved because backgrounds don't curve based on border-radius
. They get clipped instead.We can create a small bar (in the shape of the dash) using pseudo-elements and then create multiple box-shadow
versions of it to create a border like in the below snippet.
If the dash is a square shape then a single pseudo-element would be enough but if it is a rectangle, we would need one pseudo-element for the top + bottom borders and another for left + right borders. This is because the height and width for the dash on the top border will be different from that on the left.
Pros:
Cons:
border-radius
but positioning them would be very tricky with having to find points on a circle (and possibly even transform
)..dashed-box-shadow{_x000D_
position: relative;_x000D_
height: 120px;_x000D_
width: 120px;_x000D_
padding: 10px;_x000D_
}_x000D_
.dashed-box-shadow:before{ /* for border top and bottom */_x000D_
position: absolute;_x000D_
content: '';_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
height: 3px; /* height of the border top and bottom */_x000D_
width: 10px; /* width of the border top and bottom */_x000D_
background: blue; /* border color */_x000D_
box-shadow: 20px 0px 0px blue, 40px 0px 0px blue, 60px 0px 0px blue, 80px 0px 0px blue, 100px 0px 0px blue, /* top border */_x000D_
0px 110px 0px blue, 20px 110px 0px blue, 40px 110px 0px blue, 60px 110px 0px blue, 80px 110px 0px blue, 100px 110px 0px blue; /* bottom border */_x000D_
}_x000D_
.dashed-box-shadow:after{ /* for border left and right */_x000D_
position: absolute;_x000D_
content: '';_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
height: 10px; /* height of the border left and right */_x000D_
width: 3px; /* width of the border left and right */_x000D_
background: blue; /* border color */_x000D_
box-shadow: 0px 20px 0px blue, 0px 40px 0px blue, 0px 60px 0px blue, 0px 80px 0px blue, 0px 100px 0px blue, /* left border */_x000D_
110px 0px 0px blue, 110px 20px 0px blue, 110px 40px 0px blue, 110px 60px 0px blue, 110px 80px 0px blue, 110px 100px 0px blue; /* right border */_x000D_
}
_x000D_
<div class='dashed-box-shadow'>Some content</div>
_x000D_
If you are using PostgreSQL, this is the right way to get it. This is just an assumption where as you have a book table TITLE and PRICE column with populated data. Here's the query
SELECT xpath('/bookstore/book/title/@lang', xmlforest(book.title AS title, book.price AS price), ARRAY[ARRAY[]::TEXT[]]) FROM book LIMIT 1;
Use this statement to convert Month numeric value to Month name.
SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE()))
It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
Here's a link describing this:
I use Iesi.Collections http://www.codeproject.com/KB/recipes/sets.aspx
It's used in lot of OSS projects, I first came across it in NHibernate
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the Day Number ");
int day = int.Parse(Console.ReadLine());
Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}
}
}
@Amjad, good idea, but a better implementation would be:
Date.prototype.setUTCTime = function(UTCTimestamp) {
var UTCDate = new Date(UTCTimestamp);
this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
return this.getTime();
}
You can also search for the file. Navigate to your project directory with PowerShell and run Get-FileMissingRoot:
function Get-FileMissingRoot {
dir -recurse |
where {
($_ -is [IO.FileInfo]) -and
(@(".xml", ".config") -contains $_.extension)
} |
foreach {
$xml = New-Object Xml.XmlDocument;
$filename = $_.FullName
try {
$xml.Load($filename)
}
catch {
write ("File: " + $filename)
write ($_.Exception.Message)
}
}
}
I like simbu's approach, but I ain't comfortable to use first-child or last-child. Instead I only modify the content of a repeating list-comma class.
.list-comma + .list-comma::before {
content: ', ';
}
<span class="list-comma" ng-repeat="destination in destinations">
{{destination.name}}
</span>
Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error()
and curl_errno()
will contain further information in case of failure:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
/* Process $content here */
// Close curl handle
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
* The curl_init()
manual states:
Returns a cURL handle on success, FALSE on errors.
I've observed the function to return FALSE
when you're using its $url
parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE
. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.
The original perceived problem was that the code would not survive a screen orientation change. Apparently this was "solved" by having the program handle the screen orientation change itself, instead of letting the UI framework do it (via calling onDestroy)).
I would submit that if the underlying problem is that the program will not survive onDestroy(), then the accepted solution is just a workaround that leaves the program with serious other problems and vulnerabilities. Remember that the Android framework specifically states that your activity is at risk for being destroyed almost at any time due to circumstances outside your control. Therefore, your activity must be able to survive onDestroy() and subsequent onCreate() for any reason, not just a screen orientation change.
If you are going to accept handling screen orientation changes yourself to solve the OP's problem, you need to verify that other causes of onDestroy() do not result in the same error. Are you able to do this? If not, I would question whether the "accepted" answer is really a very good one.
It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:
boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0
What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)
$(document).ready(function() {
var count = $("h1").text().length;
alert(count);
});
Also, you can put your own element id or class instead of "h1" and length event count your characters of text area string ?
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
alert()
doesn't support HTML, but you have some alternatives to format your message.
You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:
...
.catch(function (error) {
const alertMessage = `Error retrieving resource. Please make sure:
• the resource server is accessible
• you're logged in
Error: ${error}`;
window.alert(alertMessage);
}
As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.
A one liner but without String.format
for all RGB colors:
Color your_color = new Color(128,128,128);
String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);
You can add a .toUpperCase()
if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.
When you have ARGB colors you can use:
Color your_color = new Color(128,128,128,128);
String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);
A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format()
:
You are doing it right, so I guess something else is at fault (not export-ing COLUMNS ?).
A trick to debug these cases is to make a specialized command (a closure for programming language guys). Create a shell script named diff-columns doing:
exec /usr/bin/diff -x -y -w -p -W "$COLUMNS" "$@"
and just use
svn diff "$@" --diff-cmd diff-columns
This way your code is cleaner to read and more modular (top-down approach), and you can test the diff-columns code thouroughly separately (bottom-up approach).
Moonrise is the best dark theme I have ever seen for Eclipse!
Just follow the steps on the website and Enjoy!
npm install
,if the issue is not yet fixed try the following one after the other.npm cache clean
,thennpm install -g npm
,then
npm install
,Finallyng serve --o
to run the project.
Hope this will help....You can also check with composer:
composer show laravel/framework
may be:
UIImage *img = [[UIImage alloc] init];
and when you want to change the image:
img = [UIImage imageNamed:@"nameOfPng.png"];
but the object wasn't in the same place in the memory, but if you use the pointer, the same pointer will be point to the last image loaded.
%s is the representation of an array of char
char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map
character = 'a'; // assign 'a' to character
printf("character %c ",a); //we will display 'a' to stout
so string is an array of char we can assign multiple character per space of memory
string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends
this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined
toy can also assign values to the array of chars assigning it with functions like strcpy;
strcpy(string,"hello" );
this do the same as the example and automatically add the (char) 0 at the end
so if you print it with %S printf("my string %s",string);
and how string is a array we can just display part of it
// the array one char
printf("first letter of wrd %s is :%c ",string,string[1] );
As of python 3.5+:
@functools.wraps(f)
def g():
pass
Is an alias for g = functools.update_wrapper(g, f)
. It does exactly three things:
__module__
, __name__
, __qualname__
, __doc__
, and __annotations__
attributes of f
on g
. This default list is in WRAPPER_ASSIGNMENTS
, you can see it in the functools source.__dict__
of g
with all elements from f.__dict__
. (see WRAPPER_UPDATES
in the source)__wrapped__=f
attribute on g
The consequence is that g
appears as having the same name, docstring, module name, and signature than f
. The only problem is that concerning the signature this is not actually true: it is just that inspect.signature
follows wrapper chains by default. You can check it by using inspect.signature(g, follow_wrapped=False)
as explained in the doc. This has annoying consequences:
Signature.bind()
.Now there is a bit of confusion between functools.wraps
and decorators, because a very frequent use case for developing decorators is to wrap functions. But both are completely independent concepts. If you're interested in understanding the difference, I implemented helper libraries for both: decopatch to write decorators easily, and makefun to provide a signature-preserving replacement for @wraps
. Note that makefun
relies on the same proven trick than the famous decorator
library.
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
boolean entered = false, last;
while (( entered |= last = ( condition ) )) {
// Do while
} if ( !entered ) {
// Else
}
You'r welcome.
Assuming your WebSocket server is listening on the same port as from which the page is being requested, I would suggest:
function createWebSocket(path) {
var protocolPrefix = (window.location.protocol === 'https:') ? 'wss:' : 'ws:';
return new WebSocket(protocolPrefix + '//' + location.host + path);
}
Then, for your case, call it as follows:
var socket = createWebSocket(location.pathname + '/to/ws');
We can use
Model::whereNotNull('sent_at');
Or
Model::whereRaw('sent_at is not null');
Put this line into your vimrc
:
set nobk nowb noswf noudf
"
nobackup
nowritebackup
noswapfile
noundofile
In windows that would be the:
C:\Program Files (x86)\vim\_vimrc
file for system-wide vim configuration for all users.
Setting the last one noundofile
is important in Windows to prevent the creation of *~
tilda files after editing.
I wish Vim had that line included by default. Nobody likes ugly directories.
Let the user choose if and how she wants to enable advanced backup/undo file features first.
This is the most annoying part of Vim.
The next step might be setting up:
set noeb vb t_vb=
"
errorbells
visualbell
to disable beeping in vim as well :-)
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
The text from the Tortoise reference:
Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.
If you want to undo an earlier change permanently, use Revert to this revision instead.
Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.
If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.
What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.
If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.
If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.
Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)
var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
// do something
}
Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.
I solved the same error, by adding "zizaco/entrust": "*"
instead of the "zizaco/entrust": "~1.2"
.
Use substring and concatenate:
if(str.length() > 50)
strOut = str.substring(0,7) + "...";
slice()
works like substring()
with a few different behaviors.
Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
What they have in common:
start
equals stop
: returns an empty stringstop
is omitted: extracts characters to the end of the stringDistinctions of substring()
:
start > stop
, then substring
will swap those 2 arguments.NaN
, it is treated as if it were 0
.Distinctions of slice()
:
start > stop
, slice()
will return the empty string. (""
)start
is negative: sets char from the end of string, exactly like substr()
in Firefox. This behavior is observed in both Firefox and IE.stop
is negative: sets stop to: string.length – Math.abs(stop)
(original value), except bounded at 0 (thus, Math.max(0, string.length + stop)
) as covered in the ECMA specification.Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
i use this
<style>
html, body{height:100%;margin:0;padding:0 0}
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
When I was beginning I needed to watch a demo.
/
You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.
You want the output to print the given statement if and only if the number falls between 10,000 and 30,000.
Code should be;
if number >= 10000 and number <= 30000:
print("you have to pay 5% taxes")
Functionally the same as rinku's answer but with IDE warning prevention
numericOnly(event): boolean {
// noinspection JSDeprecatedSymbols
const charCode = (event.which) ? event.which : event.key || event.keyCode; // keyCode is deprecated but needed for some browsers
return !(charCode === 101 || charCode === 69 || charCode === 45 || charCode === 43);
}
Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:
mvn help:evaluate -Dexpression=project.version -q -DforceStdout
Usage example:
VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar
It can be done with simple Makefile:
sleep%:
sleep $(subst sleep,,$@)
@echo $@ done.
Use -j
option.
$ make -j sleep3 sleep2 sleep1
sleep 3
sleep 2
sleep 1
sleep1 done.
sleep2 done.
sleep3 done.
Without -j
option it executes in serial.
$ make -j sleep3 sleep2 sleep1
sleep 3
sleep3 done.
sleep 2
sleep2 done.
sleep 1
sleep1 done.
You can also do dry run with `-n' option.
$ make -j -n sleep3 sleep2 sleep1
sleep 3
sleep 2
sleep 1
It says “Android library projects cannot be launched” because Android library projects cannot be launched. That simple. You cannot run a library. If you want to test a library, create an Android project that uses the library, and execute it.
When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error.
Example: Takes no arguments:
def dog
end
Takes arguments:
def cat(name)
end
When you call these, you need to call them with the arguments you defined.
dog #works fine
cat("Fluffy") #works fine
dog("Fido") #Returns ArgumentError (1 for 0)
cat #Returns ArgumentError (0 for 1)
Check out the Ruby Koans to learn all this.
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter | openSession | getCurrentSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session creation | Always open new session | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close | Need to explicity flush and close session objects | No need to flush and close sessions , since it is automatically taken by hibernate internally. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance | In single threaded environment , it is slower than getCurrentSession | In single threaded environment , it is faster than openSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration | No need to configure any property to call this method | Need to configure additional property: |
| | | <property name=""hibernate.current_session_context_class"">thread</property> |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
If you have this problem here's a python script to change all the columns of your mysql database automatically.
#! /usr/bin/env python
import MySQLdb
host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"
db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
cursor.execute(sql)
db.close()
Its probably also worth mentioning that you can do the following:
Right click the table you want to duplicate > Script Table As > Create To > New Query Editor Window
Then, where is says the name of the table you just right clicked in the script that has been generated, change the name to what ever you want your new table to be called and click Execute
In case of await Promise.all([task1(), task2()]); "task1()" and "task2()" will run parallel and will wait until both promises are completed (either resolved or rejected). Whereas in case of
const result1 = await t1;
const result2 = await t2;
t2 will only run after t1 has finished execution (has been resolved or rejected). Both t1 and t2 will not run parallel.
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
you can simply do this..
<img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
I typically just add something to the control flow, i.e.:
it('should navigate to the logfile page when attempting ' +
'to access the user login page, after logging in', function() {
userLoginPage.login(true);
userLoginPage.get();
logfilePage.expectLogfilePage();
});
logfilePage:
function login() {
element(by.buttonText('Login')).click();
// Adding this to the control flow will ensure the resulting page is loaded before moving on
browser.getLocationAbsUrl();
}
To access data from Intent you should know two things.
There are different methods in Intent class to extract different kind of data types. It looks like this
getIntent().XXXX(KEY) or intent.XXX(KEY);
So if you know the datatype of your varibale which you set in otherActivity you can use the respective method.
String profileName = getIntent().getStringExtra("SomeKey");
You can see the list of available methods in Official Documentation of Intent.
If you want to call it more like Math.Max, you can do something like this very short expression body:
public static DateTime Max(params DateTime[] dates) => dates.Max();
[...]
var lastUpdatedTime = DateMath.Max(feedItemDateTime, assemblyUpdatedDateTime);
code () {
if [[ $# = 0 ]]
then
open -a "Visual Studio Code"
else
echo "Opening: "$@
"/Applications/Visual Studio Code.app/Contents/MacOS/Electron" $@
fi
}
I put that into my .bash_profile
I tested it and it works.