Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
Did you try vertical-align: middle ???
You can find more info on vertical-align here: http://www.w3schools.com/css/pr_pos_vertical-align.asp
You can also use T-Regx library which has automatic delimiters for you:
$matches = pattern("My name is '(.*)' and im fine")->match($string1)->all();
// ? No delimiters needed
You also can try out this
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
There is an option IdentityFile
which you can use in your ~/.ssh/config
file and specify key file for each host.
Host host_with_key1.net
IdentityFile ~/.ssh/id_rsa
Host host_with_key2.net
IdentityFile ~/.ssh/id_rsa_test
More info: http://linux.die.net/man/5/ssh_config
Also look at http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/
Try the maven-exec-plugin. From there:
mvn exec:java -Dexec.mainClass="com.example.Main"
This will run your class in the JVM. You can use -Dexec.args="arg0 arg1"
to pass arguments.
If you're on Windows, apply quotes for
exec.mainClass
andexec.args
:mvn exec:java -D"exec.mainClass"="com.example.Main"
If you're doing this regularly, you can add the parameters into the pom.xml as well:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Main</mainClass>
<arguments>
<argument>foo</argument>
<argument>bar</argument>
</arguments>
</configuration>
</plugin>
csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.
Zip archives are actually more a 'filesystem' with content metadata etc. See help(unzip)
for details. So to do what you sketch out above you need to
tempfile()
)download.file()
to fetch the file into the temp. fileunz()
to extract the target file from temp. fileunlink()
which in code (thanks for basic example, but this is simpler) looks like
temp <- tempfile()
download.file("http://www.newcl.org/data/zipfiles/a1.zip",temp)
data <- read.table(unz(temp, "a1.dat"))
unlink(temp)
Compressed (.z
) or gzipped (.gz
) or bzip2ed (.bz2
) files are just the file and those you can read directly from a connection. So get the data provider to use that instead :)
To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.
Sub test_date_or_String()
Set c = ActiveCell
c.NumberFormat = "@"
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
c.NumberFormat = "m/d/yyyy"
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date
End Sub
Assuming their updates are on master, and you are on the branch you want to merge the changes into.
git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master
Also note that you will then want to push the merge back to your copy of the repository:
git push origin master
You're most likely using this on a local file over the file://
URI scheme, which cannot have cookies set. Put it on a local server so you can use http://localhost
.
There's an easier way to think about this. Start with 1 bit. This can obviously represent 2 values (0 or 1). What happens when we add a bit? We can now represent twice as many values: the values we could represent before with a 0 appended and the values we could represent before with a 1 appended.
So the the number of values we can represent with n bits is just 2^n (2 to the power n)
Install ncftpput and ncftpget. They're usually part of the same package.
In cpp, you need to pay special attention to string types when using execvp
:
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
string arg;
cin >> arg;
if (arg.empty()) {
argv[arg_i] = nullptr;
break;
} else {
argv[arg_i] = strdup(arg.c_str());
}
++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
// Print error if command not found
cerr << "command '" << command << "' not found\n";
}
Reference: execlp?execvp?????
you can follow BaseAdapter
and create your custome Xml
file and bind it with you BaseAdpter
and populate it with Listview
see here need to change xml
file as Require.
I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.
$("#Friends").animate( {top:
"-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );
With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.
SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch
AND t1.transID = t2.transID
AND ValueDate > @startMonthDate HAVING money > 0;
I am not sure if this applies to your situation, but I will post what worked for me.
I change my table view based on queries / searches to a database. For example, a database table contains Patient data. My initial table view in my program contains all Patients. I can then search query for Patients by firstName and lastName. I use the results of this query to repopulate my Observable list. Then I reset the items in the tableview by calling tableview.setItems(observableList):
/**
* Searches the table for an existing Patient.
*/
@FXML
public void handleSearch() {
String fname = this.fNameSearch.getText();
String lname = this.lNameSearch.getText();
LocalDate bdate = this.bDateSearch.getValue();
if (this.nameAndDOBSearch(fname, lname, bdate)) {
this.patientData = this.controller.processNursePatientSearch(fname, lname, bdate);
} else if (this.birthDateSearch(fname, lname, bdate)) {
this.patientData = this.controller.processNursePatientSearch(bdate);
} else if (this.nameSearch(fname, lname, bdate)) {
this.patientData = this.controller.processNursePatientSearch(fname, lname);
}
this.patientTable.setItems(this.patientData);
}
The if blocks update the ObservableList with the query results.
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'
Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.
The $.fn.equals(...)
solution is probably the cleanest and most elegant one.
I have tried something quick and dirty like this:
JSON.stringify(a) == JSON.stringify(b)
It is probably expensive, but the comfortable thing is that it is implicitly recursive, while the elegant solution is not.
Just my 2 cents.
here how I use it; This button inside my CameraActionActivity Activity class where I call camera
btn_frag_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intenImatToSec = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intenImatToSec, REQUEST_CODE_VIDEO);
//intenImatToSec.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//intenImatToSec.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
//Toast.makeText(getActivity(), "Hello From Camera", Toast.LENGTH_SHORT).show();
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_IMG) {
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
Intent intentBitMap = new Intent(getActivity(), DisplayImage.class);
// aldigimiz imagi burda yonlendirdigimiz sinifa iletiyoruz
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
intentBitMap.putExtra("byteArray", _bs.toByteArray());
startActivity(intentBitMap);
} else if (requestCode == REQUEST_CODE_VIDEO) {
Uri videoUrl = data.getData();
Intent intenToDisplayVideo = new Intent(getActivity(), DisplayVideo.class);
intenToDisplayVideo.putExtra("videoUri", videoUrl.toString());
startActivity(intenToDisplayVideo);
}
}
}
And my other DisplayVideo Activity Class
VideoView videoView = (VideoView) findViewById(R.id.videoview_display_video_actvity);
Bundle extras = getIntent().getExtras();
Uri myUri= Uri.parse(extras.getString("videoUri"));
videoView.setVideoURI(myUri);
I compared some of the methods suggested here in Firefox for speed.
The string I used contained the following characters: œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=
All results are averages of 3 runs each. Times are in milliseconds. Note that all URIEncoding methods behaved similarly and had extreme results, so I only included one.
While there are some fluctuations based on the size of the string, the charCode methods (lovasoa and fuweichin) both perform similarly and the fastest overall, with fuweichin's charCode method the fastest. The Blob and TextEncoder methods performed similarly to each other. Generally the charCode methods were about 75% faster than the Blob and TextEncoder methods. The URIEncoding method was basically unacceptable.
Here are the results I got:
Size 6.4 * 10^6 bytes:
Lauri Oherd – URIEncoding: 6400000 et: 796
lovasoa – charCode: 6400000 et: 15
fuweichin – charCode2: 6400000 et: 16
simap – Blob: 6400000 et: 26
Riccardo Galli – TextEncoder: 6400000 et: 23
Size 19.2 * 10^6 bytes: Blob does kind of a weird thing here.
Lauri Oherd – URIEncoding: 19200000 et: 2322
lovasoa – charCode: 19200000 et: 42
fuweichin – charCode2: 19200000 et: 45
simap – Blob: 19200000 et: 169
Riccardo Galli – TextEncoder: 19200000 et: 70
Size 64 * 10^6 bytes:
Lauri Oherd – URIEncoding: 64000000 et: 12565
lovasoa – charCode: 64000000 et: 138
fuweichin – charCode2: 64000000 et: 133
simap – Blob: 64000000 et: 231
Riccardo Galli – TextEncoder: 64000000 et: 211
Size 192 * 10^6 bytes: URIEncoding methods freezes browser at this point.
lovasoa – charCode: 192000000 et: 754
fuweichin – charCode2: 192000000 et: 480
simap – Blob: 192000000 et: 701
Riccardo Galli – TextEncoder: 192000000 et: 654
Size 640 * 10^6 bytes:
lovasoa – charCode: 640000000 et: 2417
fuweichin – charCode2: 640000000 et: 1602
simap – Blob: 640000000 et: 2492
Riccardo Galli – TextEncoder: 640000000 et: 2338
Size 1280 * 10^6 bytes: Blob & TextEncoder methods are starting to hit the wall here.
lovasoa – charCode: 1280000000 et: 4780
fuweichin – charCode2: 1280000000 et: 3177
simap – Blob: 1280000000 et: 6588
Riccardo Galli – TextEncoder: 1280000000 et: 5074
Size 1920 * 10^6 bytes:
lovasoa – charCode: 1920000000 et: 7465
fuweichin – charCode2: 1920000000 et: 4968
JavaScript error: file:///Users/xxx/Desktop/test.html, line 74: NS_ERROR_OUT_OF_MEMORY:
Here is the code:
function byteLengthURIEncoding(str) {
return encodeURI(str).split(/%..|./).length - 1;
}
function byteLengthCharCode(str) {
// returns the byte length of an utf8 string
var s = str.length;
for (var i=str.length-1; i>=0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) s++;
else if (code > 0x7ff && code <= 0xffff) s+=2;
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
}
return s;
}
function byteLengthCharCode2(s){
//assuming the String is UCS-2(aka UTF-16) encoded
var n=0;
for(var i=0,l=s.length; i<l; i++){
var hi=s.charCodeAt(i);
if(hi<0x0080){ //[0x0000, 0x007F]
n+=1;
}else if(hi<0x0800){ //[0x0080, 0x07FF]
n+=2;
}else if(hi<0xD800){ //[0x0800, 0xD7FF]
n+=3;
}else if(hi<0xDC00){ //[0xD800, 0xDBFF]
var lo=s.charCodeAt(++i);
if(i<l&&lo>=0xDC00&&lo<=0xDFFF){ //followed by [0xDC00, 0xDFFF]
n+=4;
}else{
throw new Error("UCS-2 String malformed");
}
}else if(hi<0xE000){ //[0xDC00, 0xDFFF]
throw new Error("UCS-2 String malformed");
}else{ //[0xE000, 0xFFFF]
n+=3;
}
}
return n;
}
function byteLengthBlob(str) {
return new Blob([str]).size;
}
function byteLengthTE(str) {
return (new TextEncoder().encode(str)).length;
}
var sample = "œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=i";
var string = "";
// Adjust multiplier to change length of string.
let mult = 1000000;
for (var i = 0; i < mult; i++) {
string += sample;
}
let t0;
try {
t0 = Date.now();
console.log("Lauri Oherd – URIEncoding: " + byteLengthURIEncoding(string) + " et: " + (Date.now() - t0));
} catch(e) {}
t0 = Date.now();
console.log("lovasoa – charCode: " + byteLengthCharCode(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("fuweichin – charCode2: " + byteLengthCharCode2(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("simap – Blob: " + byteLengthBlob(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("Riccardo Galli – TextEncoder: " + byteLengthTE(string) + " et: " + (Date.now() - t0));
This answer, just as that of @Vroomfondel aims to circumvent the loop problem in an elegant way.
My take is to let make
generate the loop itself as an imported makefile like this:
include Loop.mk
Loop.mk:Loop.sh
Loop.sh > $@
The shell script can the be as advanced as you like but a minimal working example could be
#!/bin/bash
LoopTargets=""
NoTargest=5
for Target in `seq $NoTargest` ; do
File="target_${Target}.dat"
echo $File:data_script.sh
echo $'\t'./data_script.ss $Target
LoopTargets="$LoopTargets $File"
done
echo;echo;echo LoopTargets:=$LoopTargets
which generates the file
target_1.dat:data_script.sh
./data_script.ss 1
target_2.dat:data_script.sh
./data_script.ss 2
target_3.dat:data_script.sh
./data_script.ss 3
target_4.dat:data_script.sh
./data_script.ss 4
target_5.dat:data_script.sh
./data_script.ss 5
LoopTargets:= target_1.dat target_2.dat target_3.dat target_4.dat target_5.dat
And advantage there is that make
can itself keep track of which files have been generated and which ones need to be (re)generated. As such, this also enables make
to use the -j
flag for parallelization.
You should add that you have to add an extra ' to escape an exising ' in SQL Server:
smith's -> smith''s
Besides all above solutions, check if you have the "id
" or any custom defined parameter in the DELETE
method is matching the route config.
public void Delete(int id)
{
//some code here
}
If you hit with repeated 405 errors better reset the method signature to default as above and try.
The route config by default will look for id
in the URL. So the parameter name id
is important here unless you change the route config under the App_Start
folder.
You may change the data type of the id
though.
For example the method below should work just fine:
public void Delete(string id)
{
//some code here
}
Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.
DELETE http://{url}/{action}/{id}
Example:
DELETE http://localhost/item/1
Hope it helps.
Here's the version I use:
#ifdef NDEBUG
#define Dprintf(FORMAT, ...) ((void)0)
#define Dputs(MSG) ((void)0)
#else
#define Dprintf(FORMAT, ...) \
fprintf(stderr, "%s() in %s, line %i: " FORMAT "\n", \
__func__, __FILE__, __LINE__, __VA_ARGS__)
#define Dputs(MSG) Dprintf("%s", MSG)
#endif
If you want to add a xx.tar.gz to a /usr/local
in container, unzip it, and then remove the useless compressed package.
For COPY:
COPY resources/jdk-7u79-linux-x64.tar.gz /tmp/
RUN tar -zxvf /tmp/jdk-7u79-linux-x64.tar.gz -C /usr/local
RUN rm /tmp/jdk-7u79-linux-x64.tar.gz
For ADD:
ADD resources/jdk-7u79-linux-x64.tar.gz /usr/local/
ADD supports local-only tar extraction. Besides it, COPY will use three layers, but ADD only uses one layer.
if we are talking about validations also why we have not checked for null string entries. Any specific reasons?
I think below way help since IsNullOrEmpty is a system defined method and ternary operators have cyclomatic complexity = 1 while if() {} else {} has value 2.
public static string Truncate(string input, int truncLength)
{
return (!String.IsNullOrEmpty(input) && input.Length >= truncLength)
? input.Substring(0, truncLength)
: input;
}
I had a similar problem. As you increase the line-height the space above the text increases. It's not padding but it will affect the vertical space between content. I found that adding a -ve top margin seemed to do the trick. It had to be done for all of the different instances of line-height and it varies with font-family too. Maybe this is something which designers need to be more aware of when passing design requirements (?) So for a particular instance of font-family and line-height:
h1 {
font-family: 'Garamond Premier Pro Regular';
font-size: 24px;
color: #001230;
line-height: 29px;
margin-top: -5px; /* CORRECTION FOR LINE-HEIGHT */
}
Please don't forget to initialize your buffers to something before utilizing them. And just as important, give your string buffers space for the ending null
TCHAR path[MAX_PATH+1] = L"";
DWORD len = GetCurrentDirectory(MAX_PATH, path);
Now, I can't use DateTime?
, I am using DBNull.Value
for all data types. It works great.
eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
? DBNull.Value
: DateTime.Parse(dateTimeEnd);
string textboxID;
string da;
textboxID = "ctl00$MainContent$grd$ctl" + (grd.Columns.Count + j).ToString() + "$txtDyna" + (k).ToString();
textboxID= ctl00$MainContent$grd$ctl12$ctl00;
da = Request.Form(textboxID);
isn't the code:
var text = $('#listItem').clone().children().remove().end().text();
just becoming jQuery for jQuery's sake? When simple operations involve that many chained commands & that much (unnecessary) processing, perhaps it is time to write a jQuery extension:
(function ($) {
function elementText(el, separator) {
var textContents = [];
for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
if (chld.nodeType == 3) {
textContents.push(chld.nodeValue);
}
}
return textContents.join(separator);
}
$.fn.textNotChild = function(elementSeparator, nodeSeparator) {
if (arguments.length<2){nodeSeparator="";}
if (arguments.length<1){elementSeparator="";}
return $.map(this, function(el){
return elementText(el,nodeSeparator);
}).join(elementSeparator);
}
} (jQuery));
to call:
var text = $('#listItem').textNotChild();
the arguments are in case a different scenario is encountered, such as
<li>some text<a>more text</a>again more</li>
<li>second text<a>more text</a>again more</li>
var text = $("li").textNotChild(".....","<break>");
text will have value:
some text<break>again more.....second text<break>again more
The way to keep SELECT dbo.fCalculateEstimateDate(647)
call working is:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100) AS
Declare @Result varchar(100)
SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
Return @Result
Begin
End
CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100) AS
Begin
<Function Body>
End
Or if you want to hide/show the title bar at any point:
private void toggleFullscreen(boolean fullscreen)
{
WindowManager.LayoutParams attrs = getWindow().getAttributes();
if (fullscreen)
{
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
else
{
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
getWindow().setAttributes(attrs);
}
Remove key and then add again the modified key, value pair as shown below :
JSONObject js = new JSONObject();
js.put("name", "rai");
js.remove("name");
js.put("name", "abc");
I haven't used your example; but conceptually its same.
Perhaps add the number of days in the current month using calendar.monthrange()?
import calendar, datetime
def increment_month(when):
days = calendar.monthrange(when.year, when.month)[1]
return when + datetime.timedelta(days=days)
now = datetime.datetime.now()
print 'It is now %s' % now
print 'In a month, it will be %s' % increment_month(now)
For start Activity 2 from Activity 1 and get result, you could use startActivityForResult and implement onActivityResult in Activity 1 and use setResult in Activity2.
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(NUMERO1, numero1);
intent.putExtra(NUMERO2, numero2);
//startActivity(intent);
startActivityForResult(intent, MI_REQUEST_CODE);
100% working code with demo You can also send multiple emails using this answer.
Download Project HERE
Step 1: Download mail, activation, additional jar files and add in your project libs folder in android studio. I added a screenshot see below Download link
Login with gmail (using your from mail) and TURN ON toggle button LINK
Most of the people forget about this step i hope you will not.
Step 2 : After completing this process. Copy and past this classes into your project.
GMail.java
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GMail {
final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
List<String> toEmailList;
String emailSubject;
String emailBody;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public GMail() {
}
public GMail(String fromEmail, String fromPassword,
List<String> toEmailList, String emailSubject, String emailBody) {
this.fromEmail = fromEmail;
this.fromPassword = fromPassword;
this.toEmailList = toEmailList;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", smtpAuth);
emailProperties.put("mail.smtp.starttls.enable", starttls);
Log.i("GMail", "Mail server properties set.");
}
public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException {
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
for (String toEmail : toEmailList) {
Log.i("GMail", "toEmail: " + toEmail);
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");// for a html email
// emailMessage.setText(emailBody);// for a text email
Log.i("GMail", "Email Message created.");
return emailMessage;
}
public void sendEmail() throws AddressException, MessagingException {
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromEmail, fromPassword);
Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
Log.i("GMail", "Email sent successfully.");
}
}
SendMailTask.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import java.util.List;
public class SendMailTask extends AsyncTask {
private ProgressDialog statusDialog;
private Activity sendMailActivity;
public SendMailTask(Activity activity) {
sendMailActivity = activity;
}
protected void onPreExecute() {
statusDialog = new ProgressDialog(sendMailActivity);
statusDialog.setMessage("Getting ready...");
statusDialog.setIndeterminate(false);
statusDialog.setCancelable(false);
statusDialog.show();
}
@Override
protected Object doInBackground(Object... args) {
try {
Log.i("SendMailTask", "About to instantiate GMail...");
publishProgress("Processing input....");
GMail androidEmail = new GMail(args[0].toString(),
args[1].toString(), (List) args[2], args[3].toString(),
args[4].toString());
publishProgress("Preparing mail message....");
androidEmail.createEmailMessage();
publishProgress("Sending email....");
androidEmail.sendEmail();
publishProgress("Email Sent.");
Log.i("SendMailTask", "Mail Sent.");
} catch (Exception e) {
publishProgress(e.getMessage());
Log.e("SendMailTask", e.getMessage(), e);
}
return null;
}
@Override
public void onProgressUpdate(Object... values) {
statusDialog.setMessage(values[0].toString());
}
@Override
public void onPostExecute(Object result) {
statusDialog.dismiss();
}
}
Step 3 : Now you can change this class according to your needs also you can send multiple mail using this class. i provide xml and java file both.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="30dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="From Email" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:cursorVisible="true"
android:editable="true"
android:ems="10"
android:enabled="true"
android:inputType="textEmailAddress"
android:padding="5dp"
android:textColor="#000000">
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Password (For from email)" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="To Email" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:inputType="textEmailAddress"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Subject" />
<EditText
android:id="@+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Body" />
<EditText
android:id="@+id/editText5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:inputType="textMultiLine"
android:padding="35dp"
android:textColor="#000000" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Email" />
</LinearLayout>
SendMailActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
public class SendMailActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button send = (Button) this.findViewById(R.id.button1);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("SendMailActivity", "Send Button Clicked.");
String fromEmail = ((TextView) findViewById(R.id.editText1))
.getText().toString();
String fromPassword = ((TextView) findViewById(R.id.editText2))
.getText().toString();
String toEmails = ((TextView) findViewById(R.id.editText3))
.getText().toString();
List<String> toEmailList = Arrays.asList(toEmails
.split("\\s*,\\s*"));
Log.i("SendMailActivity", "To List: " + toEmailList);
String emailSubject = ((TextView) findViewById(R.id.editText4))
.getText().toString();
String emailBody = ((TextView) findViewById(R.id.editText5))
.getText().toString();
new SendMailTask(SendMailActivity.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
}
});
}
}
Note Dont forget to add internet permission in your AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
Hope it work if it not then just comment down below.
Following solution is working fine.
HTML:
<table>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
</table>
JQuery:
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
I have done bins on http://codebins.com/bin/4ldqpa9
<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />
<head>
<base href="${baseURL}" />
Use this,
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
I've had problems using /usr/bin/php on CPanel as it is compiled as a "cgi-fcgi" binary and not "cli". Try using /usr/local/bin/php or, as it is first in the path anyway, just use 'php' instead:
php /path/to/script.php
If you want to run the script as an executable, give it +x perms and use the following as the first line of the script:
#!/usr/bin/env php
Use Python:
#!/bin/bash
# home/victoria/test.sh
START=$(date +"%s") ## seconds since Epoch
for i in $(seq 1 10)
do
sleep 1.5
END=$(date +"%s") ## integer
TIME=$((END - START)) ## integer
AVG_TIME=$(python -c "print(float($TIME/$i))") ## int to float
printf 'i: %i | elapsed time: %0.1f sec | avg. time: %0.3f\n' $i $TIME $AVG_TIME
((i++)) ## increment $i
done
Output
$ ./test.sh
i: 1 | elapsed time: 1.0 sec | avg. time: 1.000
i: 2 | elapsed time: 3.0 sec | avg. time: 1.500
i: 3 | elapsed time: 5.0 sec | avg. time: 1.667
i: 4 | elapsed time: 6.0 sec | avg. time: 1.500
i: 5 | elapsed time: 8.0 sec | avg. time: 1.600
i: 6 | elapsed time: 9.0 sec | avg. time: 1.500
i: 7 | elapsed time: 11.0 sec | avg. time: 1.571
i: 8 | elapsed time: 12.0 sec | avg. time: 1.500
i: 9 | elapsed time: 14.0 sec | avg. time: 1.556
i: 10 | elapsed time: 15.0 sec | avg. time: 1.500
$
It really helps to understand the LINQ query syntax and how it is translated to LINQ method calls.
It turns out that
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
will be translated by the compiler to
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.OrderByDescending(p => p.LowestPrice)
.Select(p => p);
This is emphatically not what you want. This sorts by Product.LowestPrice.HasValue
in descending
order and then re-sorts the entire collection by Product.LowestPrice
in descending
order.
What you want is
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.ThenBy(p => p.LowestPrice)
.Select(p => p);
which you can obtain using the query syntax by
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending,
p.LowestPrice
select p;
For details of the translations from query syntax to method calls, see the language specification. Seriously. Read it.
leading 0
means this is octal constant, not the decimal one. and you need an octal to change file mode.
permissions are a bit mask, for example, rwxrwx---
is 111111000
in binary, and it's very easy to group bits by 3 to convert to the octal, than calculate the decimal representation.
0644
(octal) is 0.110.100.100
in binary (i've added dots for readability), or, as you may calculate, 420
in decimal.
A normal broadcast Intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete.
you refer to my blog:enter link description here
get matched string back or false
function preg_match (regex, str) {
if (new RegExp(regex).test(str)){
return regex.exec(str);
}
return false;
}
Simply use ${parameter%word}
In your case:
${FILE%.*}
If you want to test it, all following work, and just remove the extension:
FILE=abc.xyz; echo ${FILE%.*};
FILE=123.abc.xyz; echo ${FILE%.*};
FILE=abc; echo ${FILE%.*};
I believe the get()
function immediately runs the select query and does not accept ORDER BY
conditions as parameters. I think you'll need to separately declare the conditions, then run the query. Give this a try:
$this->db->from($this->table_name);
$this->db->order_by("name", "asc");
$query = $this->db->get();
return $query->result();
View Remote URLs
> git remote -v
heroku https://git.heroku.com/###########.git (fetch) < your Heroku Remote URL
heroku https://git.heroku.com/############.git (push)
origin https://github.com/#######/#####.git (fetch) < if you use GitHub then this is your GitHub remote URL
origin https://github.com/#######/#####.git (push)
Remove Heroku remote URL
> git remote rm heroku
Set new Heroku URL
> heroku git:remote -a ############
And you are done.
I used this solution and it worked with Font Awesome 5: https://stackoverflow.com/a/50973559/3813846
What made the difference in my case was to add font-weight: 900;
to the class. Keep in mind to 'fa' to the value.
Example of my code:
<select class="text-primary fa-select" name="class_logo" required>
<option value="fa address-book"> address-book</option>
<option value="fa adjust"> adjust</option>
<option value="fa air-freshener"> air-freshener</option>
</select>
CSS:
.fa-select {
font-family: 'Lato', 'Font Awesome 5 Free';
font-weight: 900;
}
Edit: If you are mixing Solid Icons with Brand Icons in the select, change the CSS as follows:
.fa-select {
font-family: 'Lato', 'Font Awesome 5 Free', 'Font Awesome 5 Brands';
font-weight: 900;
}
var myVar = $("#start").find('.myClass').first().val();
mysql>
root@xion:~# mysql -uroot -ppassword;
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 33291
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> \! clear
select 'abcd' + ltrim(str(1)) + ltrim(str(2))
There is no standard Java class or method that will do what you want. Your options include:
Select and use some third-party expression evaluation library. For example JEL or any of the half dozen libraries listed here.
Wrap the expression in the Java source code for a class with an eval
method, send that to the Java compiler, and then load the resulting compiled class.
Use some scripting language that can be called from Java as an expression evaluator. Possibilities include Javascript, BeanShell, and so on.
Write your own expression evaluator from scratch.
The first approach is probably simplest. The second and third approaches are a potential security risk if you get the expression to be evaluated from an untrusted user. (Think code injection.)
There are two ways to download a file where the HTTP request requires that a header be set.
The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.
The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.
The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.
Solution:
var id = 123;
var req = ic.ajax.raw({
type: 'GET',
url: '/api/dowloads/'+id,
beforeSend: function (request) {
request.setRequestHeader('token', 'token for '+id);
},
processData: false
});
var maxSizeForBase64 = 1048576; //1024 * 1024
req.then(
function resolve(result) {
var str = result.response;
var anchor = $('.vcard-hyperlink');
var windowUrl = window.URL || window.webkitURL;
if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
var blob = new Blob([result.response], { type: 'text/bin' });
var url = windowUrl.createObjectURL(blob);
anchor.prop('href', url);
anchor.prop('download', id+'.bin');
anchor.get(0).click();
windowUrl.revokeObjectURL(url);
}
else {
//use base64 encoding when less than set limit or file API is not available
anchor.attr({
href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
download: id+'.bin',
});
anchor.get(0).click();
}
}.bind(this),
function reject(err) {
console.log(err);
}
);
Note that I'm not using a raw XMLHttpRequest
,
and instead using ic-ajax,
and should be quite similar to a jQuery.ajax
solution.
Note also that you should substitute text/bin
and .bin
with whatever corresponds to the file type being downloaded.
The implementation of FormatUtils.utf8toBase64
can be found here
Dont know if someone else has this problem but wrapping my TextBlock
into a ScrollViewer
somewhow messed up my UI - as a simple workaround I figured out that replacing the TextBlock
by a TextBox
like this one
<TextBox Name="textBlock" SelectionBrush="Transparent" Cursor="Arrow" IsReadOnly="True" Text="My Text" VerticalScrollBarVisibility="Auto">
creates a TextBox
that looks and behaves like a TextBlock
with a scrollbar (and you can do it all in the designer).
I think the simplest way to do this is from Excel.
If you have a newer version of Excel you could bring the data in from PowerPivot and then insert this data into a table.
Opacity gives you translucency or transparency. See an example Fiddle here.
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* IE 8 */
filter: alpha(opacity=50); /* IE 5-7 */
-moz-opacity: 0.5; /* Netscape */
-khtml-opacity: 0.5; /* Safari 1.x */
opacity: 0.5; /* Good browsers */
Note: these are NOT CSS3 properties
See http://css-tricks.com/snippets/css/cross-browser-opacity/
Alternate suggestion - if you're using Eclipse, you could set a breakpoint on NullPointerException itself (in the Debug perspective, go to the "Breakpoints" tab and click on the little icon that has a ! in it)
Check both the "caught" and "uncaught" options - now when you trigger the NPE, you'll immediately breakpoint and you can then step through and see how exactly it is handled and why you're not getting a stack trace.
Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates
consider example of list
List<Program> blabla= new List<Program>();
blabla.Add(new Program("shubham", 1));
blabla.Add(new Program("google", 3));
blabla.Add(new Program("world",5));
blabla.Add(new Program("hello", 5));
blabla.Add(new Program("bye", 2));
contains names and ages. Now say we want to find names on condition So I Will use,
Predicate<Program> test = delegate (Program p) { return p.age > 3; };
List<Program> matches = blabla.FindAll(test);
Action<Program> print = Console.WriteLine;
matches.ForEach(print);
tried to Keep it Simple!
set escape on
... node_name = 'Geometric Vectors \& Matrices' ...
or alternatively:
set define off
... node_name = 'Geometric Vectors & Matrices' ...
The first allows you to use the backslash to escape the &.
The second turns off & "globally" (no need to add a backslash anywhere). You can turn it on again by set define on
and from that line on the ampersands will get their special meaning back, so you can turn it off for some parts of the script and not for others.
if it's inside the transaction, the database locking system will take care of concurrency issues. of course, if you use one (the mssql default is that it uses lock, so it states if you don't override that)
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
First add UICollectionViewDelegateFlowLayout as protocol.
Then:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
var columnCount = 3
let width = (view.frame.width - 20) / columnCount
return CGSize(width: width, height: width)
}
This happens because your upstream takes too much to answer the request and NGINX thinks the upstream already failed in processing the request, so it responds with an error.
Just include and increase proxy_read_timeout in location
config block.
Same thing happened to me and I used 1 hour timeout for an internal app at work:
proxy_read_timeout 3600;
With this, NGINX will wait for an hour (3600s) for its upstream to return something.
To get the current function's or method's name from inside it, consider:
import inspect
this_function_name = inspect.currentframe().f_code.co_name
sys._getframe
also works instead of inspect.currentframe
although the latter avoids accessing a private function.
To get the calling function's name instead, consider f_back
as in inspect.currentframe().f_back.f_code.co_name
.
If also using mypy
, it can complain that:
error: Item "None" of "Optional[FrameType]" has no attribute "f_code"
To suppress the above error, consider:
import inspect
import types
from typing import cast
this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name
Simply use this
onclick="location.href='pageurl.html';"
Try using itertools.count([n])
For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.
Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:
void caluculate(Person p){
p.dotheCalculate();
}
This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
int 0x80 is the assembly language instruction that is used to invoke system calls in Linux on x86 (i.e., Intel-compatible) processors.
You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?
You can use text classes:
.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white
use text classes in any tag where needed.
<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>
You can add your own classes or modify above classes as your requirement.
There are different ways to do that.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],
'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })
def getMonth(s): return s.split("-")[1] def getDay(s): return s.split("-")[0] def getYear(s): return s.split("-")[2] def getYearMonth(s): return s.split("-")[1]+"-"+s.split("-")[2]
year
, month
, day
and 'yearMonth
'. In your case, you need one of both. You can group using two columns 'year','month'
or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x)) df['month']= df['Date'].apply(lambda x: getMonth(x)) df['day']= df['Date'].apply(lambda x: getDay(x)) df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
3 20-Jan-14 25 15 14 Jan 20 Jan-14
4 21-Feb-14 60 80 14 Feb 21 Feb-14
In this case, we are grouping by two columns:
for key,g in df.groupby(['year','month']): print key,g
Output:
('13', 'Jun') Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
('13', 'Aug') Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
('14', 'Jan') Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
('14', 'Feb') Date abc xyz year month day YearMonth
In this case, we are grouping by one column:
for key,g in df.groupby(['YearMonth']): print key,g
Output:
Jun-13 Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
Aug-13 Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
Jan-14 Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
Feb-14 Date abc xyz year month day YearMonth
4 21-Feb-14 60 80 14 Feb 21 Feb-14
get_group
print df.groupby(['YearMonth']).get_group('Jun-13')
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
get_group
. This hack would help to filter values and get the grouped values.This also would give the same result.
print df[df['YearMonth']=='Jun-13']
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
You can select list of abc
or xyz
values during Jun-13
print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values
Output:
[100 -20] #abc values
[200 50] #xyz values
You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.
for x in set(df.YearMonth):
print df[df['YearMonth']==x].abc.values
print df[df['YearMonth']==x].xyz.values
I recommend also to check this answer as well.
You do not mention the version of Access that you are using. Microsoft reports a bug in 2000:
BUG: You receive a "The search key was not found in any record" error message when you compact a database or save design changes in Access 2000http://support.microsoft.com/kb/301474
If this is not your problem, here is a pretty comprehensive FAQ by Tony Toews, Microsoft Access MVP:
Corrupt Microsoft Access MDBs FAQhttp://www.granite.ab.ca/access/corruptmdbs.htm
If the problem is constantly occuring, you need to find the reason for the corruption of your table, and you will find a number of suggestions for tracking the cause in the site link above.
For completeness sake, it's good to know you could also do this:
return default;
It returns the same as return default(T);
function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs_x000D_
//compatibility for firefox and chrome_x000D_
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;_x000D_
var pc = new myPeerConnection({_x000D_
iceServers: []_x000D_
}),_x000D_
noop = function() {},_x000D_
localIPs = {},_x000D_
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,_x000D_
key;_x000D_
_x000D_
function iterateIP(ip) {_x000D_
if (!localIPs[ip]) onNewIP(ip);_x000D_
localIPs[ip] = true;_x000D_
}_x000D_
onNewIP_x000D_
//create a bogus data channel_x000D_
pc.createDataChannel("");_x000D_
_x000D_
// create offer and set local description_x000D_
pc.createOffer().then(function(sdp) {_x000D_
sdp.sdp.split('\n').forEach(function(line) {_x000D_
if (line.indexOf('candidate') < 0) return;_x000D_
line.match(ipRegex).forEach(iterateIP);_x000D_
});_x000D_
_x000D_
pc.setLocalDescription(sdp, noop, noop);_x000D_
}).catch(function(reason) {_x000D_
// An error occurred, so handle the failure to connect_x000D_
});_x000D_
_x000D_
//listen for candidate events_x000D_
pc.onicecandidate = function(ice) {_x000D_
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;_x000D_
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);_x000D_
};_x000D_
}_x000D_
getUserIP(console.log)
_x000D_
You cannot select on specific values (or types of values). You'd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through all values every time.
If you are processing numbers in arbitrary order anyway, you may as well loop through all items:
for key, value in inputdict.items():
# do something with value
inputdict[key] = newvalue
otherwise I'd go with the reverse index:
from collections import defaultdict
reverse = defaultdict(list)
for key, value in inputdict.items():
reverse[value].append(key)
Now you can look up keys by value:
for key in reverse[value]:
inputdict[key] = newvalue
In git version 2.14.3,
You can remove upstream using
git branch --unset-upstream
The above command will also remove the tracking stream branch, hence if you want to rebase from repository you have use
git rebase origin master
instead of git pull --rebase
-z
string is null, that is, has zero length
String='' # Zero-length ("null") string variable.
if [ -z "$String" ]
then
echo "\$String is null."
else
echo "\$String is NOT null."
fi # $String is null.
This should be the Unix load average. Wikipedia has a nice article about this.
The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes
Just use floatval()
.
E.g.:
$var = '122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
And in case you wonder doubleval()
is just an alias for floatval()
.
And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001
and this error could propagate.
This is similar to other answers, however updated for new available apis and much cleaner. Also, does not assume you're in an Activity Context.
public class MyService extends AnyContextSubclass {
public void postToastMessage(final String message) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
}
});
}
}
You can return FileResult with this methods:
1: Return FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = fileName
};
}
2: Return FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
Nobody responding seems to be using the Map()
built-in for this, which tends to be my go-to combined with Array.prototype.reduce()
:
const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];_x000D_
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());_x000D_
console.log(...result);
_x000D_
N.b., you'll have to polyfill Map()
if wanting to use it in older browsers.
The trick is to add both max-height: 100%;
and max-width: 100%;
to .container img
. Example CSS:
.container {
width: 300px;
border: dashed blue 1px;
}
.container img {
max-height: 100%;
max-width: 100%;
}
In this way, you can vary the specified width of .container
in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)
Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/
with laravel pagination
file.component.ts file
datasource: any = {
data: []
}
loadData() {
this.service.find(this.params).subscribe((res: any) => {
this.datasource = res;
});
}
html file
<tr *ngFor="let item of datasource.data; let i = index">
<th>{{ datasource.from + i }}</th>
</tr>
Changing the 'w' (write) in this line:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)
To 'wb' (write binary) fixed this problem for me:
output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)
Credit to @dandrejvv for the solution in the comment on the original post above.
Clustering uses shared storage of some kind (a drive cage or a SAN, for example), and puts two database front-ends on it. The front end servers share an IP address and cluster network name that clients use to connect, and they decide between themselves who is currently in charge of serving client requests.
If you're asking about a particular database server, add that to your question and we can add details on their implementation, but at its core, that's what clustering is.
TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.
we can use for truncate
TRUNCATE TABLE tablename
we can use for delete
DELETE FROM tablename
we can also give conditions as below
DELETE FROM tablename WHERE id='xyz'
You can create a Blob
from your base64 data, and then read it asDataURL
:
var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];
var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});
var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);
Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/
Alternatively, you can use .readAsText
, it works fine, and its more elegant.. but for some reason text does not sound right ;)
fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here
Full example: http://jsfiddle.net/tTYb8/3/
There is in fact a very simple way to do so. What we do is using a recursive function which is given the number (int) in the parameter. It is pretty easy to understand. You can add other conditions/variations too. Here is the code:
int binary(int num)
{
int rem;
if (num <= 1)
{
cout << num;
return num;
}
rem = num % 2;
binary(num / 2);
cout << rem;
return rem;
}
You can store the array using serialize
/unserialize
. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode
/json_decode
instead (which gives you a widely supported format). Avoid using implode
/explode
for this since you'll probably end up with bugs or security flaws.
Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?
Also, don't save the raw $_POST
array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).
Look at the Identity of the Application Pool that's running your application. By default it will be the Network Service account, but you can change this.
At least that's how it works on 2003 server, don't know if some details have changed for 2008 server.
=Join(Parameters!Product.Label, vbcrfl) for new line
try this:
var a = screen.Data.getFullYear();
var m = screen.Data.getMonth();
var d = screen.Data.getDate();
m = m + 1;
screen.Data = new Date(a, m, d);
if (screen.Data.getDate() != d)
screen.Data = new Date(a, m + 1, 0);
i have looked into the other answers, and a vital logic seems to be missing from them . ie, select everything between two CONSECUTIVE brackets,but NOT the brackets
so, here is my answer
\{([^{}]+)\}
You can use cut
to split the line on spaces and return only the first such field:
md5=$(md5sum "$my_iso_file" | cut -d ' ' -f 1)
numpy has a great tool for this task ("numpy.reshape") link to reshape documentation
a = [[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
`numpy.reshape(a,(3,3))`
you can also use the "-1" trick
`a = a.reshape(-1,3)`
the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3
so yes.. this would also work:
a = a.reshape(3,-1)
and this:
a = a.reshape(-1,2)
would do nothing
and this:
a = a.reshape(-1,9)
would change the shape to (2,9)
getent group insert_group_name_here | awk -F ':' '{print $4}' | sed 's|,| |g'
This returns a space separated list of users which I've used in scripts to populate arrays.
for i in $(getent group ftp | awk -F ':' '{print $4}' | sed 's|,| |g')
do
userarray+=("$i")
done
or
userarray+=("$(getent group GROUPNAME | awk -F ':' '{print $4}' | sed 's|,| |g')")
You need to do two things:
ie
one.start();
one.join();
If you don't start()
it, nothing will happen - creating a Thread doesn't execute it.
If you don't join)
it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.
If you are using Java 5/6, you can use Apache Commons IO for read file to string. The class org.apache.commons.io.FileUtils
contais several method for read files.
e.g. using the method FileUtils#readFileToString
:
File file = new File("abc.txt");
String content = FileUtils.readFileToString(file);
If you have gem installed and ruby and not able to install rails, then install ruby dev lib.
sudo apt-get install ruby-dev
It works for me. I have tried the different solution.
As Oriol said, you need the following redistributables before installing WAMP.
From the readme.txt
BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.
Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.
The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17
VC9 Packages (Visual C++ 2008 SP1)
https://www.microsoft.com/en-us/download/details.aspx?id=5582
https://www.microsoft.com/en-us/download/details.aspx?id=2092
VC10 Packages (Visual C++ 2010 SP1)
https://www.microsoft.com/en-us/download/details.aspx?id=8328
https://www.microsoft.com/en-us/download/details.aspx?id=13523
VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679
VC13 Packages[/b] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe
VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=52685
VC Packages x64 (Visual C++ 2017)
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads
During the creation of S3Client you can specify the endpoint mapping to a particular region. If default of s3.amazonaws.com
then bucket will be created in us-east-1
which is North Virginia.
More details on S3 endpoints and regions in AWS docs: http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region.
So, always make sure about the endpoint/region while creating the S3Client and access S3 resouces using the same client in the same region.
If the bucket is created from AWS S3 Console, then check the region from the console for that bucket then create a S3 Client in that region using the endpoint details mentioned in the above link.
Had the same problem. I tried regular expression and the apache StringUtils.indexOfIgnoreCase-Method, but both were pretty slow... So I wrote an short method myself...:
public static int indexOfIgnoreCase(final String chkstr, final String searchStr, int i) {
if (chkstr != null && searchStr != null && i > -1) {
int serchStrLength = searchStr.length();
char[] searchCharLc = new char[serchStrLength];
char[] searchCharUc = new char[serchStrLength];
searchStr.toUpperCase().getChars(0, serchStrLength, searchCharUc, 0);
searchStr.toLowerCase().getChars(0, serchStrLength, searchCharLc, 0);
int j = 0;
for (int checkStrLength = chkstr.length(); i < checkStrLength; i++) {
char charAt = chkstr.charAt(i);
if (charAt == searchCharLc[j] || charAt == searchCharUc[j]) {
if (++j == serchStrLength) {
return i - j + 1;
}
} else { // faster than: else if (j != 0) {
i = i - j;
j = 0;
}
}
}
return -1;
}
According to my tests its much faster... (at least if your searchString is rather short). if you have any suggestions for improvement or bugs it would be nice to let me know... (since I use this code in an application ;-)
I finished my work on this stuff - that is, iOS 4 + iTunes 9.2 update of my backup decoder library for Python - http://www.iki.fi/fingon/iphonebackupdb.py
It does what I need, little documentation, but feel free to copy ideas from there ;-)
(Seems to work fine with my backups at least.)
I can't add a comment yet (no minimal reputation reached)
so I leave this reply to underline that:
the "BeforeBuild" action with <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
is great but, for me, is conflicting with an Entity Framework model included into the same project.
The error I receive is:
Error reading resource '{mymodel}.csdl' -- 'Could not find a part of the path '{myprojectpath}\obj\Release\edmxResourcesToEmbed\{mymodel}.csdl
I suppose, the "edmxResourcesToembed" is created before the "BeforeBuild" target action is executed.
You would need to add a trigger on insert, update, delete that sets a value in another table to sysdate.
When you run application, it would read the value and save it somewhere so that the next time it is run it has a reference to compare.
Would you consider that "Special Admin Stuff"?
It would be better to describe what you're actually doing so you get clearer answers.
To quote the man:
The -e option is used to edit the current crontab using the editor specified by the VISUAL or EDITOR environment variables
Most often if you run crontab -e
from X, you have VISUAL
set; that's what is used. Try this:
VISUAL=vi crontab -e
It just worked for me :)
<style type="text/css">
div {
text-align: center;
}
.img1{
width: 150px;
height: 150px;
border-radius: 50%;
}
span{
display: block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
<span class='dif'></span>
<br>
<button>ADD</button>
</div>
<script type="text/javascript">
$('button').click(function() {
$('.dif').html("<img/>");
})
A lot of the answers in this thread get the point of using refs, but I think a complete example would be good. Since you're operating on an actual DOM node by using the event listener and stepping out of the React context, a ref should be considered the standard solution. Here's a complete example:
class someComponent extends Component {
constructor(props) {
super(props)
this.node = null
}
render() {
return (
<div ref={node => { this.node = node }}>Content</div>
)
}
handleEvent(event) {
if (this.node) {
this.setState({...})
}
}
componentDidMount() {
//as soon as render completes, the node will be registered.
const handleEvent = this.handleEvent.bind(this)
this.node.addEventListener('click', handleEvent)
}
componentWillUnmount() {
const handleEvent = this.handleEvent.bind(this)
this.node.removeEventListener('click', handleEvent)
}
}
in SQL*Plus you could also use a REFCURSOR
variable:
SQL> VARIABLE x REFCURSOR
SQL> DECLARE
2 V_Sqlstatement Varchar2(2000);
3 BEGIN
4 V_Sqlstatement := 'SELECT * FROM DUAL';
5 OPEN :x for v_Sqlstatement;
6 End;
7 /
ProcÚdure PL/SQL terminÚe avec succÞs.
SQL> print x;
D
-
X
PLEASE do not use object as a class name:
public class MyObject //better to choose an appropriate name
{
string id;
DateTime date;
public string ID
{
get { return id; }
set { id = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
You should implement INotifyPropertyChanged
for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.
Your Viewmodel class/ dialogbox class should have a Property
of your MyObject
list. ObservableCollection<MyObject>
is the way to go:
public ObservableCollection<MyObject> MyList
{
get...
set...
}
In your xaml
you should set the Itemssource
to your collection of MyObject
. (the Datacontext
have to be your dialogbox class!)
<DataGrid ItemsSource="{Binding Source=MyList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
Note that this may also work:
SELECT * FROM table WHERE s=ANY(array)
You can also find Toggle Line Numbers
under View
on the top toolbar of the Jupyter notebook in your browser.
This adds/removes the lines numbers in all notebook cells.
For me, Esc+l only added/removed the line numbers of the active cell.
I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync
. I tried both cygwin
and minGW
. It seems like rsync
is incompatible with git for windows
's version of ssh
.
Here is what worked for me: NFS.
Vagrant docs says:
NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.
This isn't true anymore. We can use vagrant-winnfsd
plugin nowadays. It's really simple to install:
vagrant plugin install vagrant-winnfsd
Vagrantfile
: config.vm.synced_folder ".", "/vagrant", type: "nfs"
Vagrantfile
: config.vm.network "private_network", type: "dhcp"
That's all I needed to make NFS
work. Laravel response time decreased from 500ms to 100ms for me.
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
Swift 5:
There are two things - App version and build version
To get App version:
if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
// present appVersion
}
To get Build version:
if let buildVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
// present buildVersion
}
Thanks @Brad Larson?
a lot
@Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case 0:
{
return new AlertDialog.Builder(this)
.setMessage("text here")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
try
{
}//end try
catch(Exception e)
{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_LONG).show();
}//end catch
}//end onClick()
}).create();
}//end case
}//end switch
return null;
}//end onCreateDialog
If you are using Git Extensions: go into the Commit screen, there should be a checkbox that says "Amend Commit" at the bottom, as can be seen below:
Suspended. The session is waiting for an event, such as I/O, to complete.
p:after {
content: none;
}
none is the official value to set the content, if specified, to nothing.
If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:
public string CreateFile(string id, string name, string description,
/* --> */ SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions // <---
};
return file.Id;
}
If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:
public string CreateFile(string id, string name, string description) // <---
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = SupportedPermissions.basic // <---
};
return file.Id;
}
If the order of your integers is not required, and if there are only unique values
you can also use NSIndexSet or NSMutableIndexSet You will be able to easily add and remove integers, or check if your array contains an integer with
- (void)addIndex:(NSUInteger)index
- (void)removeIndex:(NSUInteger)index
- (BOOL)containsIndexes:(NSIndexSet *)indexSet
Check the documentation for more info.
For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.
In [8]: arr
Out[8]:
array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]])
In [9]: arr*(arr % 2 == 0).astype(np.int)
Out[9]:
array([[ 0., 2., 0., 4., 0.],
[ 6., 0., 8., 0., 10.]])
Example: Change position of field_priority after field_price in table status.
ALTER TABLE `status` CHANGE `priority` `priority` INT(11) NULL DEFAULT NULL AFTER `price`;
with your VARCHAR, you may also need to specify the length, or its usually good to
What about grabbing the text, making a sting of it, then putting it into the query witrh
String TableName = "ComplicatedTableNameHere";
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
String editTextString1 = editText1.getText().toString();
BROKEN DOWN
String TableName = "ComplicatedTableNameHere";
//sets the table name as a string so you can refer to TableName instead of writing out your table name everytime
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
//gets the text from your edit text fieldfield
//editText1 = your edit text name
//EditTextIDhere = the id of your text field
String editTextString1 = editText1.getText().toString();
//sets the edit text as a string
//editText1 is the name of the Edit text from the (EditText) we defined above
//editTextString1 = the string name you will refer to in future
then use
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
+ " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");
Hope this helps some what...
NOTE each string is within
'"+stringname+"'
its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word
Consider a solution that will neatly handle arbitrarily many tables.
//ASSUMPTION: All tables must have the same columns
var tables = new List<DataTable>();
tables.Add(oneTableToRuleThemAll);
tables.Add(oneTableToFindThem);
tables.Add(oneTableToBringThemAll);
tables.Add(andInTheDarknessBindThem);
//Or in the real world, you might be getting a collection of tables from some abstracted data source.
//behold, a table too great and terrible to imagine
var theOneTable = tables.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
Encapsulated into a helper for future reuse:
public static DataTable CombineDataTables(params DataTable[] args)
{
return args.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
}
Just have a few tables declared in code?
var combined = CombineDataTables(dt1,dt2,dt3);
Want to combine into one of the existing tables instead of creating a new one?
dt1 = CombineDataTables(dt1,dt2,dt3);
Already have a collection of tables, instead of declared one by one?
//Pretend variable tables already exists
var tables = new[] { dt1, dt2, dt3 };
var combined = CombineDataTables(tables);
yes, thats possible. just use the rgba-syntax for your background-color.
.menue{
background-color: rgba(255, 0, 0, 0.5); //semi-transparent red
}
I am not sure if I am right but in my opinion calling #define
d value is much faster than calling any other normally declared variable (or const value).
It's because when program is running and it needs to use some normally declared variable it needs to jump to exact place in memory to get that variable.
In opposite when it use #define
d value, the program don't need to jump to any allocated memory, it just takes the value. If #define myValue 7
and the program calling myValue
, it behaves exactly the same as when it just calls 7
.
Since the problem is the non-trivial destructor so if the destructor is removed from the std::string
, it's possible to define a constexpr
instance of that type. Like this
struct constexpr_str {
char const* str;
std::size_t size;
// can only construct from a char[] literal
template <std::size_t N>
constexpr constexpr_str(char const (&s)[N])
: str(s)
, size(N - 1) // not count the trailing nul
{}
};
int main()
{
constexpr constexpr_str s("constString");
// its .size is a constexpr
std::array<int, s.size> a;
return 0;
}
In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.
Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:
<location path="YourWebservice.asmx">
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</location>
but what I got is something like this: Date@124bbbf
while I change the import to: import java.util.Date;
the code works perfectly, why?
What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.
You can use the StringUtils class in Apache Commons:
StringUtils.substringAfterLast(one, "-");
For graphical elements that are purely decorative, set their respective android:contentDescription XML attributes to "@null".
If your app only supports devices running Android 4.1 (API level 16) or higher, you can instead set these elements' android:importantForAccessibility XML attributes to "no"
you can read /proc/meminfo to get used memory
file1 = open('/proc/meminfo', 'r')
for line in file1:
if 'MemTotal' in line:
x = line.split()
memTotal = int(x[1])
if 'Buffers' in line:
x = line.split()
buffers = int(x[1])
if 'Cached' in line and 'SwapCached' not in line:
x = line.split()
cached = int(x[1])
if 'MemFree' in line:
x = line.split()
memFree = int(x[1])
file1.close()
percentage_used = int ( ( memTotal - (buffers + cached + memFree) ) / memTotal * 100 )
print(percentage_used)
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
The problem is most probably between a . and a _. Say in my query I put
SELECT ..... FROM LOCATION.PT
instead of
SELECT ..... FROM LOCATION_PT
So I think MySQL would think LOCATION as a database name and was giving access privilege error.
There are several ways to create a dataframe from multiple lists.
list1=[1,2,3,4]
list2=[5,6,7,8]
list3=[9,10,11,12]
pd.DataFrame({'list1':list1, 'list2':list2, 'list3'=list3})
pd.DataFrame(data=zip(list1,list2,list3),columns=['list1','list2','list3'])
You should replace your getEnumNameForValue
by a call to the name()
method.
You can use the nice_hash gem: https://github.com/MarioRuiz/nice_hash
require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'
# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json
# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)
# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]
From msdn
When you created the project, you made the wrong choice of application type. When asked whether your project was a console application or a windows application or a DLL or a static library, you made the wrong chose windows application (wrong choice).
Go back, start over again, go to File -> New -> Project -> Win32 Console Application -> name your app -> click next -> click application settings.
For the application type, make sure Console Application is selected (this step is the vital step).
The main for a windows application is called WinMain, for a DLL is called DllMain, for a .NET application is called Main(cli::array ^), and a static library doesn't have a main. Only in a console app is main called main
It's important to note that Lauritz's suggestion idea of using bisect does not actually find the closest value in MyList to MyNumber. Instead, bisect finds the next value in order after MyNumber in MyList. So in OP's case you'd actually get the position of 44 returned instead of the position of 4.
>>> myList = [1, 3, 4, 44, 88]
>>> myNumber = 5
>>> pos = (bisect_left(myList, myNumber))
>>> myList[pos]
...
44
To get the value that's closest to 5 you could try converting the list to an array and using argmin from numpy like so.
>>> import numpy as np
>>> myNumber = 5
>>> myList = [1, 3, 4, 44, 88]
>>> myArray = np.array(myList)
>>> pos = (np.abs(myArray-myNumber)).argmin()
>>> myArray[pos]
...
4
I don't know how fast this would be though, my guess would be "not very".
This has been answered above, but I wanted to suggest an alternative.
When in the Build Settings for you project or target, you can go to the Editor menu and select Show Setting Names
from the menu. This will change all of the options in the Build Settings pane to the build variable names. The option in the menu changes to Show Setting Titles
, select this to change back to the original view.
This can be handy when you know what build setting you want to use in a script, toggle the setting names in the menu and you can see the variable name.
The middle one writes to the pipeline. Write-Host
and Out-Host
writes to the console. 'echo' is an alias for Write-Output
which writes to the pipeline as well. The best way to write to the console would be using the Write-Host
cmdlet.
When an object is written to the pipeline it can be consumed by other commands in the chain. For example:
"hello world" | Do-Something
but this won't work since Write-Host
writes to the console, not to the pipeline (Do-Something will not get the string):
Write-Host "hello world" | Do-Something
In case someone doesn't fix the problem use methods above. I fixed mine by surrounding the async func by an arrow function. As in:
describe("Profile Tab Exists and Clickable: /settings/user", () => {
test(`Assert that you can click the profile tab`, (() => {
async () => {
await page.waitForSelector(PROFILE.TAB)
await page.click(PROFILE.TAB)
}
})(), 30000);
});
usermod -m -d /newhome username
Maybe usefull to someone. On a Windows system, you can let Windows do the job by calling the dir-command. I use an absolute path, like E:/mydir/mysubdir
.
<?php
$mydir='E:/mydir/mysubdir';
$dir=str_replace('/','\\',$mydir);
$total = exec('dir '.$dir.' /b/a-d | find /v /c "::"');
You can give like this also
labelName.font = UIFont(name: "systemFont", size: 30)
Replacing backslash with forward slash worked for me on Windows.
Through CSS:
<label for="">
<input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>
pointer-events not supported in IE<10
This is what you need : ternary operator, please take a look at this
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
# extract numbers from garbage string:
s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
listOfNumbers = [float(i) for i in newstr.split()]
print(listOfNumbers)
[12.0, 3.14, 0.0, 1.6e-19, 334.0]
Ok, here's a ready-to-copy-paste answer using the require('request') npm module and an environment variable *instead of an hardcoded proxy):
coffeescript
app.use (req, res, next) ->
r = false
method = req.method.toLowerCase().replace(/delete/, 'del')
switch method
when 'get', 'post', 'del', 'put'
r = request[method](
uri: process.env.PROXY_URL + req.url
json: req.body)
else
return res.send('invalid method')
req.pipe(r).pipe res
javascript:
app.use(function(req, res, next) {
var method, r;
method = req.method.toLowerCase().replace(/delete/,"del");
switch (method) {
case "get":
case "post":
case "del":
case "put":
r = request[method]({
uri: process.env.PROXY_URL + req.url,
json: req.body
});
break;
default:
return res.send("invalid method");
}
return req.pipe(r).pipe(res);
});
You can use offsets to make a column appear centered, just use an offset equal to half of the remaining size of the row, in your case I would suggest using col-lg-4
with col-lg-offset-4
, that's (12-4)/2
.
<div class="row">
<div class="col-lg-4 col-lg-offset-4">
<div class="input-group">
<input type="text" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-lg-4 -->
</div><!-- /.row -->
Note that this technique only works for even column sizes (.col-X-2
, .col-X-4
, col-X-6
, etc...), if you want to support any size you can use margin: 0 auto;
but you need to remove the float from the element too, I recommend a custom CSS class like the following:
.col-centered{
margin: 0 auto;
float: none;
}
Here's a neat trick:
// E.g pad("sss","00000000"); should deliver "00000sss".
public static String pad(String string, String pad) {
/*
* Add the pad to the left of string then take as many characters from the right
* that is the same length as the pad.
* This would normally mean starting my substring at
* pad.length() + string.length() - pad.length() but obviously the pad.length()'s
* cancel.
*
* 00000000sss
* ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
*/
return (pad + string).substring(string.length());
}
public static void main(String[] args) throws InterruptedException {
try {
System.out.println("Pad 'Hello' with ' ' produces: '"+pad("Hello"," ")+"'");
// Prints: Pad 'Hello' with ' ' produces: ' Hello'
} catch (Exception e) {
e.printStackTrace();
}
}
If u want to tweak the spacing without touching the actual cell size, this is the solution that worked best for me. #xcode 9 #tvOS11 #iOS11 #swift
So in UICollectionViewDelegateFlowLayout, change implement the next methods, the trick is u have to use both of them, and the documentation was not really pointing me to think in that direction. :D
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return cellSpacing
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return cellSpacing
}
Had been wrecking my head on symlinking node .. and nothing seemed to work...but finally what worked is setting the right permissions . This 'sudo chown -R $(whoami) /usr/local' did the work for me.
Use:
function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
alert("pname["+i+"].value="+inp.value);
}
}
Here is Demo
.
I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).
<input type="text" value="<script>alert('test');</script>" />
Produces:
You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value
attribute.
var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";
If you add in the style
br{
display: none;
}
Then this will work. Not sure if it will work in older versions of IE though.
Are you using standards mode? This solution depends on it I think.
If you're trying to make 2 columns you could do something like this:
<div id="outer">
<div id="left">
sidebar
</div>
<div id="main">
lorem ispsum etc...
</div>
</div>
Then use CSS to style it:
div#outer
{
width:100%;
height: 500px;
}
div#left
{
width: 100px;
height: 100%;
float:left;
background: green;
}
div#main
{
width: auto;
margin-left: 100px; /* same as div#left width */
height: 100%;
background:red;
}
If you don't want 2 columns you can probably remove <div id="left">
Use the following selector.
$('#attached_docs [value=123]').remove();
This is what you want:
>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))
I will go there
I will go now
great
you can just append another hidden img
element and swap them in onload
event.
Or use single image element and use javascript like:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://whatever';
this code should preload the image and show it when it's ready
Here's another way using Visual Studio: If you do New Item in Visual Studio and you select Web Form, it will create a standalone *.aspx web form, which is what you have for your current web form (is this what you did?). You need to select Web Content Form and then select the master page you want attached to it.
If you want absolute urls, you have the third parameter.
$product_url = $this->generateUrl('product_detail',
array(
'slug' => 'slug'
),
UrlGeneratorInterface::ABSOLUTE_URL
);
Remember to include UrlGeneratorInterface.
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.
Example here: https://codesandbox.io/s/21r4z95p7j
You can even utilize the bottom gutter space if you so choose, simply by adding another "item".
Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background-color: #334;_x000D_
color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
min-height: 100vh;_x000D_
min-width: 100vw;_x000D_
display: grid;_x000D_
grid-template-columns: 100%;_x000D_
grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
background-color: #558;_x000D_
padding: 2px;_x000D_
margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>Parcel Sandbox</title>_x000D_
<meta charset="UTF-8" />_x000D_
<link rel="stylesheet" href="src/index.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="app">_x000D_
<div class="main">_x000D_
<div class="item">Item 1</div>_x000D_
<!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Through Code:
Your best bet is to use parse inside a try-catch
and catch exception in case of failed parsing. (I am not aware of any TryParse
method).
(Using JSON.Net)
Simplest way would be to Parse
the string using JToken.Parse
, and also to check if the string starts with {
or [
and ends with }
or ]
respectively (added from this answer):
private static bool IsValidJson(string strInput)
{
if (string.IsNullOrWhiteSpace(strInput)) { return false;}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
//Exception in parsing json
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
}
The reason to add checks for {
or [
etc was based on the fact that JToken.Parse
would parse the values such as "1234"
or "'a string'"
as a valid token. The other option could be to use both JObject.Parse
and JArray.Parse
in parsing and see if anyone of them succeeds, but I believe checking for {}
and []
should be easier. (Thanks @RhinoDevel for pointing it out)
Without JSON.Net
You can utilize .Net framework 4.5 System.Json namespace ,like:
string jsonString = "someString";
try
{
var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
//Invalid json format
Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
}
(But, you have to install System.Json
through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343
on Package Manager Console) (taken from here)
Non-Code way:
Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:
For my PHP application the solution was include utf8_decode function for each variable get in $_POST
.
Ex: (SERVER SIDE)
if( strtoupper($_SERVER['REQUEST_METHOD']) == "POST" ){
$variable = htmlentities($_POST['variable']); // wrong
$variable = htmlentities( utf8_decode($_POST['variable']) ); // right
}
Abraços!!! (Bye Bye!!!)
The operators && and || are short-circuiting, meaning they will not evaluate their right-hand expression if the value of the left-hand expression is enough to determine the result.
For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:
audio.mp3
for
http://www.uscis.gov/files/nativedocuments/Track%2093.mp3
linking in a freely available mp3 off the web. Thank you for sharing the easy solution!
You could use the <pre>
tag
<div class="text">_x000D_
<pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</div>
_x000D_
If your entity class isn't in the same package as your main class, you can use @EntityScan
annotation in the main class, specifying the Entity you want to save or package too. Like your model package.
About:
spring.jpa.hibernate.ddl-auto = create
You can use the option update
. It won't erase any data, and will create tables in the same way.
I encountered this issue too, and resolved it by the removing Spring Facet:
Facets
Good luck!
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Some simple examples:
// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";
This also applies to method arguments, since you are passing explicit types to them:
int AddTwoNumbers(int a, int b)
{
return a + b;
}
If I tried to call that using:
int Sum = AddTwoNumbers(5, "5");
The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer.
In a loosely typed language, such as javascript, I can do the following:
function AddTwoNumbers(a, b)
{
return a + b;
}
if I call it like this:
Sum = AddTwoNumbers(5, "5");
Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:
function AddTwoNumbers(a, b)
{
return Number(a) + Number(b);
}
Or, possibly:
function AddOnlyTwoNumbers(a, b)
{
if (isNaN(a) || isNaN(b))
return false;
return Number(a) + Number(b);
}
if I call it like this:
Sum = AddTwoNumbers(5, " dogs");
Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs".
Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.
While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.
Now, back to C#...
C# supports a language feature called covariance, this basically means that you can substitute a base type for a child type and not cause an error, for example:
public class Foo : Bar
{
}
Here, I created a new class (Foo) that subclasses Bar. I can now create a method:
void DoSomething(Bar myBar)
And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.
However, you cannot do the inverse:
void DoSomething(Foo myFoo)
In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.
Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)
If you have
<div>
<input type="checkbox" class="check-with-label" id="idinput" />
<label class="label-for-check" for="idinput">My Label</label>
</div>
you can do
.check-with-label:checked + .label-for-check {
font-weight: bold;
}
See this working. Note that this won't work in non-modern browsers.
with 'nonlocal' inner functions(ie;nested inner functions) can get read & 'write' permission for that specific variable of the outer parent function. And nonlocal can be used only inside inner functions eg:
a = 10
def Outer(msg):
a = 20
b = 30
def Inner():
c = 50
d = 60
print("MU LCL =",locals())
nonlocal a
a = 100
ans = a+c
print("Hello from Inner",ans)
print("value of a Inner : ",a)
Inner()
print("value of a Outer : ",a)
res = Outer("Hello World")
print(res)
print("value of a Global : ",a)
A better way is to use SHOW KEYS
since you don't always have access to information_schema. The following works:
SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'
Column_name will contain the name of the primary key.
With below converter
public class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
public CustomDateTimeConverter(string format)
{
DateTimeFormat = format;
}
}
Can use it with a default custom format
class ReturnObjectA
{
[JsonConverter(typeof(DateFormatConverter))]
public DateTime ReturnDate { get;set;}
}
Or any specified format for a property
class ReturnObjectB
{
[JsonConverter(typeof(DateFormatConverter), "dd MMM yy")]
public DateTime ReturnDate { get;set;}
}
A minor point perhaps, but:
import static System.out;
public class Tester
{
public static void main(String[] args)
{
out.println("Hello!");
}
}
...generated a compile time error. I corrected the error by editing the first line to read:
import static java.lang.System.out;
It's optional.
The port may be specified so cookies can be port specific. It's not necessary, the web server / application must care of this.
Source: German Wikipedia article, RFC2109, Chapter 4.3.1
dynamic MyDynamic = new ExpandoObject();
<p>
<img style="float: right; margin: 0px 15px 15px 0px;" src="files/styles/large_hero_desktop_1x/public/headers/Kids%20on%20iPad%20 %202400x880.jpg?itok=PFa-MXyQ" width="100" />
Nunc pulvinar lacus id purus ultrices id sagittis neque convallis. Nunc vel libero orci.
<br style="clear: both;" />
</p>
this will change
my_dict
in place (mutable)
my_dict.pop('key', None)
generate a new dict (immutable)
dic1 = {
"x":1,
"y": 2,
"z": 3
}
def func1(item):
return item[0]!= "x" and item[0] != "y"
print(
dict(
filter(
lambda item: item[0] != "x" and item[0] != "y",
dic1.items()
)
)
)
Here other solution to only unlock the blocked user. From your command prompt log as SYSDBA:
sqlplus "/ as sysdba"
Then type the following command:
alter user <your_username> account unlock;
It is just Value, not @value.. Try it. I'm not sure about @Model.title, maybe it's just Model.title
As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.
Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,
int main()
{
int a = func();
}
int func()
{
return 1;
}
However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.
int func();
int main()
{
int a = func();
}
int func()
{
return 1;
}
If you want to set text at design time in xml
file just simple android:text="username"
add this property.
<EditText
android:id="@+id/edtUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="username"/>
If you want to set text programmatically in Java
EditText edtUsername = findViewById(R.id.edtUsername);
edtUsername.setText("username");
and in kotlin
same like java using getter/setter
edtUsername.setText("username")
But if you want to use .text
from principle then
edtUsername.text = Editable.Factory.getInstance().newEditable("username")
because of EditText.text
requires an editable
at firstplace not String
PUT http://{rm http address:port}/ws/v1/cluster/apps/{appid}/state
{
"state":"KILLED"
}
And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?
This is the value of User-Agent, the browser identification string.
For this reason, most Web browsers use a User-Agent string value as follows:
Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:
Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:
Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.
This value will be used to identify what browser is being used by end user.