It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
I keep coming back to these questions trying to figure out where exactly the data I'm interested in is buried in what is truly a monolithic ErrorRecord structure. Almost all answers give piecemeal instructions on how to pull certain bits of data.
But I've found it immensely helpful to dump the entire object with ConvertTo-Json
so that I can visually see LITERALLY EVERYTHING in a comprehensible layout.
try {
Invoke-WebRequest...
}
catch {
Write-Host ($_ | ConvertTo-Json)
}
Use ConvertTo-Json
's -Depth
parameter to expand deeper values, but use extreme caution going past the default depth of 2
:P
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json
SOLVED
After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:
What's obviously missing there is the Content-Type
header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type
never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType
property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type
was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:
req.Method = "POST"
req.ContentType = "application/json"
lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
req.ContentLength = bytData.Length
reqStream = req.GetRequestStream()
reqStream.Write(bytData, 0, bytData.Length)
reqStream.Close()
'// Content-Type was being set here, causing the problem
'req.ContentType = "application/json"
That's all it was, the ContentType
property just needed to be set prior to writing to the request body
I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.
I came across this thread because I also had the error Could not create SSL/TLS secure channel. In my case, I was attempting to access a Siebel configuration REST API from PowerShell using Invoke-RestMethod
, and none of the suggestions above helped.
Eventually I stumbled across the cause of my problem: the server I was contacting required client certificate authentication.
To make the calls work, I had to provide the client certificate (including the private key) with the -Certificate
parameter:
$Pwd = 'certificatepassword'
$Pfx = New-Object -TypeName 'System.Security.Cryptography.X509Certificates.X509Certificate2'
$Pfx.Import('clientcert.p12', $Pwd, 'Exportable,PersistKeySet')
Invoke-RestMethod -Uri 'https://your.rest.host/api/' -Certificate $Pfx -OtherParam ...
Hopefully my experience might help someone else who has my particular flavour of this problem.
use below code
Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));
If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)
I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.
Added the following to the config and it resolved the issue:
<system.net>
<defaultProxy enabled="true">
</defaultProxy>
</system.net>
I had a similar issue using the Chrome driver (v2.23) / running the tests thru TeamCity. I was able to fix the issue by adding the "no-sandbox" flag to the Chrome options:
var options = new ChromeOptions();
options.AddArgument("no-sandbox");
I'm not sure if there is a similar option for the FF driver. From what I understand the issue has something to do with TeamCity running Selenium under the SYSTEM account.
None of the solutions out there worked for me. What I eventually discovered was the following combination:
Apparently, it was this last option that was causing the issue. I discovered this by trying to open the web service URL directly in Internet Explorer. It just hung indefinitely trying to load the page. Disabling "Accept client certificates" allowed the page to load normally. I am not sure if it was a problem with this specific system (maybe a glitched client certificate?) Since I wasn't using client certificates this option worked for me.
Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.
Here is the code - The code is in asp.net core 2.0 but should work in above versions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
namespace UnityAssets.Website.Services
{
public class EmailSender : IEmailSender
{
public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
{
var email = new MimeMessage();
email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
email.Subject = subject;
var body = new BodyBuilder
{
HtmlBody = htmlMessage
};
email.Body = body.ToMessageBody();
using (var client = new SmtpClient())
{
//provider specific settings
await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);
await client.SendAsync(email).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
}
}
I had the same error when I imported web requests from fiddler captured sessions to Visual Studio webtests. Some POST requests did not have a StringHttpBody tag. I added an empty one to them and the error was gone. Add this after the Headers tag:
<StringHttpBody ContentType="" InsertByteOrderMark="False">
</StringHttpBody>
I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.
Setting:
request.Referer = @"http://www.somesite.com/";
and adding cookies
than worked for me
It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.
The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.
tl;dr:
There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors>
section from the WCF service's web.config
file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.
EDIT:
Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null
!) or the URL is incorrect.
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded
formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data
. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
Did you try using System.Net.WebClient
?
$url = 'https://IPADDRESS/resource'
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("username","password")
$wc.DownloadString($url)
The first step is to create the helper class for the HTTP client.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace callApi.Helpers
{
public class CallApi
{
private readonly Uri BaseUrlUri;
private HttpClient client = new HttpClient();
public CallApi(string baseUrl)
{
BaseUrlUri = new Uri(baseUrl);
client.BaseAddress = BaseUrlUri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public HttpClient getClient()
{
return client;
}
public HttpClient getClientWithBearer(string token)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
}
}
Then you can use this class in your code.
This is an example of how you call the REST API without bearer using the above class.
// GET API/values
[HttpGet]
public async Task<ActionResult<string>> postNoBearerAsync(string email, string password,string baseUrl, string action)
{
var request = new LoginRequest
{
email = email,
password = password
};
var callApi = new CallApi(baseUrl);
var client = callApi.getClient();
HttpResponseMessage response = await client.PostAsJsonAsync(action, request);
if (response.IsSuccessStatusCode)
return Ok(await response.Content.ReadAsAsync<string>());
else
return NotFound();
}
This is an example of how you can call the REST API that require bearer.
// GET API/values
[HttpGet]
public async Task<ActionResult<string>> getUseBearerAsync(string token, string baseUrl, string action)
{
var callApi = new CallApi(baseUrl);
var client = callApi.getClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.GetAsync(action);
if (response.IsSuccessStatusCode)
{
return Ok(await response.Content.ReadAsStringAsync());
}
else
return NotFound();
}
You can also refer to the below repository if you want to see the working example of how it works.
You'll need a using System.Net.Http
at the top.
Just keep the following in mind.
In IIS if you have a folder for example called Pages with multiple websites in it. Website will inherit settings from the web.config file from the parent directory. So even if the folder page (in this example Pages) isn't a website but contains a web.config file, all websites listed inside of it will inherit the setting.
I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:
catch (MyCustomException ex)
{
Debug.WriteLine(ex.ToString());
}
Sample output:
ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
--- End of inner exception stack trace ---
at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13
this works only if WebResponse is a HttpWebResponse.
try
{
...
}
catch (System.Net.WebException exc)
{
var webResponse = exc.Response as System.Net.HttpWebResponse;
if (webResponse != null &&
webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
MessageBox.Show("401");
}
else
throw;
}
Tried it out. ResponseHeaders do not include status code.
If I'm not mistaken, WebClient
is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest
and HttpWebResponse
, a distinct status code may not be available.
It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.
The status code unfortunately isn't present in the ResponseHeaders
dictionary.
One more possibility --
Make sure you're trying to open the same IP address as where you're listening. My server app was listening to the host machine's IP address using IPv6, but the client was attempting to connect on the host machine's IPv4 address.
After many answers that did not work, I finally found a solution when Anonymous access is Disabled on the IIS server. Our server is using Windows authentication, not Kerberos. This is thanks to this blog posting.
No changes were made to web.config.
On the server side, the .SVC file in the ISAPI folder uses MultipleBaseAddressBasicHttpBindingServiceHostFactory
The class attributes of the service are:
[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class InvoiceServices : IInvoiceServices
{
...
}
On the client side, the key that made it work was the http binding security attributes:
EndpointAddress endpoint =
new EndpointAddress(new Uri("http://SharePointserver/_vti_bin/InvoiceServices.svc"));
BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
InvoiceServicesClient myClient = new InvoiceServicesClient(httpBinding, endpoint);
myClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
(call service)
I hope this works for you!
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ?
at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
I had this issue when running older XP SP3 boxes against both IIS and glassfish on Amazon AWS. Amazon changed their default load balancer settings to NOT enable the DES-CBC3-SHA cipher. You have to enable that on amazon ELB if you want to allow older XP TLS 1.0 to work against ELB for HTTPS otherwise you get this error. Ciphers can be changed on ELB by going to the listener tab in the console and clicking on cipher next to the particular listener you are trying to make work.
I'm not sure about your first code sample where you use WebClient.UploadValues, it's not really enough to go on, could you paste more of your surrounding code? Regarding your WebRequest code, there are two things at play here:
You're only requesting the headers of the response**, you never read the body of the response by opening and reading (to its end) the ResponseStream. Because of this, the WebRequest client helpfully leaves the connection open, expecting you to request the body at any moment. Until you either read the response body to completion (which will automatically close the stream for you), clean up and close the stream (or the WebRequest instance) or wait for the GC to do its thing, your connection will remain open.
You have a default maximum amount of active connections to the same host of 2. This means you use up your first two connections and then never dispose of them so your client isn't given the chance to complete the next request before it reaches its timeout (which is milliseconds, btw, so you've set it to 0.2 seconds - the default should be fine).
If you don't want the body of the response (or you've just uploaded or POSTed something and aren't expecting a response), simply close the stream, or the client, which will close the stream for you.
The easiest way to fix this is to make sure you use using blocks on disposable objects:
for (int i = 0; i < ops1; i++)
{
Uri myUri = new Uri(site);
WebRequest myWebRequest = WebRequest.Create(myUri);
//myWebRequest.Timeout = 200;
using (WebResponse myWebResponse = myWebRequest.GetResponse())
{
// Do what you want with myWebResponse.Headers.
} // Your response will be disposed of here
}
Another solution is to allow 200 concurrent connections to the same host. However, unless you're planning to multi-thread this operation so you'd need multiple, concurrent connections, this won't really help you:
ServicePointManager.DefaultConnectionLimit = 200;
When you're getting timeouts within code, the best thing to do is try to recreate that timeout outside of your code. If you can't, the problem probably lies with your code. I usually use cURL for that, or just a web browser if it's a simple GET request.
** In reality, you're actually requesting the first chunk of data from the response, which contains the HTTP headers, and also the start of the body. This is why it's possible to read HTTP header info (such as Content-Encoding, Set-Cookie etc) before reading from the output stream. As you read the stream, further data is retrieved from the server. WebRequest's connection to the server is kept open until you reach the end of this stream (effectively closing it as it's not seekable), manually close it yourself or it is disposed of. There's more about this here.
I have a similar issue, have you tried:
proxy.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
Just want to point out
Apart from MaxRecivedMessageSize, there are also attributes under ReaderQuotas, you might hit number of items limit instead of size limit. MSDN link is here
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
This is happening because there is an unhandled exception in your Web service, and the .NET runtime is spitting out its HTML yellow screen of death server error/exception dump page, instead of XML.
Since the consumer of your Web service was expecting a text/xml header and instead got text/html, it throws that error.
You should address the cause of your timeouts (perhaps a lengthy SQL query?).
Also, checkout this blog post on Jeff Atwood's blog that explains implementing a global unhandled exception handler and using SOAP exceptions.
You need to override the following properties:
Broker Configs($KAFKA_HOME/config/server.properties)
Consumer Configs($KAFKA_HOME/config/consumer.properties)
This step didn't work for me. I add it to the consumer app and it was working fine
Restart the server.
look at this documentation for more info: http://kafka.apache.org/08/configuration.html
Yes you can
public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
//inflate the view
View view = LayoutInflator.from(parent.getContext()).inflate(R.layout.layoutID,null);
ViewHolder holder = new ViewHolder(view);
//here we can set onClicklistener
view.setOnClickListener(new View.OnClickListeener(){
public void onClick(View v)
{
//action
}
});
return holder;
Try
<button [ngClass]="type === 'mybutton' ? namespace + '-mybutton' : ''"></button>
instead.
or
<button [ngClass]="[type === 'mybutton' ? namespace + '-mybutton' : '']"></button>
or even
<button class="{{type === 'mybutton' ? namespace + '-mybutton' : ''}}"></button>
will work but extra benefit of using ngClass is that it does not overwrite other classes that are added by any other method( eg: [class.xyz]
directive or class
attribute, etc.) as class
does.
The new compiler, Ivy, brings more clarity and predictability to what happens when there are different types of class-bindings on the same element. Read More about it here.
ngClass takes three types of input
key
'key'
"key"
are all same, and [key]
is not supported AFAIK.This should be the code you need to hide the address bar:
window.addEventListener("load",function() {
setTimeout(function(){
// This hides the address bar:
window.scrollTo(0, 1);
}, 0);
});
Also nice looking Pokedex by the way! Hope this helps!
Working with jQuery 1.10.2, this pulses a dropdown twice and changes the text to an error. It also stores the values for the changed attributes to reinstate them.
// shows the user an error has occurred
$("#myDropdown").fadeOut(700, function(){
var text = $(this).find("option:selected").text();
var background = $(this).css( "background" );
$(this).css('background', 'red');
$(this).find("option:selected").text("Error Occurred");
$(this).fadeIn(700, function(){
$(this).fadeOut(700, function(){
$(this).fadeIn(700, function(){
$(this).fadeOut(700, function(){
$(this).find("option:selected").text(text);
$(this).css("background", background);
$(this).fadeIn(700);
})
})
})
})
});
Done via callbacks - to ensure no animations are missed.
Run R in emacs with ESS (Emacs Speaks Statistics) r-mode. I have one window open with my script and R code. Another has R running. Code is sent from the syntax window and evaluated. Commands, output, errors, and warnings all appear in the running R window session. At the end of some work period, I save all the output to a file. My own naming system is *.R for scripts and *.Rout for save output files. Here's a screenshot with an example.
testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>
UPDATE tablename SET fieldname = CONCAT("test", fieldname) [WHERE ...]
You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.
Because you do not provide any context or code for your question it is not possible to give a direct answer.
I suggest you study how unicode and character encoding is done in Python:
Resumee of Richard Fearn's answer , to make each second line gray:
jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return c;
}
});
This is due to IFS (Internal Field Separator) variable which contains newline.
$ cat xx1
1
2
$ A=`cat xx1`
$ echo $A
1 2
$ echo "|$IFS|"
|
|
A workaround is to reset IFS to not contain the newline, temporarily:
$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK
To REVERT this horrible change for IFS:
IFS=$IFSBAK
If you want to change the contents of each and every cell in a datatable then we need to Create another Datatable and bind it as follows using "Import Row". If we don't create another table it will throw an Exception saying "Collection was Modified".
Consider the following code.
//New Datatable created which will have updated cells
DataTable dtUpdated = new DataTable();
//This gives similar schema to the new datatable
dtUpdated = dtReports.Clone();
foreach (DataRow row in dtReports.Rows)
{
for (int i = 0; i < dtReports.Columns.Count; i++)
{
string oldVal = row[i].ToString();
string newVal = "{"+oldVal;
row[i] = newVal;
}
dtUpdated.ImportRow(row);
}
This will have all the cells preceding with Paranthesis({)
It means you didn't set ORACLE_HOME and ORACLE_SID variables. Kindly set proper working $ORACLE_HOME and $ORACLE_SID and after that execute sqlplus /nolog command. It will be working.
You're close; you should use dot notation in your use of the $
update operator to do that:
Person.update({'items.id': 2}, {'$set': {
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
}}, function(err) { ...
The solution for me (openSUSE Leap 42.3, KDE) was to rename the folder ~/.gnupg
which apparently contained the cached keys and profiles.
After KDE logout/logon the ssh-add/agent is running again and the folder is created from scratch, but the old keys are all gone.
I didn't have success with the other approaches.
12 years later for anyone having similar problems.
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
doesn't work because the port '80' is a string. Your port needs to be int.
try:
s.connect((address, 80))
This should work. Not sure why even the best answer didnt see this.
Use
Time.now + 10.days
or even
10.days.from_now
Both definitely work. Are you sure you're in Rails and not just Ruby?
If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
date()
itself is only for formatting, but it accepts a second parameter.
date("F j, Y", time() - 60 * 60 * 24);
To keep it simple I just subtract 24 hours from the unix timestamp.
A modern oop-approach is using DateTime
$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
Or in your case (more readable/obvious)
$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
(Because DateInterval
is negative here, we must add()
it here)
See also: DateTime::sub()
and DateInterval
There is the potential for a subtle bug in your code.
[UPDATE: Since he's using map.remove() this description isn't totally valid. I missed that fact the first time thru. :( Thanks to the question's author for pointing that out. I'm leaving the rest as is, but changed the lead statement to say there is potentially a bug.]
In doWork() you get the List value from the Map in a thread-safe way. Afterward, however, you are accessing that list in an unsafe matter. For instance, one thread may be using the list in doWork() while another thread invokes synchronizedMap.get(key).add(value) in addToMap(). Those two access are not synchronized. The rule of thumb is that a collection's thread-safe guarantees don't extend to the keys or values they store.
You could fix this by inserting a synchronized list into the map like
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, Collections.synchronizedList(valuesList)); // sync'd list
Alternatively you could synchronize on the map while you access the list in doWork():
public void doWork(String key) {
List<String> values = null;
while ((values = synchronizedMap.remove(key)) != null) {
synchronized (synchronizedMap) {
//do something with values
}
}
}
The last option will limit concurrency a bit, but is somewhat clearer IMO.
Also, a quick note about ConcurrentHashMap. This is a really useful class, but is not always an appropriate replacement for synchronized HashMaps. Quoting from its Javadocs,
This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.
In other words, putIfAbsent() is great for atomic inserts but does not guarantee other parts of the map won't change during that call; it guarantees only atomicity. In your sample program, you are relying on the synchronization details of (a synchronized) HashMap for things other than put()s.
Last thing. :) This great quote from Java Concurrency in Practice always helps me in designing an debugging multi-threaded programs.
For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held.
I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)
class CheckMailer:
def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
self.f = FileWriter(filename)
self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
self.inbox = self.outlook.Folders(folderindex)
def check(self):
#===============================================================================
# for i in xrange(1,100): #Uncomment this section if index 3 does not work for you
# try:
# self.inbox = self.outlook.Folders(i) # "6" refers to the index of inbox for Default User Mailbox
# print "%i %s" % (i,self.inbox) # "3" refers to the index of inbox for Another user's mailbox
# except:
# print "%i does not work"%i
#===============================================================================
self.f.pl(time.strftime("%H:%M:%S"))
tot = 0
messages = self.inbox.Items
message = messages.GetFirst()
while message:
self.f.pl (message.Subject)
message = messages.GetNext()
tot += 1
self.f.pl("Total Messages found: %i" % tot)
self.f.pl("-" * 80)
self.f.flush()
if __name__ == "__main__":
mail = CheckMailer()
for i in xrange(320): # this is 10.6 hours approximately
mail.check()
time.sleep(120.00)
For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.
class FileWriter(object):
'''
convenient file wrapper for writing to files
'''
def __init__(self, filename):
'''
Constructor
'''
self.file = open(filename, "w")
def pl(self, a_string):
str_uni = a_string.encode('utf-8')
self.file.write(str_uni)
self.file.write("\n")
def flush(self):
self.file.flush()
The watch function should place in Child component. Not parent.
Yes, you can use regular expressions
in C#.
Using regular expressions with C#
:
using System.Text.RegularExpressions;
string your_String = "Hello@Hello&Hello(Hello)";
string my_String = Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");
$(document).ready(function() {_x000D_
$("a").click(function(event) {_x000D_
var myClass = $(this).attr("class");_x000D_
var myId = $(this).attr('id');_x000D_
alert(myClass + " " + myId);_x000D_
});_x000D_
})
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
<a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
This works for me. There is no event.target.class function in jQuery.
This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch
you can remove files or change something over a large number of files throughout your entire git history.
It is best explained here.
Here is another example using Spark/Scala to convert a CSV to RDD. For a more detailed description see this post.
def main(args: Array[String]): Unit = {
val csv = sc.textFile("/path/to/your/file.csv")
// split / clean data
val headerAndRows = csv.map(line => line.split(",").map(_.trim))
// get header
val header = headerAndRows.first
// filter out header (eh. just check if the first val matches the first header name)
val data = headerAndRows.filter(_(0) != header(0))
// splits to map (header/value pairs)
val maps = data.map(splits => header.zip(splits).toMap)
// filter out the user "me"
val result = maps.filter(map => map("user") != "me")
// print result
result.foreach(println)
}
Important: Use the
( )
parentheses in your search string
While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( )
parentheses, otherwise these matched segments won't be accessible to defined variables such as $1
, $2
or \1
, \2
etc.
For example we want to replace 'em' with 'px' but preserve the digit values:
margin: 10em; /* Expected: margin: 10px */
margin: 2em; /* Expected: margin: 2px */
margin: $1px
or margin: \1px
margin: ([0-9]*)em
// with parenthesesmargin: [0-9]*em
CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em
search string (with parentheses). Enclose the desired matched segment (e.g. $1
or \1
) by ( )
parentheses as following:
margin: ([0-9]*)em
(with parentheses)margin: $1px
or margin: \1px
margin: 10px;
margin: 2px;
INCORRECT CASE EXAMPLE: Using margin: [0-9]*em
search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1
or \1
:
margin: [0-9]*em
(without parentheses)margin: $1px
or margin: \1px
margin: px; /* `$1` is undefined */
margin: px; /* `$1` is undefined */
With formatting
require 'json'
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(JSON.pretty_generate(tempHash))
end
Output
{
"key_a":"val_a",
"key_b":"val_b"
}
You can easily define such function and use it then:
ifnull <- function(x,y) {
if(is.na(x)==TRUE)
return (y)
else
return (x);
}
or same minified version:
ifnull <- function(x,y) {if(is.na(x)==TRUE) return (y) else return (x);}
Go to project properties -> configurations properties -> C/C++ -> treats warning as error -> No (/WX-)
.
Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.
List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();
You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.
Here is way to do this using javascript and the ant scriptdef task, you don't need ant-contrib for this code to work since scriptdef is a core ant task.
<scriptdef name="bzip2-files" language="javascript">
<element name="fileset" type="fileset"/>
<![CDATA[
importClass(java.io.File);
filesets = elements.get("fileset");
for (i = 0; i < filesets.size(); ++i) {
fileset = filesets.get(i);
scanner = fileset.getDirectoryScanner(project);
scanner.scan();
files = scanner.getIncludedFiles();
for( j=0; j < files.length; j++) {
var basedir = fileset.getDir(project);
var filename = files[j];
var src = new File(basedir, filename);
var dest= new File(basedir, filename + ".bz2");
bzip2 = self.project.createTask("bzip2");
bzip2.setSrc( src);
bzip2.setDestfile(dest );
bzip2.execute();
}
}
]]>
</scriptdef>
<bzip2-files>
<fileset id="test" dir="upstream/classpath/jars/development">
<include name="**/*.jar" />
</fileset>
</bzip2-files>
You can check the total number of arguments which are passed in command line with "$#
"
Say for Example my shell script name is hello.sh
sh hello.sh hello-world
# I am passing hello-world as argument in command line which will b considered as 1 argument
if [ $# -eq 1 ]
then
echo $1
else
echo "invalid argument please pass only one argument "
fi
Output will be hello-world
Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
fclose($file);
You'll want to put more error checking in there in case fopen()
fails, but this works to read a CSV file line by line and parse the line into an array.
This worked for me. Running android API 19 and above.
FragmentManager fragMan = getFragmentManager();
you can not put ";" in the value field of a cookie, the name that will be set is the string until the ";" in most browsers...
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.
What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.
What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.
This isn't something that can fit into a few lines of code, but this is one approach that might work for you.
To hide the navigation bar:
[[self navigationController] setNavigationBarHidden:YES animated:YES];
To show it:
[[self navigationController] setNavigationBarHidden:NO animated:YES];
Documentation for this method is available here.
To listen for a "double click" or double-tap, subclass UIView
and make an instance of that subclass your view controller's view
property.
In the view subclass, override its -touchesEnded:withEvent:
method and count how many touches you get in a duration of time, by measuring the time between two consecutive taps, perhaps with CACurrentMediaTime()
. Or test the result from [touch tapCount]
.
If you get two taps, your subclassed view issues an NSNotification
that your view controller has registered to listen for.
When your view controller hears the notification, it fires a selector that either hides or shows the navigation bar using the aforementioned code, depending on the navigation bar's current visible state, accessed through reading the navigation bar's isHidden
property.
EDIT
The part of my answer for handling tap events is probably useful back before iOS 3.1. The UIGestureRecognizer
class is probably a better approach for handling double-taps, these days.
EDIT 2
The Swift way to hide the navigation bar is:
navigationController?.setNavigationBarHidden(true, animated: true)
To show it:
navigationController?.setNavigationBarHidden(false, animated: true)
I'd like to clarify a few things:
pandas.Series.tolist()
. I'm not sure why the top voted answer
leads off with using pandas.Series.values.tolist()
since as far as I can tell, it adds syntax/confusion with no added benefit.tst[lookupValue][['SomeCol']]
is a dataframe (as stated in the
question), not a series (as stated in a comment to the question). This is because tst[lookupValue]
is a dataframe, and slicing it with [['SomeCol']]
asks for
a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you
remove the extra set of brackets, as in
tst[lookupValue]['SomeCol']
, then you are asking for just that one
column rather than a list of columns, and thus you get a series back.pandas.Series.tolist()
, so you should
definitely skip the second set of brackets in this case. FYI, if you
ever end up with a one-column dataframe that isn't easily avoidable
like this, you can use pandas.DataFrame.squeeze()
to convert it to
a series.tst[lookupValue]['SomeCol']
is getting a subset of a particular column via
chained slicing. It slices once to get a dataframe with only certain rows
left, and then it slices again to get a certain column. You can get
away with it here since you are just reading, not writing, but
the proper way to do it is tst.loc[lookupValue, 'SomeCol']
(which returns a series).ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()
Demo Code:
import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
'colB':[4,5,6]})
filter_value = 1
print "df"
print df
print type(df)
rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)
result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)
result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)
result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)
result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)
result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)
ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)
ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)
Result:
df
colA colB
0 1 4
1 2 5
2 1 6
<class 'pandas.core.frame.DataFrame'>
df['colA'] == filter_value
0 True
1 False
2 True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>
df[rows_to_keep]['colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df[rows_to_keep][['colB']]
colB
0 4
2 6
<class 'pandas.core.frame.DataFrame'>
df[rows_to_keep][['colB']].squeeze()
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[df['colA'] == filter_value, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>
df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>
Open the file for 'append' rather than 'write'.
with open('file.txt', 'a') as file:
file.write('input')
I was facing the same problem in windows.
You can change the encoding of a file with an editor such as notepad++. Just go to Encoding and select what you want.
I always prefer the Windows 1252
The join feature supported by Mongodb 3.2 and later versions. You can use joins by using aggregate query.
You can do it using below example :
db.users.aggregate([
// Join with user_info table
{
$lookup:{
from: "userinfo", // other table name
localField: "userId", // name of users table field
foreignField: "userId", // name of userinfo table field
as: "user_info" // alias for userinfo table
}
},
{ $unwind:"$user_info" }, // $unwind used for getting data in object or for one record only
// Join with user_role table
{
$lookup:{
from: "userrole",
localField: "userId",
foreignField: "userId",
as: "user_role"
}
},
{ $unwind:"$user_role" },
// define some conditions here
{
$match:{
$and:[{"userName" : "admin"}]
}
},
// define which fields are you want to fetch
{
$project:{
_id : 1,
email : 1,
userName : 1,
userPhone : "$user_info.phone",
role : "$user_role.role",
}
}
]);
This will give result like this:
{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "[email protected]",
"userName" : "admin",
"userPhone" : "0000000000",
"role" : "admin"
}
Hope this will help you or someone else.
Thanks
I have come across the same problem and have a cleaner solution. Instead of creating an empty data.frame
you can instead save your data as a named list. Once you have added all results to this list you convert it to a data.frame after.
For the case of adding features one at a time this works best.
mylist = list()
for(column in 1:10) mylist$column = rnorm(10)
mydf = data.frame(mylist)
For the case of adding rows one at a time this becomes tricky due to mixed types. If all types are the same it is easy.
mylist = list()
for(row in 1:10) mylist$row = rnorm(10)
mydf = data.frame(do.call(rbind, mylist))
I haven't found a simple way to add rows of mixed types. In this case, if you must do it this way, the empty data.frame is probably the best solution.
Below command can be used to first search the files and replace the files:
find . | xargs grep 'search string' | sed 's/search string/new string/g'
For example
find . | xargs grep abc | sed 's/abc/xyz/g'
You can use the following to programmatically center TextView
text in Kotlin:
textview.gravity = Gravity.CENTER
body {
background-image: url(http://domains.com/photo.jpeg);
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
Take a look at the jsFiddle demo
Ok, at that time got it done with the help of a friend and the code looks like this.
Sub Saving()
Dim part1 As String
Dim part2 As String
part1 = Range("C5").Value
part2 = Range("C8").Value
ActiveWorkbook.SaveAs Filename:= _
"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou
Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?
There's opencv
for python (documentation here).
import cv2
import numpy as np
img = ... # Your image as a numpy array
cv2.imwrite("filename.png", img)
useful if you need to do more processing other than saving.
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
This helped me to get uri from Gallery and convert to a file for Multipart upload
File file = FileUtils.getFile(this, fileUri);
In management studio you can set the timeout in seconds. menu Tools => Options set the field and then Ok
We were getting the same error.For us, it solved by upgrading pip version (also discussed in FAQ of OpenCV GitHub). Earlier we had pip-7.1.0, post upgrading it to "pip-9.0.2", it successfully installed.
pip install --upgrade pip
pip install opencv-python
npm install bootstrap --save
and add relevent files into angular.json
file under the style
property for css files and under scripts
for JS files.
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
....
]
PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself
Its little tricky in android studio there is no default folder for all screen size you need to create but with little trick.
i cant post image here so if still having any problem. here is tutorial..
In Visual Studio, you can't just open a .cpp
file and expect it to run. You must create a project first, or open the .cpp in some existing project.
In your case, there is no project, so there is no project to build.
Go to File --> New --> Project --> Visual C++ --> Win32 Console Application
. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".
Then, You can add .cpp
files you created outside the Visual Studio by right clicking in the Solution explorer
on folder icon "Source" and Add->Existing Item.
Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.
Then you can press ctrl+F5 to compile without debugging and can see output on console window.
I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection
, which the QueryString
property actually is, unfortunately it is internal in the .NET framework.
You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.
HttpValueCollection
extends NameValueCollection
, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString()
method to later rebuild the query string from the underlying collection.
if the autocomplete isn't working for you in Android Studio, just press File and uncheck the Power save mode, it should work fine after that. if power save mode is already unchecked then first check then uncheck them.
Simple:
public static String decToHex(int dec)
{
return Integer.toHexString(dec);
}
As mentioned here: Java Convert integer to hex integer
I'm doing a git repository statistics generator in ruby, it's called git_stats.
You can find examples generated for some repositories on project page.
Here is a list of what it can do:
If you have any idea what to add or improve please let me know, I would appreciate any feedback.
make sure you have mapped the y: drive, or copy all the files to local dir c:/local
c:/local> copy *.* c:/newfile.txt
The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.
Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool())
by filter(ItemType::isCool)
. That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter
invocation using a lambda expression with &&
.
But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.
In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.
So there is no simple answer.
The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.
¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
Please note , you might need to disable adblocks if necessary. Drag and drop off script path in visual studio doesn't work if you are using HTML pages but it does work for mvc ,asp.netwebforms. I figured this after one hour
The property
in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.
For example, to use that code you would have to have something like this in your <head
tag. <head xmlns:og="http://example.org/">
and inside the http://example.org/
there would be a specification for title
(og:title).
The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).
There are some third-party Java libraries that provide string join method, but you probably don't want to start using a library just for something simple like that. I would just create a helper method like this, which I think is a bit better than your version, It uses StringBuffer, which will be more efficient if you need to join many strings, and it works on a collection of any type.
public static <T> String join(Collection<T> values)
{
StringBuffer ret = new StringBuffer();
for (T value : values)
{
if (ret.length() > 0) ret.append(",");
ret.append(value);
}
return ret.toString();
}
Another suggestion with using Collection.toString() is shorter, but that relies on Collection.toString() returning a string in a very specific format, which I would personally not want to rely on.
Modify the DataNode class so that it implements Comparable interface.
public int compareTo(DataNode o)
{
return(degree - o.degree);
}
then just use
Collections.sort(nodeList);
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
You could also use the php native funcion get_browser()
IMPORTANT NOTE: You should have a browscap.ini file.
Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.
To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:
var spawn = require('child_process').spawn;
//kick off process of listing files
var child = spawn('ls', ['-l', '/']);
//spit stdout to screen
child.stdout.on('data', function (data) { process.stdout.write(data.toString()); });
//spit stderr to screen
child.stderr.on('data', function (data) { process.stdout.write(data.toString()); });
child.on('close', function (code) {
console.log("Finished with code " + code);
});
I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.
However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:
var execSync = require('child_process').execSync;
execSync("xterm -title RecursiveFileListing -e ls -latkR /");
This will allow you to see what your command is doing in the new terminal but still have the synchronous call.
My personal understanding of the "nonlocal" statement (and do excuse me as I am new to Python and Programming in general) is that the "nonlocal" is a way to use the Global functionality within iterated functions rather than the body of the code itself. A Global statement between functions if you will.
If it's not working why don't you try using jQuery's scrollTop method?
$("#id").scrollTop($("#id").scrollTop() + 100);
If you're looking to scroll smoothly you could use basic javascript setTimeout/setInterval function to make it scroll in increments of 1px over a set length of time.
1 Create login while connecting to the master db (in your databaseclient open a connection to the master db)
CREATE LOGIN 'testUserLogin' WITH password='1231!#ASDF!a';
2 Create a user while connecting to your db (in your db client open a connection to your database)
CREATE USER testUserLoginFROM LOGIN testUserLogin;
Please, note, user name is the same as login. It did not work for me when I had a different username and login.
3 Add required permissions
EXEC sp_addrolemember db_datawriter, 'testUser';
You may want to add 'db_datareader' as well.
list of the roles:
I was inspired by @nthpixel answer, but it did not work for my db client DBeaver.
It did not allow me to run USE [master]
and use [my-db]
statements.
https://azure.microsoft.com/en-us/blog/adding-users-to-your-sql-azure-database/
Run the query bellow in the master database connection.
SELECT A.name as userName, B.name as login, B.Type_desc, default_database_name, B.*
FROM sys.sysusers A
FULL OUTER JOIN sys.sql_logins B
ON A.sid = B.sid
WHERE islogin = 1 and A.sid is not null
Since $.browser is deprecated, here is an alternative solution:
/**
* Returns the version of Internet Explorer or a -1
* (indicating the use of another browser).
*/
function getInternetExplorerVersion()
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
if ( ver >= 8.0 )
msg = "You're using a recent copy of Internet Explorer."
else
msg = "You should upgrade your copy of Internet Explorer.";
}
alert( msg );
}
However, the reason that its deprecated is because jQuery wants you to use feature detection instead.
An example:
$("p").html("This frame uses the W3C box model: <span>" +
jQuery.support.boxModel + "</span>");
And last but not least, the most reliable way to check IE versions:
// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// If you're in IE (>=5) then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9 ...
// ie < 9 // Anything less than IE9
// ----------------------------------------------------------
// UPDATE: Now using Live NodeList idea from @jdalton
var ie = (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
The best colors I've found --which aside from being so beautiful, are very easy to look at too and do not boil my eyes-- are the ones I've found listed in this GitHub repository: VSCode Snazzy
Very Easy Installation:
Copy the contents of snazzy.json into your VS Code "settings.json" file.
(In case you don't know how to open the "settings.json" file, first hit Ctrl+Shift+P and then write Preferences: open settings(JSON) and hit enter).
Notice: For those who have tried ColorTool and it works outside VSCode but not inside VSCode, you've made no mistakes in implementing it, that's just a decision of VSCode developers for the VSCode's terminal to be colored independently.
'Date' is your index so you want to do,
print (df.index.min())
print (df.index.max())
2014-03-13 00:00:00
2014-03-31 00:00:00
you may use template reference variable and send to a method
html
<input #variable type="file" placeholder="File Name" name="filename" (change)="onChange($event, variable);">
component
onChange(event: any, element): void {
// codes
element.value = '';
}
I use -o "ProxyCommand=nc -X 5 -x proxyhost:proxyport %h %p"
ssh option to connect through socks5 proxy on OSX.
It's a bit surprising seeing multiple answers suggesting to use python
for this task, as there's no need to write a multi-line program for this.
Standard Unix tools like sed
, awk
or perl
can achieve this easily straight from the command-line.
e.g anywhere you have perl
(Windows, Mac, Linux) the following should achieve what the OP asked:
perl -i -pe 's/[ \t]+$//;' files...
Explanation of the arguments to perl
:
-i # run the edit "in place" (modify the original file)
-p # implies a loop with a final print over every input line
-e # next arg is the perl expression to apply (to every line)
s/[ \t]$//
is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.
Advantages:
Edit:
Newer versions of
perl
support\h
(any horizontal-space character), so the solution becomes even shorter:
perl -i -pe 's/\h+$//;' files...
More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO
with BAR
, you may always use this generic template:
perl -i -pe 's/FOO/BAR/' files...
Heres the Swift version:
myButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
npm config set registry https://registry.npmjs.org/
this is the only solution for me.
This seems to work only for some characters ... including special characters for German, Portuguese, French. However, I ran into trouble with Russian, Hindi and Mandarin characters. These are not converted to Properties format 'native2ascii', instead get saved with ?? ?? ??
The only way I could get my app to display these characters correctly is by putting them in the properties file translated to UTF-8 format - as \u0915 instead of ?, or \u044F instead of ?.
Any advice?
You can use parentheses to override rules of precedence.
If your database StartTime = 07:00:00
and endtime = 14:00:00
, and both are time type. Your query to get the time difference would be:
SELECT TIMEDIFF(Time(endtime ), Time(StartTime )) from tbl_name
If your database startDate = 2014-07-20 07:00:00
and endtime = 2014-07-20 23:00:00
, you can also use this query.
I can't reproduce your problem. I get the expected result.
How exactly are you using mb_detect_encoding()
to verify your string is in fact UTF-8?
If I simply call mb_detect_encoding($input)
on both a UTF-8 and ISO-8859-1 encoded version of your string, both of them return "UTF-8", so that function isn't particularly reliable.
iconv()
gives me a PHP "notice" when it gets the wrongly encoded string and only echoes "F", but that might just be because of different PHP/iconv settings/versions (?).
I suggest to you try calling mb_check_encoding($input, "utf-8")
first to verify that your string really is UTF-8. I think it probably isn't.
UINavigationBar.appearance().barTintColor = UIColor(colorLiteralRed: 51/255, green: 90/255, blue: 149/255, alpha: 1)
This will set your navigation bar color like Facebook bar color :)
You can use the function difftime
. It returns the difference between two given time_t
values, the output value is double
(see difftime documentation).
time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0);
printf("%g",actual_time_sec);
removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.
http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html
I was searching for a similar solution and found this one use full.
var es;
function startTask() {
es = new EventSource('yourphpfile.php');
//a message is received
es.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
console.log(result.message);
if(e.lastEventId == 'CLOSE') {
console.log('closed');
es.close();
var pBar = document.getElementById('progressor');
pBar.value = pBar.max; //max out the progress bar
}
else {
console.log(response); //your progress bar action
}
});
es.addEventListener('error', function(e) {
console.log('error');
es.close();
});
}
and your server outputs
header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
function send_message($id, $message, $progress) {
$d = array('message' => $message , 'progress' => $progress); //prepare json
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode($d) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
sleep(1);
}
send_message('CLOSE', 'Process complete');
While I agree with Tim and Oben Sonne that you should use an XML library, there are ways to still manipulate it as a simple string object.
I likely would not try to use a single file pointer for what you are describing, and instead read the file into memory, edit it, then write it out.:
inFile = open('file.xml', 'r')
data = inFile.readlines()
inFile.close()
# some manipulation on `data`
outFile = open('file.xml', 'w')
outFile.writelines(data)
outFile.close()
You can use inbuilt library pickle
This library allows you to save any object in python to a file
This library will maintain the format as well
import pickle
with open('/content/list_1.txt', 'wb') as fp:
pickle.dump(list_1, fp)
you can also read the list back as an object using same library
with open ('/content/list_1.txt', 'rb') as fp:
list_1 = pickle.load(fp)
reference : Writing a list to a file with Python
Probably not the most efficient code, but here it goes:
$dateElements = explode('-', $dateValue);
$year = $dateElements[0];
echo $year; //2012
switch ($dateElements[1]) {
case '01' : $mo = "January";
break;
case '02' : $mo = "February";
break;
case '03' : $mo = "March";
break;
.
.
.
case '12' : $mo = "December";
break;
}
echo $mo; //January
The part within the lock statement can only be executed by one thread, so all other threads will wait indefinitely for it the thread holding the lock to finish. This can result in a so-called deadlock.
l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
Python 2:
print ', '.join('{:0.2f}'.format(i) for i in l)
Python 3:
print(', '.join('{:0.2f}'.format(i) for i in l))
Output:
9.00, 0.05, 0.03, 0.01, 0.06, 0.08
http://codepen.io/Edo_B/pen/cLbrt
Using:
that's it.
I also believe this could be done dynamically for any screen if using canvas to copy the current dom and blurring it.
Add the following in the textview in XML.
android:scrollbars="vertical"
And finally, add
textView.setMovementMethod(new ScrollingMovementMethod());
in the Java file.
The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:
% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
extracting ikernel.dll
extracting IsProBENT.tlb
....
extracting IScript.dll
extracting iKernel.rgs
All done, no errors.
Always prefer to use the language features over some additional tools like preprocessor.
ES.31: Don't use macros for constants or "functions"
Macros are a major source of bugs. Macros don't obey the usual scope and type rules. Macros don't obey the usual rules for argument passing. Macros ensure that the human reader sees something different from what the compiler sees. Macros complicate tool building.
From C++ Core Guidelines
Perhaps you want to change your output record separator to linefeed with:
local $\ = "\n";
$ perl -e 'print q{hello};print q{goodbye}' | od -c
0000000 h e l l o g o o d b y e
0000014
$ perl -e '$\ = qq{\n}; print q{hello};print q{goodbye}' | od -c
0000000 h e l l o \n g o o d b y e \n
0000016
Update: my answer speaks to capability rather than advisability. I don't regard adding "\n" at the end of lines to be a "pesky" chore, but if someone really wants to avoid them, this is one way. If I had to maintain a bit of code that uses this technique, I'd probably refactor it out pronto.
myWindow.Activate();
Attempts to bring the window to the foreground and activates it.
That should do the trick, unless I misunderstood and you want Always on Top behavior. In that case you want:
myWindow.TopMost = true;
@Test(expected = Exception.class)
Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.
For
@Test
Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.
.help will show you all the options. Do .exit in this case
Other than win32, if your company had set up you web outlook, you can also try PYTHON REST API, which is officially made by Microsoft. (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)
You could sort the array first (Ascending by default) and then apply np.flip() (https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html)
FYI It works with datetime objects as well.
Example:
x = np.array([2,3,1,0])
x_sort_asc=np.sort(x)
print(x_sort_asc)
>>> array([0, 1, 2, 3])
x_sort_desc=np.flip(x_sort_asc)
print(x_sort_desc)
>>> array([3,2,1,0])
The following gives you list of operating system users sorted by number of connections, which is useful when looking for excessive resource usage.
select osuser, count(*) as active_conn_count
from v$session
group by osuser
order by active_conn_count desc
Here you can find my my implementation, you can limit the ram usage by changing the "buffer" variable, there is a bug that the program prints an empty line in the beginning.
And also ram usage may be increase if there is no new lines for more than buffer bytes, "leak" variable will increase until seeing a new line ("\n").
This is also working for 16 GB files which is bigger then my total memory.
import os,sys
buffer = 1024*1024 # 1MB
f = open(sys.argv[1])
f.seek(0, os.SEEK_END)
filesize = f.tell()
division, remainder = divmod(filesize, buffer)
line_leak=''
for chunk_counter in range(1,division + 2):
if division - chunk_counter < 0:
f.seek(0, os.SEEK_SET)
chunk = f.read(remainder)
elif division - chunk_counter >= 0:
f.seek(-(buffer*chunk_counter), os.SEEK_END)
chunk = f.read(buffer)
chunk_lines_reversed = list(reversed(chunk.split('\n')))
if line_leak: # add line_leak from previous chunk to beginning
chunk_lines_reversed[0] += line_leak
# after reversed, save the leakedline for next chunk iteration
line_leak = chunk_lines_reversed.pop()
if chunk_lines_reversed:
print "\n".join(chunk_lines_reversed)
# print the last leaked line
if division - chunk_counter < 0:
print line_leak
StartDate = moment(StartDate).format('MM-YYYY');
...and MySQL date format:
StartDate = moment(StartDate).format('YYYY-MM-DD');
ssh-keygen -R [hostname]
Example with an ip address/hostname would be:
ssh-keygen -R 168.9.9.2
This will update the offending of your host from the known_hosts. You can also provide the path of the known_hosts with -f flag.
From the command line, .exit
is what you want:
$ node
> .exit
$
It's documented in the REPL docs. REPL (Read-Eval-Print-Loop) is what the Node command line is called.
From a normal program, use process.exit([code])
.
You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.
For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns
. For example, mash up friend of a friend with vCard, etc.
myDataTable.Columns.Contains("col_name")
I'm assuming you're using Windows, and GitBASH.
You can just delete the folder "C:...\project" with no adverse effects.
Then in git bash, you can do cd c\:
. This changes the directory you're working in to C:\
Then you can do git clone [url]
This will create a folder called "project" on C:\ with the contents of the repo.
If you'd like to name it something else, you can do
git clone [url] [something else]
For example
cd c\:
git clone [email protected]:username\repo.git MyRepo
This would create a folder at "C:\MyRepo" with the contents of the remote repository.
auto: The browser sets the margin. The result of this is dependant of the browser
margin:0 auto specifies
* top and bottom margins are 0
* right and left margins are auto
as an alternative syntax you can write foreach loops like so
foreach($arr as $item):
//do stuff
endforeach;
This type of syntax is typically used when php is being used as a templating language as such
<?php foreach($arr as $item):?>
<!--do stuff -->
<?php endforeach; ?>
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
If you have a Decimal or similar numeric type, you can use:
Math.Round(myNumber, 2)
EDIT: So, in your case, it would be:
Public Class Form1
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
End Sub
End Class
At my day job I sit behind a corporate firewall protecting and caching web traffic (among other things). For the most part it stays out of the way. But sometimes it rears its ugly head and stands firmly in the path of what I am trying to do.
Earlier this week I was trying to look at a cool new general validation system for ColdFusion called Validat, put out by the great guys at Alagad. They don't have a download on the RIAForge site yet, but the files are available via SVN. I loaded up the subclipse plugin into my Eclipse, restarted and began adding the Validat SVN repository. I started getting errors abou the "RA layer request failed" and "svn: PROPFIND request failed on /Validat/trunk", followed by an error about not being able to connect to the SVN server.
I already had Eclipse setup with my proxy settings, so I thought I was doing something wrong or Alagad didn't actually have the subversion repository up-and-available. After going home that night, I tried it from home and wa-la it worked. Stupid proxy server! So the subclipse plugin won't use the Eclipse proxy settings. (Can that be fixed please!). After digging around the subclipse help site and being redirected to the collab.net help, then unproductively searching through the eclipse workspace, plugins, and configuration folders for the settings file, I was finally able to figure out how to set up subclipse to use the proxy server.
In my Windows development environment, I opened the following file: C:\Documents and Settings\MyUserId\Application Data\Subversion\servers in my favorite text editor. Near the bottom of that file is a [global] section with http-proxy-host and http-proxy-port settings. I uncommented those two lines, modified them for my corporate proxy server, went back to the SVN Repository view in Eclipse, refreshed the Validat repository and Boom! it worked!
from http://www.mkville.com/blog/index.cfm/2007/11/8/Using-Subclipse-Behind-a-Proxy-Server
You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull
or $pullAll
operators to remove the item from the array :
Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )
(you can also use updateMany for multiple documents)
http://docs.mongodb.org/manual/reference/operator/update/pullAll/
You can do it without any interruption, with the new (Git 2.0 Q2 2014) setting gc.autodetach
.
See commit 4c4ac4d and commit 9f673f9 (Nguy?n Thái Ng?c Duy, aka pclouds):
gc --auto
takes time and can block the user temporarily (but not any less annoyingly).
Make it run in background on systems that support it.
The only thing lost with running in background is printouts. Butgc output
is not really interesting.
You can keep it in foreground by changinggc.autodetach
.
Since that 2.0 release, there was a bug though: git 2.7 (Q4 2015) will make sure to not lose the error message.
See commit 329e6e8 (19 Sep 2015) by Nguy?n Thái Ng?c Duy (pclouds
).
(Merged by Junio C Hamano -- gitster
-- in commit 076c827, 15 Oct 2015)
gc
: save log from daemonizedgc --auto
and print it next timeWhile commit 9f673f9 (
gc
: config option for running--auto
in background - 2014-02-08) helps reduce some complaints about 'gc --auto
' hogging the terminal, it creates another set of problems.The latest in this set is, as the result of daemonizing,
stderr
is closed and all warnings are lost. This warning at the end ofcmd_gc()
is particularly important because it tells the user how to avoid "gc --auto
" running repeatedly.
Because stderr is closed, the user does not know, naturally they complain about 'gc --auto
' wasting CPU.Daemonized
gc
now savesstderr
to$GIT_DIR/gc.log
.
Followinggc --auto
will not run andgc.log
printed out until the user removesgc.log
.
Do you know sprintf
? It's basically the same thing with fprintf
. The first argument is the destination (the file in the case of fprintf
i.e. stderr
), the second argument is the format string, and the rest are the arguments as usual.
I also recommend this printf
(and family) reference.
You can pass the inline handler the this
keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
Quick and Easy using lodash - var array = ["12346","12347","12348","12349","12349"]; console.log(_.uniqWith(array,_.isEqual));
The JavaScript function:
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
To use this function:
capitalizedString = someString.toLowerCase().capitalize();
Also, this would work on multiple words string.
To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.
You can convert .csv file to UTF-8 with BOM via Notepad++:
Encoding
?Convert to UTF-8
.File
?Save
.Worked in Microsoft Excel 2013 (15.0.5093.1000) MSO (15.0.5101.1000) 64-bit from Microsoft Office Professional Plus 2013 on Windows 8.1 with locale for non-Unicode programs set to "German (Germany)".
<script type="text/javascript">
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
</script>
<input type="text" required="" name="partno" class="form-control" placeholder="Enter a Part No*" onkeydown="upperCaseF(this)">
As @Raf Z commented on this question, dplyr now has mutate_if. Super useful, simple and readable.
> str(df)
'data.frame': 5 obs. of 5 variables:
$ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
$ B: int 1 2 3 4 5
$ C: logi TRUE TRUE FALSE FALSE TRUE
$ D: chr "a" "b" "c" "d" ...
$ E: chr "A a" "B b" "C c" "D d" ...
> df <- df %>% mutate_if(is.character,as.factor)
> str(df)
'data.frame': 5 obs. of 5 variables:
$ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
$ B: int 1 2 3 4 5
$ C: logi TRUE TRUE FALSE FALSE TRUE
$ D: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
$ E: Factor w/ 5 levels "A a","B b","C c",..: 1 2 3 4 5
FreeGor version converted to Swift 3.0
func removeOldFileIfExist() {
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0]
let fileName = "filename.jpg"
let filePath = NSString(format:"%@/%@", dirPath, fileName) as String
if FileManager.default.fileExists(atPath: filePath) {
do {
try FileManager.default.removeItem(atPath: filePath)
print("User photo has been removed")
} catch {
print("an error during a removing")
}
}
}
}
In your AppDelegate, in the didRegisterForRemoteNotificationsWithDeviceToken
method:
Updated for Swift:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("\(deviceToken.reduce("") { $0 + String(format: "%02.2hhx", arguments: [$1]) })")
}
@Stebra See this example. This may help you.
public class CustomerInfo
{
@SerializedName("customerid")
public String customerid;
@SerializedName("picture")
public String picture;
@SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
Also you can position the other window before withdrawing it so that you position your message
#!/usr/bin/env python
from Tkinter import *
import tkMessageBox
window = Tk()
window.wm_withdraw()
#message at x:200,y:200
window.geometry("1x1+200+200")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y")
tkMessageBox.showerror(title="error",message="Error Message",parent=window)
#centre screen message
window.geometry("1x1+"+str(window.winfo_screenwidth()/2)+"+"+str(window.winfo_screenheight()/2))
tkMessageBox.showinfo(title="Greetings", message="Hello World!")
You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK
XSD files are used to validate that XML files conform to a certain format.
In that respect they are similar to DTDs that existed before them.
The main difference between XSD and DTD is that XSD is written in XML and is considered easier to read and understand.
A workaround and a handy tool:
CSS3Pie uses .htc files and the behavior property to implement CSS3 into IE 6 - 8.
Modernizr is a bit of javascript that will put classes on your html element, allowing you to serve different style definitions to different browsers based on their capabilities.
Obviously, these both add more overhead, but with IE9 due to only run on Vista/7 we might be stuck for quite awhile. As of August 2010 Windows XP still accounts for 48% of web client OSes.
This is not possible with css, but I have used one css trick in one of my website, please check if this works for you.
The trick is: wrap the input box with a div and make it relative, place a transparent image inside the div and make it absolute over the input text box, so that no one can edit it.
css
.txtBox{
width:250px;
height:25px;
position:relative;
}
.txtBox input{
width:250px;
height:25px;
}
.txtBox img{
position:absolute;
top:0;
left:0
}
html
<div class="txtBox">
<input name="" type="text" value="Text Box" />
<img src="http://dev.w3.org/2007/mobileok-ref/test/data/ROOT/GraphicsForSpacingTest/1/largeTransparent.gif" width="250" height="25" alt="" />
</div>
To see just the symlinks themselves, you can use
find -L /path/to/dir/ -xtype l
while if you want to see also which files they target, just append an ls
find -L /path/to/dir/ -xtype l -exec ls -al {} \;
As pointed out by @Jayan in another post, the solution was to do the following
import jenkins.model.*
jenkins = Jenkins.instance
Then I was able to do the rest of my scripting the way it was.
In a conda
environment, this is what solved my problem (I was missing cudart64-100.dll
:
Downloaded it from dll-files.com/CUDART64_100.DLL
Put it in my conda environment at
C:\Users\<user>\Anaconda3\envs\<env name>\Library\bin
That's all it took! You can double check if it's working:
import tensorflow as tf
tf.config.experimental.list_physical_devices('GPU')
"Any" works well. Just make sure that the any keyword is on the right side of the equal to sign i.e. is present after the equal to sign.
Below statement will throw error: ERROR: syntax error at or near "any"
select 1 where any('{hello}'::text[]) = 'hello';
Whereas below example works fine
select 1 where 'hello' = any('{hello}'::text[]);
If you want an alternative to Array.concat
in ECMAScript 2015 (a.k.a. ES6, ES2015) that, like it, does not modify the array but returns a new array you can use the spread operator like so:
var arr = [1];_x000D_
var newItems = [2, 3];_x000D_
var newerItems = [4, 5];_x000D_
var newArr = [...arr, ...newItems, ...newerItems];_x000D_
console.log(newArr);
_x000D_
Note this is different than the push
method as the push
method mutates/modifies the array.
If you want to see if certain ES2015 features work in your browser check Kangax's compatibility table.
You can also use Babel or a similar transpiler if you do not want to wait for browser support and want to use ES2015 in production.
If you frequently need to access the Nth element of a sequence, std::list
, which is implemented as a doubly linked list, is probably not the right choice. std::vector
or std::deque
would likely be better.
That said, you can get an iterator to the Nth element using std::advance
:
std::list<Object> l;
// add elements to list 'l'...
unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
std::list<Object>::iterator it = l.begin();
std::advance(it, N);
// 'it' points to the element at index 'N'
}
For a container that doesn't provide random access, like std::list
, std::advance
calls operator++
on the iterator N
times. Alternatively, if your Standard Library implementation provides it, you may call std::next
:
if (l.size() > N)
{
std::list<Object>::iterator it = std::next(l.begin(), N);
}
std::next
is effectively wraps a call to std::advance
, making it easier to advance an iterator N
times with fewer lines of code and fewer mutable variables. std::next
was added in C++11.
It will overflow and wrap around to Long.MIN_VALUE
.
Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.
echo $VAR_REMOTEROOTPASS | ssh -tt -i $PATH_TO_KEY/id_mykey $VAR_REMOTEUSER@$varRemoteHost
echo \"$varCommand\" | sudo bash
It's pandas
label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label
The boolean array is basically a selection method using a mask.
I agree with Cade Roux.
This article should get you on the right track:
One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits.
Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused.
e.g. imagine you search a table on three columns
state, county, zip.
Then an index with state, county, zip. will be used in all three of these searches.
If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful.
You could then create an index on Zip alone that would be used in this instance.
By the way We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state'
I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's.
The article will help a lot. :-)
There is no work-around for this aside from ditching the select
element.
Also internationalization.
I fooled around with this some a while back. Did this in my model:
[Display(Name = "XXX", ResourceType = typeof(Labels))]
I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.
In there I had key = XXX, value = "meaningful string in that culture."
To enter keys using Selenium, first you need to import the following library:
import org.openqa.selenium.Keys
then add this code where you want to enter the key
WebElement.sendKeys(Keys.RETURN);
You can replace RETURN with any key from the list according to your requirement.
I use lambdas to avoid code duplication. It would make the function easily comprehensible Eg:
def a_func()
...
if some_conditon:
...
call_some_big_func(arg1, arg2, arg3, arg4...)
else
...
call_some_big_func(arg1, arg2, arg3, arg4...)
I replace that with a temp lambda
def a_func()
...
call_big_f = lambda args_that_change: call_some_big_func(arg1, arg2, arg3, args_that_change)
if some_conditon:
...
call_big_f(argX)
else
...
call_big_f(argY)
You can write case
expressions in two different ways in Ruby:
if
statementscase
and each when
clause is compared to the target.age = 20
case
when age >= 21
puts "display something"
when 1 == 0
puts "omg"
else
puts "default condition"
end
or:
case params[:unknown]
when /Something/ then 'Nothing'
when /Something else/ then 'I dont know'
end
You can parse dates from a custom format (as of PHP 5.3) with DateTime::createFromFormat
$timestamp = DateTime::createFromFormat('!d/m/Y', '23/05/2010')->getTimestamp();
(Aside: The !
is used to reset non-specified values to the Unix timestamp, ie. the time will be midnight.)
If you do not want to (or cannot) use PHP 5.3, then a full list of available date/time formats which strtotime accepts is listed on the Date Formats manual page. That page more thoroughly describes the fact that m/d/Y
is inferred over d/m/Y
(but you can, as mentioned in the answers here, use d-m-Y
, d.m.Y
or d\tm\tY
).
In the past, I've also resorted to the quicky str_replace
mentioned in another answer, as well as self-parsing the date string into another format like
$subject = '23/05/2010';
$formatted = vsprintf('%3$04d/%2$02d/%1$02d', sscanf($subject,'%02d/%02d/%04d'));
$timestamp = strtotime($formatted);
You can use the excecl command
int execl(const char *path, const char *arg, ...);
Like shown here
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
int main (void) {
return execl ("/bin/pwd", "pwd", NULL);
}
The second argument will be the name of the process as it will appear in the process table.
Alternatively, you can use the getcwd() function to get the current working directory:
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255
int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';
if(getcwd(wd, MAX-1) == NULL) {
printf ("Can not get current working directory\n");
}
else {
printf("%s\n", wd);
}
return 0;
}
Make SymbolIndexer( const SymbolIndexer& )
private. If you're assigning to a reference, you're not copying.
You don't need a regex for this. Use tr:
"some text\nandsomemore".tr("\n","")
I did this in my local environment. Wasn't difficult but obviously it was done in "unsupported" way.
To do the downgrade you need just to download php 5.3 from http://php.net/releases/ (zip archive), than go to xampp folder and copy subfolder "php" to e.g. php5.5 (just for backup). Than remove content of the folder php and unzip content of zip archive downloaded from php.net. The next step is to adjust configuration (php.ini) - you can refer to your backed-up version from php 5.5. After that just run xampp control utility - everything should work (at least worked in my local environment). I didn't found any problem with such installation, although I didn't tested this too intensively.
You can make all warnings being treated as such using -Wno-error
. You can make specific warnings being treated as such by using -Wno-error=<warning name>
where <warning name>
is the name of the warning you don't want treated as an error.
If you want to entirely disable all warnings, use -w
(not recommended).
Source: http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html
While astype
is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr
in the following examples:
>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1., 2., 3., 4.])
int*
functions from NumPy>>> np.int64(arr)
array([1, 2, 3, 4])
>>> np.int_(arr)
array([1, 2, 3, 4])
*array
functions themselves:>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])
astype
method (that was already mentioned but for completeness sake):>>> arr.astype(int)
array([1, 2, 3, 4])
Note that passing int
as dtype to astype
or array
will default to a default integer type that depends on your platform. For example on Windows it will be int32
, on 64bit Linux with 64bit Python it's int64
. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32
or np.int64
.
I would use $_POST
, and $_GET
because differently from $_REQUEST
their content is not influenced by variables_order
.
When to use $_POST
and $_GET
depends on what kind of operation is being executed. An operation that changes the data handled from the server should be done through a POST request, while the other operations should be done through a GET request. To make an example, an operation that deletes a user account should not be directly executed after the user click on a link, while viewing an image can be done through a link.
I'm not sure I quite understand the question but if you want to search objects on the database for a particular search string try:
SELECT owner, name, type, line, text
FROM dba_source
WHERE instr(UPPER(text), UPPER(:srch_str)) > 0;
From there if you need any more info you can just look up the object / line number.
Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.
That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.
for i in {1..3}; do cat "$i.txt" >> 0.txt; done
I found this page because I needed to join 952 files together into one. I found this to work much better if you have many files. This will do a loop for however many numbers you need and cat each one using >> to append onto the end of 0.txt.
Edit:
as brought up in the comments:
cat {1..3}.txt >> 0.txt
or
cat {0..3}.txt >> all.txt
The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:
Deny from all
If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/
, set the server to serve files from /srv/YourApp/app/
and put the includes in /srv/YourApp/includes
, so there literally isn't any URL that can access them.
I tried to solve this issue.
My answer is here.
"DynamicHeader" - http://dynamicheader.codeplex.com/, https://nuget.org/packages/DynamicHeader
For example, _Layout.cshtml is:
<head>
@Html.DynamicHeader()
</head>
...
And, you can register .js and .css files to "DynamicHeader" anywhere you want.
For example, the code block in AnotherPartial.cshtml is:
@{
DynamicHeader.AddSyleSheet("~/Content/themes/base/AnotherPartial.css");
DynamicHeader.AddScript("~/some/myscript.js");
}
Result HTML output for this sample is:
<html>
<link href="/myapp/Content/themes/base/AnotherPartial.css" .../>
<script src="/myapp/some/myscript.js" ...></script>
</html>
...
Right!!! after much hair pulling I've finally worked out how to make this work properly.
It seems as though fragment [3] is not removed from the view when back is pressed so you have to do it manually!
First of all, dont use replace() but instead use remove and add separately. It seems as though replace() doesnt work properly.
The next part to this is overriding the onKeyDown method and remove the current fragment every time the back button is pressed.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
if (getSupportFragmentManager().getBackStackEntryCount() == 0)
{
this.finish();
return false;
}
else
{
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
return false;
}
}
return super.onKeyDown(keyCode, event);
}
public void removeCurrentFragment()
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.detailFragment);
String fragName = "NONE";
if (currentFrag!=null)
fragName = currentFrag.getClass().getSimpleName();
if (currentFrag != null)
transaction.remove(currentFrag);
transaction.commit();
}
Hope this helps!
this solved my problem
android:adjustViewBounds="true"
android:scaleType="fitXY"
Refactoring:
new WindowsMediaPlayer() { URL = "MyMusic.mp3" }.controls.play();
If you enabled two-factor authentication in your Github account you won't be able to push via HTTPS using your accounts password. Instead you need to generate a personal access token. This can be done in the application settings of your Github account. Using this token as your password should allow you to push to your remote repository via HTTPS. Use your username as usual.
https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/
You may also need to update the origin for your repository if set to https:
git remote -v
git remote remove origin
git remote add origin [email protected]:user/repo.git
$ git config --get-regexp alias
class Grandpa
{
public function __construct()
{
echo"Hello Kiddo";
}
}
class Papa extends Grandpa
{
public function __construct()
{
}
public function CallGranddad()
{
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
}
public function needSomethingFromGrandDad
{
parent::CallGranddad();
}
}
If you're going to build complex user interfaces in the browser then you will probably find yourself eventually inventing most of the pieces that make up frameworks like Backbone.js and Sammy.js. So the question is, are you building something complicated enough in the browser to merit using it (so you don't end up inventing the same thing yourself).
If what you plan to build is something where the UI regularly changes how it displays but does not go to the server to get entire new pages then you probably need something like Backbone.js or Sammy.js. The cardinal example of something like that is Google's GMail. If you've ever used it you'll notice that it downloads one big chunk of HTML, CSS, and JavaScript when you first log in and then after that everything happens in the background. It can move between reading an email and processing the inbox and searching and back through all of them again without ever asking for a whole new page to be rendered.
It's that kind of app that these frameworks excel at making easier to develop. Without them you'll either end up glomming together a diverse set of individual libraries to get parts of the functionality (for example, jQuery BBQ for history management, Events.js for events, etc.) or you'll end up building everything yourself and having to maintain and test everything yourself as well. Contrast that with something like Backbone.js that has thousands of people watching it on Github, hundreds of forks where people may be working on it, and hundreds of questions already asked and answered here on Stack Overflow.
But none of it is of any importance if what you plan to build is not complicated enough to be worth the learning curve associated with a framework. If you're still building PHP, Java, or something else sites where the back end server is still doing all the heavy lifting of building the web pages upon request by the user and JavaScript/jQuery is just icing upon that process, you aren't going to need or are not yet ready for Backbone.js.
for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like
class Base
{
public:
virtual void foo(int a, const int b) = 0;
}
class D: public Base
{
public:
void foo(int a, int b){};
}
<?php
$items = DB::table('course')->get()->pluck('name','id');
$selectID = 3;
?>
<div class="form-group">
{{ Form::label('course_title', 'Course Title') }}
{!! Form::select('myselect', $items, $select, ['class' => 'form-control']) !!}
</div>
This show similar types of following options :
<select name="myselect" id="myselect">
<option value="1">Computer Introduction</option>
<option value="2">Machine Learning</option>
<option value="3" selected='selected'>Python Programming</option>
<option value="4">Networking Fundamentals</option>
.
.
.
.
</select>
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
In summary, I've fixed the problem by putting the database file (* .db) in a subfolder.
i have same problem, and i try this:
This worked for me, and hope will help you.
*sorry for my bad english
Credits to jose.angel.jimenez and Gus Bus.
For the "oneliner" fans…
If you want the first element of a list or if you want a default value if the list is empty try:
liste = ['a', 'b', 'c']
value = (liste[0:1] or ('default',))[0]
print(value)
returns a
and
liste = []
value = (liste[0:1] or ('default',))[0]
print(value)
returns default
Examples for other elements…
liste = ['a', 'b', 'c']
print(liste[0:1]) # returns ['a']
print(liste[1:2]) # returns ['b']
print(liste[2:3]) # returns ['c']
print(liste[3:4]) # returns []
With default fallback…
liste = ['a', 'b', 'c']
print((liste[0:1] or ('default',))[0]) # returns a
print((liste[1:2] or ('default',))[0]) # returns b
print((liste[2:3] or ('default',))[0]) # returns c
print((liste[3:4] or ('default',))[0]) # returns default
Possibly shorter:
liste = ['a', 'b', 'c']
value, = liste[:1] or ('default',)
print(value) # returns a
It looks like you need the comma before the equal sign, the equal sign and the latter parenthesis.
More general:
liste = ['a', 'b', 'c']
f = lambda l, x, d: l[x:x+1] and l[x] or d
print(f(liste, 0, 'default')) # returns a
print(f(liste, 1, 'default')) # returns b
print(f(liste, 2, 'default')) # returns c
print(f(liste, 3, 'default')) # returns default
Tested with Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)
Seems like one of your values, with a property key of 'value' is undefined. Test that i1
, i2
and __i
are defined before executing the if statements:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}
Why use a constructor and prototyping for a single object?
The above is equivalent to:
var earth= {
someMethod: function () {
if (console && console.log)
console.log('some method');
}
};
privateFunction1();
privateFunction2();
return {
Person: Constructors.Person,
PlanetEarth: earth
};
This is a slight variation that worked better for me.
$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"
$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open($CSV)
$Worksheets = $Workbooks.worksheets
$Workbook.SaveAs($XLS,1)
$Workbook.Saved = $True
$xl.Quit()
Found how.
First, configure the text of titleLabel
(because of styles, i.e, bold, italic, etc). Then, use setTitleEdgeInsets
considering the width of your image:
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont boldSystemFontOfSize:10.0]];
// Left inset is the negative of image width.
[button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -image.size.width, -25.0, 0.0)];
After that, use setTitleEdgeInsets
considering the width of text bounds:
[button setImage:image forState:UIControlStateNormal];
// Right inset is the negative of text bounds width.
[button setImageEdgeInsets:UIEdgeInsetsMake(-15.0, 0.0, 0.0, -button.titleLabel.bounds.size.width)];
Now the image and the text will be centered (in this example, the image appears above the text).
Cheers.
As of Python 3.3, you can use the find_spec() method
import importlib.util
# For illustrative purposes.
package_name = 'pandas'
spec = importlib.util.find_spec(package_name)
if spec is None:
print(package_name +" is not installed")
The reason is that your are defining your imageSegment
outside of a function in your source code (static variable).
In such cases, the initialization cannot include execution of code, like calling a function or allocation a class. Initializer must be a constant whose value is known at compile time.
You can then initialize your static variable inside of your init
method (if you postpone its declaration to init).
This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up
<a href="\\server\folder\path" target="_blank">click</a>
If there is a need in a fancy UI - then it will barely serve as a solution.
If all is you need is convertion from ListItem to your type T you can implement this convertion in T class as conversion operator.
public class T
{
public static implicit operator T(ListItem listItem) => /* ... */;
}
public static string GetAllItems(...)
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(listItem);
}
...
}
This is not valid TypeScript code. You can not have method invocations in the body of a class.
// INVALID CODE
export class AppComponent {
public n: number = 1;
setTimeout(function() {
n = n + 10;
}, 1000);
}
Instead move the setTimeout
call to the constructor
of the class. Additionally, use the arrow function =>
to gain access to this
.
export class AppComponent {
public n: number = 1;
constructor() {
setTimeout(() => {
this.n = this.n + 10;
}, 1000);
}
}
In TypeScript, you can only refer to class properties or methods via this
. That's why the arrow function =>
is important.
I also wanted to load any iframe inside modal window. What I did was, Created an iframe inside Modal and passing the source of target iframe to the iframe inside the modal.
function closeModal() {_x000D_
$('#modalwindow').hide();_x000D_
var modalWindow = document.getElementById('iframeModalWindow');_x000D_
modalWindow.src = "";_x000D_
}
_x000D_
.modal {_x000D_
z-index: 3;_x000D_
display: none;_x000D_
padding-top: 5%;_x000D_
padding-left: 5%;_x000D_
position: fixed;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow: auto;_x000D_
background-color: rgb(51, 34, 34);_x000D_
background-color: rgba(0, 0, 0, 0.4)_x000D_
}
_x000D_
<!-- Modal Window -->_x000D_
<div id="modalwindow" class="modal">_x000D_
<div class="modal-header">_x000D_
<button type="button" style="margin-left:80%" class="close" onclick=closeModal()>×</button>_x000D_
</div>_x000D_
<iframe id="iframeModalWindow" height="80%" width="80%" src="" name="iframe_modal"></iframe>_x000D_
</div>
_x000D_
I need to select every production with a category that doesn't contain "Business"
Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as
//production[category[not(contains(., 'Business'))]]
rather than
//production[not(contains(category, 'Business'))]
The latter selects every production whose first category
child doesn't contain "Business". The two XPath expressions will behave differently when a production
has no category
children, or more than one.
It doesn't make any difference in practice as long as every <production>
has exactly one <category>
child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').
If your dates
column does not contain time information, you could get away with:
WHERE dates BETWEEN '20121211' and '20121213'
However, given your dates
column is actually datetime, you want this
WHERE dates >= '20121211'
AND dates < '20121214' -- i.e. 00:00 of the next day
Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:
WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'
Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.
I posted a fix for this here
You can use this function to modify JSON.stringify
to encode arrays
, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
May be you would find a complete list through the CJK Unicode FAQ (which does include "Chinese, Japanese, and Korean" characters)
The "East Asian Script" document does mention:
Blocks Containing Han Ideographs
Han ideographic characters are found in five main blocks of the Unicode Standard, as shown in Table 12-2
Table 12-2. Blocks Containing Han Ideographs
Block Range Comment
CJK Unified Ideographs 4E00-9FFF Common
CJK Unified Ideographs Extension A 3400-4DBF Rare
CJK Unified Ideographs Extension B 20000-2A6DF Rare, historic
CJK Unified Ideographs Extension C 2A700–2B73F Rare, historic
CJK Unified Ideographs Extension D 2B740–2B81F Uncommon, some in current use
CJK Unified Ideographs Extension E 2B820–2CEAF Rare, historic
CJK Compatibility Ideographs F900-FAFF Duplicates, unifiable variants, corporate characters
CJK Compatibility Ideographs Supplement 2F800-2FA1F Unifiable variants
Note: the block ranges can evolve over time: latest is in CJK Unified Ideographs.
See also Wikipedia:
You should use TryParse
- Parse
throws an exception if the string is not a valid number - e.g. if you want to test for a valid integer:
int v;
if (Int32.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
If you want to test for a valid floating-point number:
double v;
if (Double.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
Note also that Double.TryParse
has an overloaded version with extra parameters specifying various rules and options controlling the parsing process - e.g. localization ('.' or ',') - see http://msdn.microsoft.com/en-us/library/3s27fasw.aspx.
2019-04-07 UPDATE: I tested today with a new version of windows 10 (build 1809, "2018 October's update") and not only the open SSH client is no longer in beta, as it is already installed. So, all you need to do is create the key and set your client to use open SSH instead of putty(pagent):
ssh-keygen
and press enterI tested on Git Extensions and Source Tree and it worked with my personal repo in GitHub. If you are in an earlier windows version or prefer a graphical client for SSH, please read below.
2018-06-04 UDPATE:
On windows 10, starting with version 1709 (win+R and type winver
to find the build number), Microsoft is releasing a beta of the OpenSSH client and server.
To be able to create a key, you'll need to install the OpenSSH server. To do this follow these steps:
Now you can open a prompt and ssh-keygen
and the client will be recognized by windows. I have not tested this.
If you do not have windows 10 or do not want to use the beta, follow the instructions below on how to use putty.
ssh-keygen
does not come installed with windows. Here's how to create an ssh key with Putty:
For openssh keys, a few more steps are required:
Now that the keys are saved. Start pagent
and add the private key there ( the ppk file in Putty's format)
Remember that pagent
must be running for the authentication to work
Checkboxes (radio buttons and <select>
) are OS-level components, not browser-level. You cannot reliably style them in a manner that will be consistent across browsers and operating systems.
Your best bet it to put an overlay on top and style that instead.
From the source code you will be able to view that, ExpectedConditions.elementToBeClickable()
, it will judge the element visible and enabled, so you can use isEnabled()
together with isDisplayed()
. Following is the source code.
public static ExpectedCondition<WebElement> elementToBeClickable(final WebElement element) {_x000D_
return new ExpectedCondition() {_x000D_
public WebElement apply(WebDriver driver) {_x000D_
WebElement visibleElement = (WebElement) ExpectedConditions.visibilityOf(element).apply(driver);_x000D_
_x000D_
try {_x000D_
return visibleElement != null && visibleElement.isEnabled() ? visibleElement : null;_x000D_
} catch (StaleElementReferenceException arg3) {_x000D_
return null;_x000D_
}_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return "element to be clickable: " + element;_x000D_
}_x000D_
};_x000D_
}
_x000D_
Copied from the bash completion file, the following is a naive way to do it
# Copyright (C) 2006,2007 Shawn O. Pearce <[email protected]>
# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/).
# Distributed under the GNU General Public License, version 2.0.
if [ -d .git ]; then
echo .git;
else
git rev-parse --git-dir 2> /dev/null;
fi;
You could either wrap that in a function or use it in a script.
Condensed into a one line condition suitable for bash and zsh
[ -d .git ] && echo .git || git rev-parse --git-dir > /dev/null 2>&1