Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
Do you mean, for concatenation?
Real world example: You want to create a new string out of many others.
For instance to send a message:
String
String s = "Dear " + user.name + "<br>" +
" I saw your profile and got interested in you.<br>" +
" I'm " + user.age + "yrs. old too"
StringBuilder
String s = new StringBuilder().append.("Dear ").append( user.name ).append( "<br>" )
.append(" I saw your profile and got interested in you.<br>")
.append(" I'm " ).append( user.age ).append( "yrs. old too")
.toString()
Or
String s = new StringBuilder(100).appe..... etc. ...
// The difference is a size of 100 will be allocated upfront as fuzzy lollipop points out.
StringBuffer ( the syntax is exactly as with StringBuilder, the effects differ )
About
StringBuffer
vs. StringBuilder
The former is synchonized and later is not.
So, if you invoke it several times in a single thread ( which is 90% of the cases ), StringBuilder
will run much faster because it won't stop to see if it owns the thread lock.
So, it is recommendable to use StringBuilder
( unless of course you have more than one thread accessing to it at the same time, which is rare )
String
concatenation ( using the + operator ) may be optimized by the compiler to use StringBuilder
underneath, so, it not longer something to worry about, in the elder days of Java, this was something that everyone says should be avoided at all cost, because every concatenation created a new String object. Modern compilers don't do this anymore, but still it is a good practice to use StringBuilder
instead just in case you use an "old" compiler.
edit
Just for who is curious, this is what the compiler does for this class:
class StringConcatenation {
int x;
String literal = "Value is" + x;
String builder = new StringBuilder().append("Value is").append(x).toString();
}
javap -c StringConcatenation
Compiled from "StringConcatenation.java"
class StringConcatenation extends java.lang.Object{
int x;
java.lang.String literal;
java.lang.String builder;
StringConcatenation();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: aload_0
5: new #2; //class java/lang/StringBuilder
8: dup
9: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
12: ldc #4; //String Value is
14: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
17: aload_0
18: getfield #6; //Field x:I
21: invokevirtual #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
24: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
27: putfield #9; //Field literal:Ljava/lang/String;
30: aload_0
31: new #2; //class java/lang/StringBuilder
34: dup
35: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
38: ldc #4; //String Value is
40: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
43: aload_0
44: getfield #6; //Field x:I
47: invokevirtual #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
50: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
53: putfield #10; //Field builder:Ljava/lang/String;
56: return
}
Lines numbered 5 - 27 are for the String named "literal"
Lines numbered 31-53 are for the String named "builder"
Ther's no difference, exactly the same code is executed for both strings.
Ok folks, I ran into this problem this weekend when my OpenStack environment crashed. Another post about that coming soon on how to recover.
I found a solution that worked for me with a SQL Server instance running under the Ver 15.1 Distrib 10.1.21-MariaDB with Fedora 25 Server as the host. Do not listen to all the other posts that say your database is corrupted if you completely copied your old mariadb-server's /var/lib/mysql directory and the database you are copying is not already corrupted. This process is based on a system where the OS became corrupted but its files were still accessible.
Here are the steps I followed.
Make sure that you have completely uninstalled any current versions of SQL only on the NEW server. Also, make sure ALL mysql-server or mariadb-server processes on the NEW AND OLD servers have been halted by running:
service mysqld stop or service mariadb stop.
On the NEW SQL server go into the /var/lib/mysql directory and ensure that there are no files at all in this directory. If there are files in this directory then your process for removing the database server from the new machine did not work and is possibly corrupted. Make sure it completely uninstalled from the new machine.
On the OLD SQL server:
mkdir /OLDMYSQL-DIR cd /OLDMYSQL-DIR tar cvf mysql-olddirectory.tar /var/lib/mysql gzip mysql-olddirectory.tar
Make sure you have sshd running on both the OLD and NEW servers. Make sure there is network connectivity between the two servers.
On the NEW SQL server:
mkdir /NEWMYSQL-DIR
On the OLD SQL server:
cd /OLDMYSQL-DIR scp mysql-olddirectory.tar.gz @:/NEWMYSQL-DIR
On the NEW SQL server:
cd /NEWMYSQL-DIR gunzip mysql-olddirectory.tar.gz OR tar zxvf mysql-olddirectory.tar.gz (if tar zxvf doesn't work) tar xvf mysql-olddirectory.tar.gz
You should now have a "mysql" directory file sitting in the NEWMYSQL-DIR. Resist the urge to run a "cp" command alone with no switches. It will not work. Run the following "cp" command and ensure you use the same switches I did.
cd mysql/ cp -rfp * /var/lib/mysql/
Now you should have a copy of all of your old SQL server files on the NEW server with permissions in tact. On the NEW SQL server:
cd /var/lib/mysql/
VERY IMPORTANT STEP. DO NOT SKIP
> rm -rfp ib_logfile*
FOR MARIADB-SERVER and DNF:
> dnf install mariadb-server
> service mariadb restart
FOR MYSQL-SERVER and YUM:
> yum install mysql-server
> service mysqld restart
I think you want this:
Dim filename As String
filename = Application.GetOpenFilename
Dim cell As Range
cell = Application.Range("A1")
cell.Value = filename
I would suggest you to use fseek-ftell functions.
FILE *stream = fopen("example.txt", "r");
if(!stream) {
puts("I/O error.\n");
return;
}
fseek(stream, 0, SEEK_END);
long size = ftell(stream);
fseek(stream, 0, SEEK_SET);
while(1) {
if(ftell(stream) == size) {
break;
}
/* INSERT ROUTINE */
}
fclose(stream);
I would be very careful with self closing tags as this example demonstrates:
var a = '<span/><span/>';
var d = document.createElement('div');
d.innerHTML = a
console.log(d.innerHTML) // "<span><span></span></span>"
My gut feeling would have been <span></span><span></span>
instead
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
I came up with a simple solution.
I have a model.cs class with:
private int _isSuccess;
public int IsSuccess { get { return _isSuccess; } set { _isSuccess = value; } }
I have Window1.xaml.cs file with DataContext set to model.cs. The xaml contains the radiobuttons:
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=1}" Content="one" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=2}" Content="two" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=3}" Content="three" />
Here is my converter:
public class RadioBoolToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int integer = (int)value;
if (integer==int.Parse(parameter.ToString()))
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter;
}
}
And of course, in Window1's resources:
<Window.Resources>
<local:RadioBoolToIntConverter x:Key="radioBoolToIntConverter" />
</Window.Resources>
Works with an arbitrary number of input values:
public static double min(double... doubles) {
double m = Double.MAX_VALUE;
for (double d : doubles) {
m = Math.min(m, d);
}
return m;
}
No, if a is true (in a or
test), b will not be tested, as the result of the test will always be true, whatever is the value of the b expression.
Make a simple test:
if (true || ((String) null).equals("foobar")) {
...
}
will not throw a NullPointerException
!
In the case of having this message in live tests, but not in unit tests, it's because selected assemblies are copied on the fly to $(SolutionDir)\.vs\$(SolutionName)\lut\0\0\x64\Debug\
. But sometime few assemblies can be not selected, eg., VC++ dlls in case of interop c++/c# projects.
Post-build xcopy
won't correct the problem, because the copied file will be erased by the live test engine.
The only workaround to date (28 dec 2018), is to avoid Live tests, and do everything in unit tests with the attribute [TestCategory("SkipWhenLiveUnitTesting")]
applied to the test class or the test method.
This bug is seen in any Visual Studio 2017 up to 15.9.4, and needs to be addressed by the Visual Studio team.
.cut_text {_x000D_
white-space: nowrap; _x000D_
width: 200px; _x000D_
border: 1px solid #000000;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<div class="cut_text">_x000D_
_x000D_
very long text_x000D_
</div>
_x000D_
You can try this example out. A simple C# progaram to convert string to double
class Calculations{
protected double length;
protected double height;
protected double width;
public void get_data(){
this.length = Convert.ToDouble(Console.ReadLine());
this.width = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());
}
}
I like using fsockopen open for this.
The order of the importing was the reason why I was having issues:
a.py
:
############
# this is a problem
# move this to below
#############
from b import NewThing
class ProblemThing(object):
pass
class A(object):
###############
# add it here
# from b import NewThing
###############
nt = NewThing()
pass
b.py
:
from a import ProblemThing
class NewThing(ProblemThing):
pass
Just another example of how it might look, similar to RichieHindie's answer, but with classes.
If you need to target multiple classes use:
#main_text .title, #main_text .title2 {
/* Properties */
}
Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.
There are problems with using 0 (and hence NULL). For example:
void f(int);
void f(void*);
f(0); // Ambiguous. Calls f(int).
The next version of C++ (C++0x) includes nullptr
to fix this.
f(nullptr); // Calls f(void*).
Good news everyone, Chris Eppstein created a compass plugin with inline css import functionality:
https://github.com/chriseppstein/sass-css-importer
Now, importing a CSS file is as easy as:
@import "CSS:library/some_css_file"
Assume logs are already put to stdout/stderr, and have systemd unit's log in /var/log/syslog
journalctl -u unitxxx.service
Jun 30 13:51:46 host unitxxx[1437]: time="2018-06-30T11:51:46Z" level=info msg="127.0.0.1
Jun 30 15:02:15 host unitxxx[1437]: time="2018-06-30T13:02:15Z" level=info msg="127.0.0.1
Jun 30 15:33:02 host unitxxx[1437]: time="2018-06-30T13:33:02Z" level=info msg="127.0.0.1
Jun 30 15:56:31 host unitxxx[1437]: time="2018-06-30T13:56:31Z" level=info msg="127.0.0.1
Config rsyslog (System Logging Service)
# Create directory for log file
mkdir /var/log/unitxxx
# Then add config file /etc/rsyslog.d/unitxxx.conf
if $programname == 'unitxxx' then /var/log/unitxxx/unitxxx.log
& stop
Restart rsyslog
systemctl restart rsyslog.service
wrong code:$("#myParagraph").css({"backgroundColor":"black","color":"white");
its missing "}"
after white"
change it to this
$("#myParagraph").css({"background-color":"black","color":"white"});
A query of type MyEntity
is going to return MyEntity
. You want a query for a Long
.
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.
So, I'm using Razor but this will work using either. I'm basically wrapping a button in a link.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
If none of the above solutions worked, then stop and do a sanity check.
I got burned using the wrong -G <config>
string and it gave me this misleading error.
First, run from the VS Command Prompt not the regular command prompt. You can find it in
Start Menu -> Visual Studio 2015 -> MSBuild Command Prompt for VS2015
This sets up all the correct paths to VS tools, etc.
Now see what generators are available from cmake...
cmake -help
...<snip>...
The following generators are available on this platform:
Visual Studio 15 [arch] = Generates Visual Studio 15 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
Optional [arch] can be "Win64" or "IA64".
...
Then chose the appropriate string with the [arch] added.
mkdir _build
cd _build
cmake .. -G "Visual Studio 15 Win64"
Running cmake in a subdirectory makes it easier to do a 'clean' since you can just delete everything in that directory.
I upgraded to Visual Studio 15 but wasn't paying attention and was trying to generate for 2012.
If it's not a big/long array just mirror it:
for( int i = 0; i < arr.length/2; ++i )
{
temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
By default wordpress uses MD5. You can upgrade it to blowfish or extended DES.
http://frameworkgeek.com/support/what-hash-does-wordpress-use/
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.
For macOS Sierra:
I ran into this error When i used bundler(v1.15.3
) in Rails(v4.2
) project.
The solution for me is gem uninstall bundler -v '1.15.3'
and gem install bundler -v '1.14.6'
.
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
I have had the same problem recently and after installing different packages in different order it was just getting very messy. Then I have found this repo - https://github.com/felixrieseberg/windows-build-tools
npm install --global windows-build-tools
It installs Python & VS Build tools that are required to compile most node modules. It worked a treat!
Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?
Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.
If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.
In Xcode-11.2.1
You might be see different pattern for uploading IPA
Steps:-
i) Add your apple developer id in xcode preference -> account
ii)Clean Build Folder :-
iii) Archive
iv) Tap on Distribute App
v) Choose Ad-hoc to distribute on designated device
6)Tricky part -> User can download app from company's website URL. Many of us might get stuck and start creating website url to upload ipa, which is not required. Simply write google website url with https. :)
7)Click on export and you get ipa.
8)Visit https://www.diawi.com/ & drag and drop ipa you have downloaded. & share the link to your client/user who want to test :)
Here is yet another directive to highlight active links.
.directive('activeLink', ['$location',
function($location) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var path = attrs.activeLink ? 'activeLink' : 'href';
var target = angular.isDefined(attrs.activeLinkParent) ? elem.parent() : elem;
var disabled = angular.isDefined(attrs.activeLinkDisabled) ? true : false;
var nested = angular.isDefined(attrs.activeLinkNested) ? true : false;
function inPath(needle, haystack) {
var current = (haystack == needle);
if (nested) {
current |= (haystack.indexOf(needle + '/') == 0);
}
return current;
}
function toggleClass(linkPath, locationPath) {
// remove hash prefix and trailing slashes
linkPath = linkPath ? linkPath.replace(/^#!/, '').replace(/\/+$/, '') : '';
locationPath = locationPath.replace(/\/+$/, '');
if (linkPath && inPath(linkPath, locationPath)) {
target.addClass('active');
if (disabled) {
target.removeClass('disabled');
}
} else {
target.removeClass('active');
if (disabled) {
target.addClass('disabled');
}
}
}
// watch if attribute value changes / evaluated
attrs.$observe(path, function(linkPath) {
toggleClass(linkPath, $location.path());
});
// watch if location changes
scope.$watch(
function() {
return $location.path();
},
function(newPath) {
toggleClass(attrs[path], newPath);
}
);
}
};
}
]);
Simple example with angular expression, lets say $scope.var = 2, then link will be active if location is /url/2 :
<a href="#!/url/{{var}}" active-link>
Bootstrap example, parent li will get active class:
<li>
<a href="#!/url" active-link active-link-parent>
</li>
Example with nested urls, link will be active if any nested url is active (i.e. /url/1, /url/2, url/1/2/...)
<a href="#!/url" active-link active-link-nested>
Complex example, link points to one url (/url1) but will be active if another is selected (/url2):
<a href="#!/url1" active-link="#!/url2" active-link-nested>
Example with disabled link, if it is not active it will have 'disabled' class:
<a href="#!/url" active-link active-link-disabled>
All active-link-* attributes can be used in any combination, so very complex conditions could be implemented.
In your pom.xml file inside that <java.version> write "8" instead write "11" ,and RECOMPILE your pom.xml file And tadaaaaaa it works !
Before each of your conditional statements, you could do something like this:
var pagetype = pagetype || false;
if (pagetype === 'something') {
//do stuff
}
The two socket options SO_RCVTIMEO
and SO_SNDTIMEO
have no effect on connect
. Below is a link to the screenshot which includes this explanation, here I am just briefing it. The apt way of implementing timeouts with connect
are using signal
or select or poll
.
connect
can be interrupted by a self generated signal SIGALRM
by using syscall (wrapper) alarm
. But, a signal disposition should be installed for the same signal otherwise the program would be terminated. The code goes like this...
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<signal.h>
#include<errno.h>
static void signal_handler(int signo)
{
return; // Do nothing just interrupt.
}
int main()
{
/* Register signal handler */
struct sigaction act, oact;
act.sa_handler = signal_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
#ifdef SA_INTERRUPT
act.sa_flags |= SA_INTERRUPT;
#endif
if(sigaction(SIGALRM, &act, &oact) < 0) // Error registering signal handler.
{
fprintf(stderr, "Error registering signal disposition\n");
exit(1);
}
/* Prepare your socket and sockaddr structures */
int sockfd;
struct sockaddr* servaddr;
/* Implementing timeout connect */
int sec = 30;
if(alarm(sec) != 0)
fprintf(stderr, "Already timer was set\n");
if(connect(sockfd, servaddr, sizeof(struct sockaddr)) < 0)
{
if(errno == EINTR)
fprintf(stderr, "Connect timeout\n");
else
fprintf(stderr, "Connect failed\n");
close(sockfd);
exit(1);
}
alarm(0); /* turn off the alarm */
sigaction(SIGALRM, &oact, NULL); /* Restore the default actions of SIGALRM */
/* Use socket */
/* End program */
close(sockfd);
return 0;
}
As already some users provided nice explanation on how to use select
to achieve connect
timeout, it would not be necessary for me to reiterate the same. poll
can be used in the same way. However, there are few mistakes that are common in all of the answers, which I would like to address.
Even though socket is non-blocking, if the server to which we are connecting is on the same local machine, connect
may return with success. So it is advised to check the return value of connect
before calling select
.
Berkeley-derived implementations (and POSIX) have the following rules for non-blocking sockets and connect
.
1) When the connection completes successfully, the descriptor becomes writable (p. 531 of TCPv2).
2) When the connection establishment encounters an error, the descriptor becomes both readable and writable (p. 530 of TCPv2).
So the code should handle these cases, here I just code the necessary modifications.
/* All the code stays */
/* Modifications at connect */
int conn_ret = connect(sockfd, servaddr, sizeof(struct sockdaddr));
if(conn_ret == 0)
goto done;
/* Modifications at select */
int sec = 30;
for( ; ; )
{
struct timeval timeo;
timeo.tv_sec = sec;
timeo.tv_usec = 0;
fd_set wr_set, rd_set;
FDZERO(&wr_set);
FD_SET(sockfd, &wr_set);
rd_set = wr_set;
int sl_ret = select(sockfd + 1, &rd_set, &wr_set, NULL, &timeo);
/* All the code stays */
}
done:
/* Use your socket */
Go to the Users & Groups pane of the System Preferences -> Select the User -> Click the lock to make changes (bottom left corner) -> right click the current user select Advanced options... -> Select the Login Shell: /bin/zsh and OK
There is actually another way of looking at this problem, not as a number problem, but a Unary problem, starting with the base character of Roman numbers, "I". So we represent the number with just I, and then we replace the characters in ascending value of the roman characters.
public String getRomanNumber(int number) {
return join("", nCopies(number, "I"))
.replace("IIIII", "V")
.replace("IIII", "IV")
.replace("VV", "X")
.replace("VIV", "IX")
.replace("XXXXX", "L")
.replace("XXXX", "XL")
.replace("LL", "C")
.replace("LXL", "XC")
.replace("CCCCC", "D")
.replace("CCCC", "CD")
.replace("DD", "M")
.replace("DCD", "CM");
}
I especially like this method of solving this problem rather than using a lot of ifs and while loops, or table lookups. It is also actually a quit intuitive solution when you thinking of the problem not as a number problem.
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
I had the same issue with anaconda package, it got updated.
anaconda {4.3.1 -> custom} ## I am not sure if this was the issue
Hit below command to know
conda list --revisions
what i did is just uninstall pandas with conda and re-install it
conda install pandas
Some new libs may also get installed with it.
It worked for me hope will do the same for you.
Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.
Map is Select
:
Enumerable.Range(1, 10).Select(x => x + 2);
Reduce is Aggregate
:
Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
Filter is Where
:
Enumerable.Range(1, 10).Where(x => x % 2 == 0);
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
If, for some reason, you don't want to use String.split
(for example, because of regular expressions) and you want to use functional programming on Java 8 or newer:
List<String> lines = new BufferedReader(new StringReader(string))
.lines()
.collect(Collectors.toList());
You should have font-weight set to 900 for Font Awesome 5 Free font-family to work.
This is the working one:
.css-selector::before {
font-family: 'Font Awesome 5 Free';
content: "\f101";
font-weight: 900;
}
Although this question was posted 10 years ago, I believe that it still needs some improvements. So here is my solution.
$(document).on('propertychange change click keyup input paste', 'selector', function (e) {
// Do something here
});
The only problem with this solution is, it won't trigger if the value changes from javascript like $('selector').val('some value')
. You can fire any event to your selector when you change the value from javascript.
$(selector).val('some value');
// fire event
$(selector).trigger('change');
Very late to the thread, but a technique I've used, pre-Angular, is to take advantage of JSON and the flexibility of JS to dynamically reference collection keys, and use inalienable facts of the environment (host server name, current browser language, etc.) as inputs to selectively discriminate/prefer suffixed key names within a JSON data structure.
This provides not merely deploy-environment context (per OP) but any arbitrary context (such as language) to provide i18n or any other variance required simultaneously, and (ideally) within a single configuration manifest, without duplication, and readably obvious.
IN ABOUT 10 LINES VANILLA JS
Overly-simplified but classic example: An API endpoint base URL in a JSON-formatted properties file that varies per environment where (natch) the host server will also vary:
...
'svcs': {
'VER': '2.3',
'API@localhost': 'http://localhost:9090/',
'[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
'[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
},
...
A key to the discrimination function is simply the server hostname in the request.
This, naturally, can be combined with an additional key based on the user's language settings:
...
'app': {
'NAME': 'Ferry Reservations',
'NAME@fr': 'Réservations de ferry',
'NAME@de': 'Fähren Reservierungen'
},
...
The scope of the discrimination/preference can be confined to individual keys (as above) where the "base" key is only overwritten if there's a matching key+suffix for the inputs to the function -- or an entire structure, and that structure itself recursively parsed for matching discrimination/preference suffixes:
'help': {
'BLURB': 'This pre-production environment is not supported. Contact Development Team with questions.',
'PHONE': '808-867-5309',
'EMAIL': '[email protected]'
},
'[email protected]': {
'BLURB': 'Please contact Customer Service Center',
'BLURB@fr': 'S\'il vous plaît communiquer avec notre Centre de service à la clientèle',
'BLURB@de': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
'PHONE': '1-800-CUS-TOMR',
'EMAIL': '[email protected]'
},
SO, if a visiting user to the production website has German (de) language preference setting, the above configuration would collapse to:
'help': {
'BLURB': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
'PHONE': '1-800-CUS-TOMR',
'EMAIL': '[email protected]'
},
What does such a magical preference/discrimination JSON-rewriting function look like? Not much:
// prefer(object,suffix|[suffixes]) by/par/durch storsoc
// prefer({ a: 'apple', a@env: 'banana', b: 'carrot' },'env') -> { a: 'banana', b: 'carrot' }
function prefer(o,sufs) {
for (var key in o) {
if (!o.hasOwnProperty(key)) continue; // skip non-instance props
if(key.split('@')[1]) { // suffixed!
// replace root prop with the suffixed prop if among prefs
if(o[key] && sufs.indexOf(key.split('@')[1]) > -1) o[key.split('@')[0]] = JSON.parse(JSON.stringify(o[key]));
// and nuke the suffixed prop to tidy up
delete o[key];
// continue with root key ...
key = key.split('@')[0];
}
// ... in case it's a collection itself, recurse it!
if(o[key] && typeof o[key] === 'object') prefer(o[key],sufs);
};
};
In our implementations, which include Angular and pre-Angular websites, we simply bootstrap the configuration well ahead of other resource calls by placing the JSON within a self-executing JS closure, including the prefer() function, and fed basic properties of hostname and language-code (and accepts any additional arbitrary suffixes you might need):
(function(prefs){ var props = {
'svcs': {
'VER': '2.3',
'API@localhost': 'http://localhost:9090/',
'[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
'[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
},
...
/* yadda yadda moar JSON und bisque */
function prefer(o,sufs) {
// body of prefer function, broken for e.g.
};
// convert string and comma-separated-string to array .. and process it
prefs = [].concat( ( prefs.split ? prefs.split(',') : prefs ) || []);
prefer(props,prefs);
window.app_props = JSON.parse(JSON.stringify(props));
})([location.hostname, ((window.navigator.userLanguage || window.navigator.language).split('-')[0]) ] );
A pre-Angular site would now have a collapsed (no @ suffixed keys) window.app_props to refer to.
An Angular site, as a bootstrap/init step, simply copies the dead-dropped props object into $rootScope, and (optionally) destroys it from global/window scope
app.constant('props',angular.copy(window.app_props || {})).run( function ($rootScope,props) { $rootScope.props = props; delete window.app_props;} );
to be subsequently injected into controllers:
app.controller('CtrlApp',function($log,props){ ... } );
or referred to from bindings in views:
<span>{{ props.help.blurb }} {{ props.help.email }}</span>
Caveats? The @ character is not valid JS/JSON variable/key naming, but so far accepted. If that's a deal-breaker, substitute for any convention you like, such as "__" (double underscore) as long as you stick to it.
The technique could be applied server-side, ported to Java or C# but your efficiency/compactness may vary.
Alternately, the function/convention could be part of your front-end compile script, so that the full gory all-environment/all-language JSON is never transmitted over the wire.
UPDATE
We've evolved usage of this technique to allow multiple suffixes to a key, to avoid being forced to use collections (you still can, as deeply as you want), and as well to honor the order of the preferred suffixes.
Example (also see working jsFiddle):
var o = { 'a':'apple', 'a@dev':'apple-dev', 'a@fr':'pomme',
'b':'banana', 'b@fr':'banane', 'b@dev&fr':'banane-dev',
'c':{ 'o':'c-dot-oh', 'o@fr':'c-point-oh' }, 'c@dev': { 'o':'c-dot-oh-dev', 'o@fr':'c-point-oh-dev' } };
/*1*/ prefer(o,'dev'); // { a:'apple-dev', b:'banana', c:{o:'c-dot-oh-dev'} }
/*2*/ prefer(o,'fr'); // { a:'pomme', b:'banane', c:{o:'c-point-oh'} }
/*3*/ prefer(o,'dev,fr'); // { a:'apple-dev', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*4*/ prefer(o,['fr','dev']); // { a:'pomme', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*5*/ prefer(o); // { a:'apple', b:'banana', c:{o:'c-dot-oh'} }
1/2 (basic usage) prefers '@dev' keys, discards all other suffixed keys
3 prefers '@dev' over '@fr', prefers '@dev&fr' over all others
4 (same as 3 but prefers '@fr' over '@dev')
5 no preferred suffixes, drops ALL suffixed properties
It accomplishes this by scoring each suffixed property and promoting the value of a suffixed property to the non-suffixed property when iterating over the properties and finding a higher-scored suffix.
Some efficiencies in this version, including removing dependence on JSON to deep-copy, and only recursing into objects that survive the scoring round at their depth:
function prefer(obj,suf) {
function pr(o,s) {
for (var p in o) {
if (!o.hasOwnProperty(p) || !p.split('@')[1] || p.split('@@')[1] ) continue; // ignore: proto-prop OR not-suffixed OR temp prop score
var b = p.split('@')[0]; // base prop name
if(!!!o['@@'+b]) o['@@'+b] = 0; // +score placeholder
var ps = p.split('@')[1].split('&'); // array of property suffixes
var sc = 0; var v = 0; // reset (running)score and value
while(ps.length) {
// suffix value: index(of found suffix in prefs)^10
v = Math.floor(Math.pow(10,s.indexOf(ps.pop())));
if(!v) { sc = 0; break; } // found suf NOT in prefs, zero score (delete later)
sc += v;
}
if(sc > o['@@'+b]) { o['@@'+b] = sc; o[b] = o[p]; } // hi-score! promote to base prop
delete o[p];
}
for (var p in o) if(p.split('@@')[1]) delete o[p]; // remove scores
for (var p in o) if(typeof o[p] === 'object') pr(o[p],s); // recurse surviving objs
}
if( typeof obj !== 'object' ) return; // validate
suf = ( (suf || suf === 0 ) && ( suf.length || suf === parseFloat(suf) ) ? suf.toString().split(',') : []); // array|string|number|comma-separated-string -> array-of-strings
pr(obj,suf.reverse());
}
With query syntax:
var values =
from inner in outer
from value in inner
select value;
take example if we want to compare "a" and "b", i.e ("a" == this)
For Skin remove No Skin and add some skin into it
For 2 and more left joins (left joining creatorUser and initiatorUser )
IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
join candidateUser in authContext.AuthUsers
on r.CandidateId equals candidateUser.Id
join creatorUser in authContext.AuthUsers
on r.CreatorId equals creatorUser.Id into gj
from x in gj.DefaultIfEmpty()
join initiatorUser in authContext.AuthUsers
on r.InitiatorId equals initiatorUser.Id into init
from x1 in init.DefaultIfEmpty()
where candidateUser.UserName.Equals(candidateUsername)
select new CreateRequestModel
{
UserName = candidateUser.UserName,
CreatorId = (x == null ? String.Empty : x.UserName),
InitiatorId = (x1 == null ? String.Empty : x1.UserName),
CandidateId = candidateUser.UserName
};
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
A simpler but equally effective option would be:
+ theme_bw(base_size=X)
I am using MVC 1.0 RTM and none of the above solutions worked for me. But this one did:
Public Function RenderView(ByVal viewContext As ViewContext) As String
Dim html As String = ""
Dim response As HttpResponse = HttpContext.Current.Response
Using tempWriter As New System.IO.StringWriter()
Dim privateMethod As MethodInfo = response.GetType().GetMethod("SwitchWriter", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim currentWriter As Object = privateMethod.Invoke(response, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, New Object() {tempWriter}, Nothing)
Try
viewContext.View.Render(viewContext, Nothing)
html = tempWriter.ToString()
Finally
privateMethod.Invoke(response, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, New Object() {currentWriter}, Nothing)
End Try
End Using
Return html
End Function
Everything is encoded by default!!! This is pretty huge.
Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.
You can make a section required which is nice.
Here is my answer,
In row.model.ts
export interface Row {
otherProperty : type;
checked : bool;
otherProperty : type;
...
}
In .html
<tr class="even" *ngFor="let item of rows">
<input [checked]="item.checked" type="checkbox">
</tr>
In .ts
rows : Row[] = [];
update the rows in component.ts
The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource. The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly. DOC
Get a decent text editor like Notepad++ or Vim (if you're already proficient with it). Search for the table name and you should be able to highlight just the CREATE, ALTER, and INSERT commands for that table. It may be easier to navigate with your keyboard rather than a mouse. And I would make sure you're on a machine with plenty or RAM so that it will not have a problem loading the entire file at once. Once you've highlighted and copied the rows you need, it would be a good idea to back up just the copied part into it's own backup file and then import it into MySQL.
What fixed this for me was re-setting my origin url:
git remote set-url origin https://github.com/username/example_repo.git
And then I was able to successfully git push
my project. I had to do this even though when I viewed my origins with git remote -v
, that the urls were same as what I re-set it as.
git remote set-url origin <URL>
This is an improvement on the ".localized" approach. Start with adding the class extension as this will help with any strings you were setting programatically:
extension String {
func localized (bundle: Bundle = .main, tableName: String = "Localizable") -> String {
return NSLocalizedString(self, tableName: tableName, value: "\(self)", comment: "")
}
}
Example use for strings you set programmatically:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Now Xcode's storyboard translation files make the file manager messy and don't handle updates to the storyboard well either. A better approach is to create a new basic label class and assign it to all your storyboard labels:
class BasicLabel: UILabel {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.text
text = storyboardText?.localized()
}
}
Now every label you add and provide default default for in the storyboard will automatically get translated, assuming you've provide a translation for it.
You could do the same for UIButton:
class BasicBtn: UIButton {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.titleLabel?.text
let lclTxt = storyboardText?.localized()
setTitle(lclTxt, for: .normal)
}
}
In Erlang there is no need to differentiate between aggregates, once the aggregate is composed by data structures inside the state, instead of OO composition. See an example: https://github.com/bryanhunter/cqrs-with-erlang/tree/ndc-london
As per my answer here, it is also possible to use a table head (which can be empty) and apply relative widths for each table head cell. The widths of all cells in the table body will conform to the width of their column head. Example:
HTML
<table>
<thead>
<tr>
<th width="5%"></th>
<th width="70%"></th>
<th width="15%"></th>
<th width="10%"></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Some text...</td>
<td>May 2018</td>
<td>Edit</td>
</tr>
<tr>
<td>2</td>
<td>Another text...</td>
<td>April 2018</td>
<td>Edit</td>
</tr>
</tbody>
</table>
CSS
table {
width: 600px;
border-collapse: collapse;
}
td {
border: 1px solid #999999;
}
Alternatively, use colgroup
as suggested in Hyathin's answer.
You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.
You can however have cells span multiple columns, such as:
<table>
<tr>
<td>25</td>
<td>50</td>
<td>25</td>
</tr>
<tr>
<td colspan="2">75</td>
<td>20</td>
</tr>
</table>
As an aside, you should avoid using style attributes like border
and bgcolor
and prefer CSS for those.
A bit time consuming, but it should work in any case:
Connect via USB and enable USB storage. Copy the APK file from your local build to the phone (you might need to allow unknown sources under application settings).
Then just tap the APK file and Android will install it. Like I said, it's time consuming, but it might be faster than rebooting every now and then.
As Benjamin said in his answer, TC39 explicitly decided not to include this feature at least for ES2015. However, the consensus seems to be that they will add it in ES2016.
The syntax hasn't been decided yet, but there's a preliminary proposal for ES2016 that will allow you to declare static properties on a class.
Thanks to the magic of babel, you can use this today. Enable the class properties transform according to these instructions and you're good to go. Here's an example of the syntax:
class foo {
static myProp = 'bar'
someFunction() {
console.log(this.myProp)
}
}
This proposal is in a very early state, so be prepared to tweak your syntax as time goes on.
Use -execdir
which automatically holds the current file in {}
, for example:
find . -type f -execdir echo '{}' ';'
You can also use $PWD
instead of .
(on some systems it won't produce an extra dot in the front).
If you still got an extra dot, alternatively you can run:
find . -type f -execdir basename '{}' ';'
-execdir utility [argument ...] ;
The
-execdir
primary is identical to the-exec
primary with the exception that utility will be executed from the directory that holds the current file.
When used +
instead of ;
, then {}
is replaced with as many pathnames as possible for each invocation of utility. In other words, it'll print all filenames in one line.
Excel has to be able to handle the exact same situation.
Put those things into Excel, save them as CSV, and examine the file with a text editor. Then you'll know the rules Excel is applying to these situations.
Make Java produce the same output.
The formats used by Excel are published, by the way...
****Edit 1:**** Here's what Excel does
****Edit 2:**** Note that php's fputcsv
does the same exact thing as excel if you use " as the enclosure.
[email protected]
Richard
"This is what I think"
gets transformed into this:
Email,Fname,Quoted
[email protected],Richard,"""This is what I think"""
If there is no vertical scrolling then you can use position:absolute
and height:100%
declared on html and body elements.
Another option is to use viewport height units, see Make div 100% height of browser window
Absolute position Example:
html, body {_x000D_
height:100%;_x000D_
position: absolute;_x000D_
background-color:red;_x000D_
}_x000D_
.button{_x000D_
height:50%;_x000D_
background-color:white;_x000D_
}
_x000D_
<div class="button">BUTTON</div>
_x000D_
html, body {min-height:100vh;background:gray;_x000D_
}_x000D_
.col-100vh {_x000D_
height:100vh;_x000D_
}_x000D_
.col-50vh {_x000D_
height:50vh;_x000D_
}_x000D_
#mmenu_screen--information{_x000D_
background:teal;_x000D_
}_x000D_
#mmenu_screen--book{_x000D_
background:blue;_x000D_
}_x000D_
.mmenu_screen--direktaction{_x000D_
background:red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div id="mmenu_screen" class="col-100vh container-fluid main_container">_x000D_
_x000D_
<div class="row col-100vh">_x000D_
<div class="col-xs-6 col-100vh">_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--book">_x000D_
BOOKING BUTTON_x000D_
</div>_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--information">_x000D_
INFO BUTTON_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
<div class="col-100vh col-xs-6 mmenu_screen--direktaction">_x000D_
DIRECT ACTION BUTTON_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You need to code your html using absolute path for images. By Absolute path means you have to upload the images in a server and in the src
attribute of images you have to give the direct path like this <img src="http://yourdomain.com/images/example.jpg">
.
Below is the PHP code for your refference :- Its taken from http://www.php.net/manual/en/function.mail.php
<?php
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<p>Here are the birthdays upcoming in August!</p>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
If you have VS2013 installed and are getting this error, you may be invoking the wrong MSBuild. With VS2013, Microsoft now includes MSBuild as part of Visual Studio. See this Visual Studio blog posting for details.
In particular, note the new location of the binaries:
On 32-bit machines they can be found in: C:\Program Files\MSBuild\12.0\bin
On 64-bit machines the 32-bit tools will be under: C:\Program Files (x86)\MSBuild\12.0\bin
and the 64-bit tools under: C:\Program Files (x86)\MSBuild\12.0\bin\amd64
The MSBuild in %WINDIR%\Microsoft.NET\Framework\
doesn't seem to recognize the VS2013 (v120) platform toolset.
Yes, add the -Force
parameter.
copy-item $from $to -Recurse -Force
This worked for me, using the latest release of Angular 2 (2.0.0-rc.1):
main.ts
import {enableProdMode} from '@angular/core';
enableProdMode();
bootstrap(....);
Here is the function reference from their docs: https://angular.io/api/core/enableProdMode
Your code for setting value for hidden input is correct. Here is the example. Maybe you have some conditions in your if
statements that are not allowing your scripts to execute.
This is just my personal opinion and folks from web API team can probably articulate it better but here is my 2c.
First of all, I think it is not a question of one over another. You can use them both depending on what you want to do in your action method but in order to understand the real power of IHttpActionResult
, you will probably need to step outside those convenient helper methods of ApiController
such as Ok
, NotFound
, etc.
Basically, I think a class implementing IHttpActionResult
as a factory of HttpResponseMessage
. With that mind set, it now becomes an object that need to be returned and a factory that produces it. In general programming sense, you can create the object yourself in certain cases and in certain cases, you need a factory to do that. Same here.
If you want to return a response which needs to be constructed through a complex logic, say lots of response headers, etc, you can abstract all those logic into an action result class implementing IHttpActionResult
and use it in multiple action methods to return response.
Another advantage of using IHttpActionResult
as return type is that it makes ASP.NET Web API action method similar to MVC. You can return any action result without getting caught in media formatters.
Of course, as noted by Darrel, you can chain action results and create a powerful micro-pipeline similar to message handlers themselves in the API pipeline. This you will need depending on the complexity of your action method.
Long story short - it is not IHttpActionResult
versus HttpResponseMessage
. Basically, it is how you want to create the response. Do it yourself or through a factory.
Click Tools > Firebase to open the Assistant window.
Click to expand one of the listed features (for example, Analytics), then click the provided tutorial link (for example, Log an Analytics event).
Click the Connect to Firebase button to connect to Firebase and add the necessary code to your app.
JQUERY
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
var videoID = 'videoclip';_x000D_
var sourceID = 'mp4video';_x000D_
var newmp4 = 'media/video2.mp4';_x000D_
var newposter = 'media/video-poster2.jpg';_x000D_
_x000D_
$('#videolink1').click(function(event) {_x000D_
$('#'+videoID).get(0).pause();_x000D_
$('#'+sourceID).attr('src', newmp4);_x000D_
$('#'+videoID).get(0).load();_x000D_
//$('#'+videoID).attr('poster', newposter); //Change video poster_x000D_
$('#'+videoID).get(0).play();_x000D_
});_x000D_
});
_x000D_
You've forgot to define an onclick attribute to do something when the button is clicked, so nothing happening is the correct execution, see below;
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
----------------------
$json empty
public function deleteUser($extid)
{
$path = "/rest/user/".$extid."/;token=".$this->__token;
$result = $this->curl_req($path,"**$json**","DELETE");
return $result;
}
I'll address any questions you have... but here is an improved pattern you should follow to reduce code duplication.
As a sidenote though, you should consider not doing pagination on client-side. Since if you have a huge dataset, it would mean you need to download all the data before your page loads. Better to implement server-side pagination instead.
Fiddle: http://jsfiddle.net/Lzp0dw83/
HTML
<div id="listingTable"></div>
<a href="javascript:prevPage()" id="btn_prev">Prev</a>
<a href="javascript:nextPage()" id="btn_next">Next</a>
page: <span id="page"></span>
Javascript (put anywhere):
var current_page = 1;
var records_per_page = 2;
var objJson = [
{ adName: "AdName 1"},
{ adName: "AdName 2"},
{ adName: "AdName 3"},
{ adName: "AdName 4"},
{ adName: "AdName 5"},
{ adName: "AdName 6"},
{ adName: "AdName 7"},
{ adName: "AdName 8"},
{ adName: "AdName 9"},
{ adName: "AdName 10"}
]; // Can be obtained from another source, such as your objJson variable
function prevPage()
{
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage()
{
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page)
{
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("listingTable");
var page_span = document.getElementById("page");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
listing_table.innerHTML = "";
for (var i = (page-1) * records_per_page; i < (page * records_per_page); i++) {
listing_table.innerHTML += objJson[i].adName + "<br>";
}
page_span.innerHTML = page;
if (page == 1) {
btn_prev.style.visibility = "hidden";
} else {
btn_prev.style.visibility = "visible";
}
if (page == numPages()) {
btn_next.style.visibility = "hidden";
} else {
btn_next.style.visibility = "visible";
}
}
function numPages()
{
return Math.ceil(objJson.length / records_per_page);
}
window.onload = function() {
changePage(1);
};
UPDATE 2014/08/27
There is a bug above, where the for loop errors out when a particular page (the last page usually) does not contain records_per_page
number of records, as it tries to access a non-existent index.
The fix is simple enough, by adding an extra checking condition into the for loop to account for the size of objJson
:
Updated fiddle: http://jsfiddle.net/Lzp0dw83/1/
for (var i = (page-1) * records_per_page; i < (page * records_per_page) && i < objJson.length; i++)
Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.
If you only need to remove the first character you would do:
s = ":dfa:sif:e"
fixed = s[1:]
If you want to remove a character at a particular position, you would do:
s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]
If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:
s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
Here's a complete example of how it can be done. However you need flashback query privileges on the child table.
Here's the setup.
create table parent_tab
(parent_id number primary key,
val varchar2(20));
create table child_tab
(child_id number primary key,
parent_id number,
child_val number,
constraint child_par_fk foreign key (parent_id) references parent_tab);
insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');
insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);
commit;
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).
delete from child_tab where child_val = 100;
Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab
delete from parent_tab
where parent_id in
(select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
minus
select parent_id from child_tab);
'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
select * from parent_tab;
It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.
Can't you start maximized?
Set the System.Windows.Forms.Form.WindowState
property to FormWindowState.Maximized
This worked for me, curly braces are not required.
ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"
notification.icon here is scope variable.
I don't think this version exists on this thread yet: it provides both the list of column names along with the ddl for the index.
CREATE OR REPLACE VIEW V_TABLE_INDEXES AS
SELECT
n.nspname as "schema"
,t.relname as "table"
,c.relname as "index"
,i.indisunique AS "is_unique"
,array_to_string(array_agg(a.attname), ', ') as "columns"
,pg_get_indexdef(i.indexrelid) as "ddl"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid
JOIN pg_catalog.pg_class t ON i.indrelid = t.oid
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(i.indkey)
WHERE c.relkind = 'i'
and n.nspname not in ('pg_catalog', 'pg_toast')
and pg_catalog.pg_table_is_visible(c.oid)
GROUP BY
n.nspname
,t.relname
,c.relname
,i.indisunique
,i.indexrelid
ORDER BY
n.nspname
,t.relname
,c.relname;
I found that indexes using functions don't link to column names, so occasionally you find an index listing e.g. one column name when in fact is uses 3.
Example:
CREATE INDEX ui1 ON table1 (coalesce(col1,''),coalesce(col2,''),col3)
The query returns only 'col3' as a column on the index, but the DDL shows the full set of columns used in the index.
Try str_detect()
from the stringr package, which detects the presence or absence of a pattern in a string.
Here is an approach that also incorporates the %>%
pipe and filter()
from the dplyr package:
library(stringr)
library(dplyr)
CO2 %>%
filter(str_detect(Treatment, "non"))
Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
...
This filters the sample CO2 data set (that comes with R) for rows where the Treatment variable contains the substring "non". You can adjust whether str_detect
finds fixed matches or uses a regex - see the documentation for the stringr package.
Already answered above, but here's another approach you could take. I can't find the original post I adapted this from, but here's the code for the sake of your question. As noted above, the flatMap() function is what you'd be looking to utilize with Java 8. You can throw it in a utility class and just call "RandomUtils.combine(list1, list2, ...);" and you'd get a single List with all values. Just be careful with the wildcard - you could change this if you want a less generic method. You can also modify it for Sets - you just have to take care when using flatMap() on Sets to avoid data loss from equals/hashCode methods due to the nature of the Set interface.
Edit - If you use a generic method like this for the Set interface, and you happen to use Lombok, make sure you understand how Lombok handles equals/hashCode generation.
/**
* Combines multiple lists into a single list containing all elements of
* every list.
*
* @param <T> - The type of the lists.
* @param lists - The group of List implementations to combine
* @return a single List<?> containing all elements of the passed in lists.
*/
public static <T> List<?> combine(final List<?>... lists) {
return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
}
Adding a shell script e.g. run.sh
makes it much more easier:
#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"
Then you are able to execute:
./run.sh arg1 arg2 arg3
How it should be done in the tidyverse:
df.dplyr.purrr <- listOfDataFrames %>% map_df(bind_rows)
how to have a click event outside of the dropdown menu so that it close the dropdown menu ? Heres the code
$(document).click(function (e) {
e.stopPropagation();
var container = $(".dropDown");
//check if the clicked area is dropDown or not
if (container.has(e.target).length === 0) {
$('.subMenu').hide();
}
})
Following function allocates just enough memory to keep string representation of the given number and then writes the string representation into this area using standard sprintf
method.
char *itoa(long n)
{
int len = n==0 ? 1 : floor(log10l(labs(n)))+1;
if (n<0) len++; // room for negative sign '-'
char *buf = calloc(sizeof(char), len+1); // +1 for null
snprintf(buf, len+1, "%ld", n);
return buf;
}
Don't forget to free
up allocated memory when out of need:
char *num_str = itoa(123456789L);
// ...
free(num_str);
N.B. As snprintf copies n-1 bytes, we have to call snprintf(buf, len+1, "%ld", n) (not just snprintf(buf, len, "%ld", n))
In case it helps anyone setBackgroundImage
didn't work for me, but setImage
did
It's initialized to null if you do nothing, as are all reference types.
Python is a pragmatic programming language, and the reasons for len()
being a function and not a method of str
, list
, dict
etc. are pragmatic.
The len()
built-in function deals directly with built-in types: the CPython implementation of len()
actually returns the value of the ob_size
field in the PyVarObject
C struct that represents any variable-sized built-in object in memory. This is much faster than calling a method -- no attribute lookup needs to happen. Getting the number of items in a collection is a common operation and must work efficiently for such basic and diverse types as str
, list
, array.array
etc.
However, to promote consistency, when applying len(o)
to a user-defined type, Python calls o.__len__()
as a fallback. __len__
, __abs__
and all the other special methods documented in the Python Data Model make it easy to create objects that behave like the built-ins, enabling the expressive and highly consistent APIs we call "Pythonic".
By implementing special methods your objects can support iteration, overload infix operators, manage contexts in with
blocks etc. You can think of the Data Model as a way of using the Python language itself as a framework where the objects you create can be integrated seamlessly.
A second reason, supported by quotes from Guido van Rossum like this one, is that it is easier to read and write len(s)
than s.len()
.
The notation len(s)
is consistent with unary operators with prefix notation, like abs(n)
. len()
is used way more often than abs()
, and it deserves to be as easy to write.
There may also be a historical reason: in the ABC language which preceded Python (and was very influential in its design), there was a unary operator written as #s
which meant len(s)
.
Following the Jenkins wiki, you'll have to:
chown -R jenkins:jenkins $JENKINS_HOME
JENKINS_HOME is by default located in ~/.jenkins
on a Linux installation, yet to exactly find where it is located, go on the http://your_jenkins_url/configure page and check the value of the first parameter: Home directory
; this is the JENKINS_HOME.
display:none is the best thing to avoid takeup white space on the page
Try the following code with an added request property:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class SocketConnection
{
public static String getURLSource(String url) throws IOException
{
URL urlObject = new URL(url);
URLConnection urlConnection = urlObject.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
return toString(urlConnection.getInputStream());
}
private static String toString(InputStream inputStream) throws IOException
{
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
{
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
}
return stringBuilder.toString();
}
}
}
If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression You can use it like:
val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)
You can do it with css first-letter! eg I wanted it for the Menu:
a {display:inline-block; text-transorm:uppercase;}
a::first-letter {font-size:50px;}
It only runs with block elements - therefore the inline-block!
Step 1: Un-comment plyfills in polyfills.ts. Also run all npm install commands mentioned in in polyfills.ts file to install those packages
Step 2: In browserslist file remove not before the line where IE 9-11 support is mentioned
Step 3: In tsconfig.json file change like "target": "es2015" to "target": "es5"
These steps fixed my issue
You don't want to lose the user scaling option if you can help it. I like this JS solution from here.
<script type="text/javascript">
(function(doc) {
var addEvent = 'addEventListener',
type = 'gesturestart',
qsa = 'querySelectorAll',
scales = [1, 1],
meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];
function fix() {
meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
doc.removeEventListener(type, fix, true);
}
if ((meta = meta[meta.length - 1]) && addEvent in doc) {
fix();
scales = [.25, 1.6];
doc[addEvent](type, fix, true);
}
}(document));
</script>
You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this
="Today is "&TEXT(A1,"dd-mm-yyyy")
You can change the "dd-mm-yyyy" part as required
A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.
You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.
If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.
Here is some code that show how it works.
class Test
{
public static void main(String args[])
{
System.out.println(Test.test());
}
public static String test()
{
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
The results is:
try
catch
finally
return in finally
/*Swift-5 update*/
let tempBtn: UIButton = UIButton(frame: CGRect(x: 5, y: 20, width: 40, height: 40))
tempBtn.backgroundColor = UIColor.red
We just open-sourced this jquery plug-in Github: tactivos/jquery-sew.
Or you can tell javascript where to write it.
<script type="text/javascript">
var elem = document.getElementById('myDiv');
var msg= 'Hello<br />';
elem.innerHTML = msg;
</script>
You can combine this with other functions to have function write content after being evaluated.
get the value in the variable & then separate its extension just like this.
var find_file_ext=document.getElementById('filename').value;
var file_ext=/[^.]+$/.exec(find_file_ext);
This will help you.
An example here from a sample test WAMP server database:-
mysql> select * from user_privileges;
| GRANTEE | TABLE_CATALOG | PRIVILEGE_TYPE | IS_GRANTABLE |
+--------------------+---------------+-------------------------+--------------+
| 'root'@'localhost' | def | SELECT | YES |
| 'root'@'localhost' | def | INSERT | YES |
| 'root'@'localhost' | def | UPDATE | YES |
| 'root'@'localhost' | def | DELETE | YES |
| 'root'@'localhost' | def | CREATE | YES |
| 'root'@'localhost' | def | DROP | YES |
| 'root'@'localhost' | def | RELOAD | YES |
| 'root'@'localhost' | def | SHUTDOWN | YES |
| 'root'@'localhost' | def | PROCESS | YES |
| 'root'@'localhost' | def | FILE | YES |
| 'root'@'localhost' | def | REFERENCES | YES |
| 'root'@'localhost' | def | INDEX | YES |
| 'root'@'localhost' | def | ALTER | YES |
| 'root'@'localhost' | def | SHOW DATABASES | YES |
| 'root'@'localhost' | def | SUPER | YES |
| 'root'@'localhost' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'localhost' | def | LOCK TABLES | YES |
| 'root'@'localhost' | def | EXECUTE | YES |
| 'root'@'localhost' | def | REPLICATION SLAVE | YES |
| 'root'@'localhost' | def | REPLICATION CLIENT | YES |
| 'root'@'localhost' | def | CREATE VIEW | YES |
| 'root'@'localhost' | def | SHOW VIEW | YES |
| 'root'@'localhost' | def | CREATE ROUTINE | YES |
| 'root'@'localhost' | def | ALTER ROUTINE | YES |
| 'root'@'localhost' | def | CREATE USER | YES |
| 'root'@'localhost' | def | EVENT | YES |
| 'root'@'localhost' | def | TRIGGER | YES |
| 'root'@'localhost' | def | CREATE TABLESPACE | YES |
| 'root'@'127.0.0.1' | def | SELECT | YES |
| 'root'@'127.0.0.1' | def | INSERT | YES |
| 'root'@'127.0.0.1' | def | UPDATE | YES |
| 'root'@'127.0.0.1' | def | DELETE | YES |
| 'root'@'127.0.0.1' | def | CREATE | YES |
| 'root'@'127.0.0.1' | def | DROP | YES |
| 'root'@'127.0.0.1' | def | RELOAD | YES |
| 'root'@'127.0.0.1' | def | SHUTDOWN | YES |
| 'root'@'127.0.0.1' | def | PROCESS | YES |
| 'root'@'127.0.0.1' | def | FILE | YES |
| 'root'@'127.0.0.1' | def | REFERENCES | YES |
| 'root'@'127.0.0.1' | def | INDEX | YES |
| 'root'@'127.0.0.1' | def | ALTER | YES |
| 'root'@'127.0.0.1' | def | SHOW DATABASES | YES |
| 'root'@'127.0.0.1' | def | SUPER | YES |
| 'root'@'127.0.0.1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'127.0.0.1' | def | LOCK TABLES | YES |
| 'root'@'127.0.0.1' | def | EXECUTE | YES |
| 'root'@'127.0.0.1' | def | REPLICATION SLAVE | YES |
| 'root'@'127.0.0.1' | def | REPLICATION CLIENT | YES |
| 'root'@'127.0.0.1' | def | CREATE VIEW | YES |
| 'root'@'127.0.0.1' | def | SHOW VIEW | YES |
| 'root'@'127.0.0.1' | def | CREATE ROUTINE | YES |
| 'root'@'127.0.0.1' | def | ALTER ROUTINE | YES |
| 'root'@'127.0.0.1' | def | CREATE USER | YES |
| 'root'@'127.0.0.1' | def | EVENT | YES |
| 'root'@'127.0.0.1' | def | TRIGGER | YES |
| 'root'@'127.0.0.1' | def | CREATE TABLESPACE | YES |
| 'root'@'::1' | def | SELECT | YES |
| 'root'@'::1' | def | INSERT | YES |
| 'root'@'::1' | def | UPDATE | YES |
| 'root'@'::1' | def | DELETE | YES |
| 'root'@'::1' | def | CREATE | YES |
| 'root'@'::1' | def | DROP | YES |
| 'root'@'::1' | def | RELOAD | YES |
| 'root'@'::1' | def | SHUTDOWN | YES |
| 'root'@'::1' | def | PROCESS | YES |
| 'root'@'::1' | def | FILE | YES |
| 'root'@'::1' | def | REFERENCES | YES |
| 'root'@'::1' | def | INDEX | YES |
| 'root'@'::1' | def | ALTER | YES |
| 'root'@'::1' | def | SHOW DATABASES | YES |
| 'root'@'::1' | def | SUPER | YES |
| 'root'@'::1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'::1' | def | LOCK TABLES | YES |
| 'root'@'::1' | def | EXECUTE | YES |
| 'root'@'::1' | def | REPLICATION SLAVE | YES |
| 'root'@'::1' | def | REPLICATION CLIENT | YES |
| 'root'@'::1' | def | CREATE VIEW | YES |
| 'root'@'::1' | def | SHOW VIEW | YES |
| 'root'@'::1' | def | CREATE ROUTINE | YES |
| 'root'@'::1' | def | ALTER ROUTINE | YES |
| 'root'@'::1' | def | CREATE USER | YES |
| 'root'@'::1' | def | EVENT | YES |
| 'root'@'::1' | def | TRIGGER | YES |
| 'root'@'::1' | def | CREATE TABLESPACE | YES |
| ''@'localhost' | def | USAGE | NO |
+--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)
And when it is given additional order by PRIVILEGE_TYPE
or can be given order by 3
. Notice the 3rd column (PRIVILEGE_TYPE
) getting sorted alphabetically.
mysql> select * from user_privileges order by PRIVILEGE_TYPE;
+--------------------+---------------+-------------------------+--------------+
| GRANTEE | TABLE_CATALOG | PRIVILEGE_TYPE | IS_GRANTABLE |
+--------------------+---------------+-------------------------+--------------+
| 'root'@'127.0.0.1' | def | ALTER | YES |
| 'root'@'::1' | def | ALTER | YES |
| 'root'@'localhost' | def | ALTER | YES |
| 'root'@'::1' | def | ALTER ROUTINE | YES |
| 'root'@'localhost' | def | ALTER ROUTINE | YES |
| 'root'@'127.0.0.1' | def | ALTER ROUTINE | YES |
| 'root'@'127.0.0.1' | def | CREATE | YES |
| 'root'@'::1' | def | CREATE | YES |
| 'root'@'localhost' | def | CREATE | YES |
| 'root'@'::1' | def | CREATE ROUTINE | YES |
| 'root'@'localhost' | def | CREATE ROUTINE | YES |
| 'root'@'127.0.0.1' | def | CREATE ROUTINE | YES |
| 'root'@'::1' | def | CREATE TABLESPACE | YES |
| 'root'@'localhost' | def | CREATE TABLESPACE | YES |
| 'root'@'127.0.0.1' | def | CREATE TABLESPACE | YES |
| 'root'@'::1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'localhost' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'127.0.0.1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'localhost' | def | CREATE USER | YES |
| 'root'@'127.0.0.1' | def | CREATE USER | YES |
| 'root'@'::1' | def | CREATE USER | YES |
| 'root'@'localhost' | def | CREATE VIEW | YES |
| 'root'@'127.0.0.1' | def | CREATE VIEW | YES |
| 'root'@'::1' | def | CREATE VIEW | YES |
| 'root'@'127.0.0.1' | def | DELETE | YES |
| 'root'@'::1' | def | DELETE | YES |
| 'root'@'localhost' | def | DELETE | YES |
| 'root'@'::1' | def | DROP | YES |
| 'root'@'localhost' | def | DROP | YES |
| 'root'@'127.0.0.1' | def | DROP | YES |
| 'root'@'127.0.0.1' | def | EVENT | YES |
| 'root'@'::1' | def | EVENT | YES |
| 'root'@'localhost' | def | EVENT | YES |
| 'root'@'127.0.0.1' | def | EXECUTE | YES |
| 'root'@'::1' | def | EXECUTE | YES |
| 'root'@'localhost' | def | EXECUTE | YES |
| 'root'@'127.0.0.1' | def | FILE | YES |
| 'root'@'::1' | def | FILE | YES |
| 'root'@'localhost' | def | FILE | YES |
| 'root'@'localhost' | def | INDEX | YES |
| 'root'@'127.0.0.1' | def | INDEX | YES |
| 'root'@'::1' | def | INDEX | YES |
| 'root'@'::1' | def | INSERT | YES |
| 'root'@'localhost' | def | INSERT | YES |
| 'root'@'127.0.0.1' | def | INSERT | YES |
| 'root'@'127.0.0.1' | def | LOCK TABLES | YES |
| 'root'@'::1' | def | LOCK TABLES | YES |
| 'root'@'localhost' | def | LOCK TABLES | YES |
| 'root'@'127.0.0.1' | def | PROCESS | YES |
| 'root'@'::1' | def | PROCESS | YES |
| 'root'@'localhost' | def | PROCESS | YES |
| 'root'@'::1' | def | REFERENCES | YES |
| 'root'@'localhost' | def | REFERENCES | YES |
| 'root'@'127.0.0.1' | def | REFERENCES | YES |
| 'root'@'::1' | def | RELOAD | YES |
| 'root'@'localhost' | def | RELOAD | YES |
| 'root'@'127.0.0.1' | def | RELOAD | YES |
| 'root'@'::1' | def | REPLICATION CLIENT | YES |
| 'root'@'localhost' | def | REPLICATION CLIENT | YES |
| 'root'@'127.0.0.1' | def | REPLICATION CLIENT | YES |
| 'root'@'::1' | def | REPLICATION SLAVE | YES |
| 'root'@'localhost' | def | REPLICATION SLAVE | YES |
| 'root'@'127.0.0.1' | def | REPLICATION SLAVE | YES |
| 'root'@'127.0.0.1' | def | SELECT | YES |
| 'root'@'::1' | def | SELECT | YES |
| 'root'@'localhost' | def | SELECT | YES |
| 'root'@'127.0.0.1' | def | SHOW DATABASES | YES |
| 'root'@'::1' | def | SHOW DATABASES | YES |
| 'root'@'localhost' | def | SHOW DATABASES | YES |
| 'root'@'127.0.0.1' | def | SHOW VIEW | YES |
| 'root'@'::1' | def | SHOW VIEW | YES |
| 'root'@'localhost' | def | SHOW VIEW | YES |
| 'root'@'localhost' | def | SHUTDOWN | YES |
| 'root'@'127.0.0.1' | def | SHUTDOWN | YES |
| 'root'@'::1' | def | SHUTDOWN | YES |
| 'root'@'::1' | def | SUPER | YES |
| 'root'@'localhost' | def | SUPER | YES |
| 'root'@'127.0.0.1' | def | SUPER | YES |
| 'root'@'127.0.0.1' | def | TRIGGER | YES |
| 'root'@'::1' | def | TRIGGER | YES |
| 'root'@'localhost' | def | TRIGGER | YES |
| 'root'@'::1' | def | UPDATE | YES |
| 'root'@'localhost' | def | UPDATE | YES |
| 'root'@'127.0.0.1' | def | UPDATE | YES |
| ''@'localhost' | def | USAGE | NO | +--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)
DEFINITIVELY, a long answer and alot of scrolling.
Also I struggled hard to pass the output of the queries to a text file.
Here is how to do that without using the annoying into outfile
thing-
tee E:/sqllogfile.txt;
And when you are done, stop the logging-
tee off;
Hope it adds more clarity.
Warnings are annoying. As mentioned in other answers, you can suppress them using:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:
import warnings
warnings.filterwarnings("error")
But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:
import warnings
warnings.simplefilter(action='error', category=FutureWarning)
Following code works perfect for me
EfficientAdapter adp = (EfficientAdapter) QuickList.getAdapter();
adp.UpdateDataList(EfficientAdapter.MY_DATA);
adp.notifyDataSetChanged();
QuickList.invalidateViews();
QuickList.scrollBy(0, 0);
There are two ways to exit a method early (without quitting the program):
i) Use the return keyword.
ii) Throw an exception.
Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
for me only the following code works
.noBorder tr {
border-width: 0 ;
}
.ui-panelgrid td{
border-width: 0
}
<p:panelGrid id="userFormFields" columns="2" styleClass="noBorder" >
</p:panelGrid>
Caucho Quercus can run PHP code on the jvm.
I am not really sure why, but as soon as I comment out the following method it works:
connectionDidFinishDownloading:destinationURL:
Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.
It is probably failing because 1.0.0
is an annotated tag. Perhaps you saw the following error message:
error: Trying to write non-commit object to branch refs/heads/master
Annotated tags have their own distinct type of object that points to the tagged commit object. Branches can not usefully point to tag objects, only commit objects. You need to “peel” the annotated tag back to commit object and push that instead.
git push production +1.0.0^{commit}:master
git push production +1.0.0~0:master # shorthand
There is another syntax that would also work in this case, but it means something slightly different if the tag object points to something other than a commit (or a tag object that points to (a tag object that points to a …) a commit).
git push production +1.0.0^{}:master
These tag peeling syntaxes are described in git-rev-parse(1) under Specifying Revisions.
You can use microtime
and calculate the difference:
$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
Here's the PHP docs for microtime
: http://php.net/manual/en/function.microtime.php
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
The javadoc of the File
class describes the class as:
An abstract representation of file and directory pathnames.
File
is only a representation of a pathname, with a few methods concerning the filesystem (like exists()
) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.
(My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile
, causing much confusion with its inconsistent naming.)
A global Mutex is not only to ensure to have only one instance of an application. I personally prefer using Microsoft.VisualBasic to ensure single instance application like described in What is the correct way to create a single-instance WPF application? (Dale Ragan answer)... I found that's easier to pass arguments received on new application startup to the initial single instance application.
But regarding some previous code in this thread, I would prefer to not create a Mutex each time I want to have a lock on it. It could be fine for a single instance application but in other usage it appears to me has overkill.
That's why I suggest this implementation instead:
Usage:
static MutexGlobal _globalMutex = null;
static MutexGlobal GlobalMutexAccessEMTP
{
get
{
if (_globalMutex == null)
{
_globalMutex = new MutexGlobal();
}
return _globalMutex;
}
}
using (GlobalMutexAccessEMTP.GetAwaiter())
{
...
}
Mutex Global Wrapper:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
namespace HQ.Util.General.Threading
{
public class MutexGlobal : IDisposable
{
// ************************************************************************
public string Name { get; private set; }
internal Mutex Mutex { get; private set; }
public int DefaultTimeOut { get; set; }
public Func<int, bool> FuncTimeOutRetry { get; set; }
// ************************************************************************
public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)
{
return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);
}
// ************************************************************************
public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)
{
try
{
if (string.IsNullOrEmpty(specificName))
{
Name = Guid.NewGuid().ToString();
}
else
{
Name = specificName;
}
Name = string.Format("Global\\{{{0}}}", Name);
DefaultTimeOut = defaultTimeOut;
FuncTimeOutRetry = DefaultFuncTimeOutRetry;
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);
if (Mutex == null)
{
throw new Exception($"Unable to create mutex: {Name}");
}
}
catch (Exception ex)
{
Log.Log.Instance.AddEntry(Log.LogType.LogException, $"Unable to create Mutex: {Name}", ex);
throw;
}
}
// ************************************************************************
/// <summary>
///
/// </summary>
/// <param name="timeOut"></param>
/// <returns></returns>
public MutexGlobalAwaiter GetAwaiter(int timeOut)
{
return new MutexGlobalAwaiter(this, timeOut);
}
// ************************************************************************
/// <summary>
///
/// </summary>
/// <param name="timeOut"></param>
/// <returns></returns>
public MutexGlobalAwaiter GetAwaiter()
{
return new MutexGlobalAwaiter(this, DefaultTimeOut);
}
// ************************************************************************
/// <summary>
/// This method could either throw any user specific exception or return
/// true to retry. Otherwise, retruning false will let the thread continue
/// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to
/// take proper action depending on timeout or not.
/// </summary>
/// <param name="timeOutUsed"></param>
/// <returns></returns>
private bool DefaultFuncTimeOutRetry(int timeOutUsed)
{
// throw new TimeoutException($"Mutex {Name} timed out {timeOutUsed}.");
Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $"Mutex {Name} timeout: {timeOutUsed}.");
return true; // retry
}
// ************************************************************************
public void Dispose()
{
if (Mutex != null)
{
Mutex.ReleaseMutex();
Mutex.Close();
}
}
// ************************************************************************
}
}
Awaiter
using System;
namespace HQ.Util.General.Threading
{
public class MutexGlobalAwaiter : IDisposable
{
MutexGlobal _mutexGlobal = null;
public bool HasTimedOut { get; set; } = false;
internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)
{
_mutexGlobal = mutexEx;
do
{
HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);
if (! HasTimedOut) // Signal received
{
return;
}
} while (_mutexGlobal.FuncTimeOutRetry(timeOut));
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_mutexGlobal.Mutex.ReleaseMutex();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~MutexExAwaiter()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
Set the upper date to date + 1 day, so in your case, set it to 2011-02-01.
Something like this should work:
<%=Html.TextBox("test", new { style="width:50px" })%>
Or better:
<%=Html.TextBox("test")%>
<style type="text/css">
input[type="text"] { width:50px; }
</style>
I made a short answer, that sums up most of the above, to clean the uncertainty that was in my head as a beginner:
Opposed to Objective-C, no variable can contain nil in Swift, so the Optional variable type was added (variables suffixed by "?"):
var aString = nil //error
The big difference is that the Optional variables don't directly store values (as a normal Obj-C variables would) they contain two states: "has a value" or "has nil":
var aString: String? = "Hello, World!"
aString = nil //correct, now it contains the state "has nil"
That being, you can check those variables in different situations:
if let myString = aString? {
println(myString)
}
else {
println("It's nil") // this will print in our case
}
By using the "!" suffix, you can also access the values wrapped in them, only if those exist. (i.e it is not nil):
let aString: String? = "Hello, World!"
// var anotherString: String = aString //error
var anotherString: String = aString!
println(anotherString) //it will print "Hello, World!"
That's why you need to use "?" and "!" and not use all of them by default. (this was my biggest bewilderment)
I also agree with the answer above: Optional type cannot be used as a boolean.
This is gonna show all the stored procedures and the code:
select sch.name As [Schema], obj.name AS [Stored Procedure], code.definition AS [Code] from sys.objects as obj
join sys.sql_modules as code on code.object_id = obj.object_id
join sys.schemas as sch on sch.schema_id = obj.schema_id
where obj.type = 'P'
Hope this will help you
Cast(columnName as Numeric(10,2))
or
Cast(@s as decimal(10,2))
I am not getting why you want to cast to varchar?.If you cast to varchar again convert back to decimail for two
decimal points
By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.
On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.
Something like that I am using:
namespace System.Net.Sockets
{
public class TcpConnection : IDisposable
{
public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
public event EvHandler<TcpConnection> Drop = delegate { };
private const int IntSize = 4;
private const int BufferSize = 8 * 1024;
private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
private readonly TcpClient _tcpClient;
private readonly object _droppedRoot = new object();
private bool _dropped;
private byte[] _incomingData = new byte[0];
private Nullable<int> _objectDataLength;
public TcpClient TcpClient { get { return _tcpClient; } }
public bool Dropped { get { return _dropped; } }
private void DropConnection()
{
lock (_droppedRoot)
{
if (Dropped)
return;
_dropped = true;
}
_tcpClient.Close();
_syncContext.Post(delegate { Drop(this); }, null);
}
public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
public void SendData(PCmds pCmd, object[] datas)
{
datas.ThrowIfNull();
SendDataInternal(new object[] { pCmd }.Append(datas));
}
private void SendDataInternal(object data)
{
if (Dropped)
return;
byte[] bytedata;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
try { bf.Serialize(ms, data); }
catch { return; }
bytedata = ms.ToArray();
}
try
{
lock (_tcpClient)
{
TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
}
}
catch { DropConnection(); }
}
private void EndSend(IAsyncResult ar)
{
try { TcpClient.Client.EndSend(ar); }
catch { }
}
public TcpConnection(TcpClient tcpClient)
{
_tcpClient = tcpClient;
StartReceive();
}
private void StartReceive()
{
byte[] buffer = new byte[BufferSize];
try
{
_tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
}
catch { DropConnection(); }
}
private void DataReceived(IAsyncResult ar)
{
if (Dropped)
return;
int dataRead;
try { dataRead = TcpClient.Client.EndReceive(ar); }
catch
{
DropConnection();
return;
}
if (dataRead == 0)
{
DropConnection();
return;
}
byte[] byteData = ar.AsyncState as byte[];
_incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
bool exitWhile = false;
while (exitWhile)
{
exitWhile = true;
if (_objectDataLength.HasValue)
{
if (_incomingData.Length >= _objectDataLength.Value)
{
object data;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
try { data = bf.Deserialize(ms); }
catch
{
SendData(PCmds.Disconnect);
DropConnection();
return;
}
_syncContext.Post(delegate(object T)
{
try { DataArrive(this, new DataArrivedEventArgs(T)); }
catch { DropConnection(); }
}, data);
_incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
_objectDataLength = null;
exitWhile = false;
}
}
else
if (_incomingData.Length >= IntSize)
{
_objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
_incomingData = _incomingData.TrimLeft(IntSize);
exitWhile = false;
}
}
StartReceive();
}
public void Dispose() { DropConnection(); }
}
}
That is just an example, you should edit it for your use.
I find that if I specify .row:nth-of-type(..)
, my other row's elements (for other formatting, etc) also get alternating colours. So rather, I'd define in my css an entirely new class:
.row-striped:nth-of-type(odd){
background-color: #efefef;
}
.row-striped:nth-of-type(even){
background-color: #ffffff;
}
So now, the alternating row colours will only apply to the row container, when I specify its class as .row-striped
, and not the elements inside the row
.
<!-- this entire row container is #efefef -->
<div class="row row-striped">
<div class="form-group">
<div class="col-sm-8"><h5>Field Greens with strawberry vinegrette</h5></div>
<div class="col-sm-4">
<input type="number" type="number" step="1" min="0"></input><small>$30/salad</small>
</div>
</div>
</div>
<!-- this entire row container is #ffffff -->
<div class="row row-striped">
<div class="form-group">
<div class="col-sm-8"><h5>Greek Salad</h5></div>
<div class="col-sm-4">
<input type="number" type="number" step="1" min="0"></input><small>$25/salad</small>
</div>
</div>
</div>
If everyone agrees that
return
is not necessary at the end of a function's bodyreturn
is marginally faster (according to @Alan's test, 4.3 microseconds versus 5.1)should we all stop using return
at the end of a function? I certainly won't, and I'd like to explain why. I hope to hear if other people share my opinion. And I apologize if it is not a straight answer to the OP, but more like a long subjective comment.
My main problem with not using return
is that, as Paul pointed out, there are other places in a function's body where you may need it. And if you are forced to use return
somewhere in the middle of your function, why not make all return
statements explicit? I hate being inconsistent. Also I think the code reads better; one can scan the function and easily see all exit points and values.
Paul used this example:
foo = function() {
if(a) {
return(a)
} else {
return(b)
}
}
Unfortunately, one could point out that it can easily be rewritten as:
foo = function() {
if(a) {
output <- a
} else {
output <- b
}
output
}
The latter version even conforms with some programming coding standards that advocate one return statement per function. I think a better example could have been:
bar <- function() {
while (a) {
do_stuff
for (b) {
do_stuff
if (c) return(1)
for (d) {
do_stuff
if (e) return(2)
}
}
}
return(3)
}
This would be much harder to rewrite using a single return statement: it would need multiple break
s and an intricate system of boolean variables for propagating them. All this to say that the single return rule does not play well with R. So if you are going to need to use return
in some places of your function's body, why not be consistent and use it everywhere?
I don't think the speed argument is a valid one. A 0.8 microsecond difference is nothing when you start looking at functions that actually do something. The last thing I can see is that it is less typing but hey, I'm not lazy.
Simple solution would be to remove padding from .panel-heading
and add to .panel-title a
.
.panel-heading {
padding: 0;
}
.panel-title a {
display: block;
padding: 10px 15px;
}
This solution is similar to the above one posted by calfzhou, slightly different.
Old post but I figured i could contribute anyway.
A script is arguably not necessary and with some tolerance to wild cards could be carried out from the command line.
wild anywhere matching. Lets remove any occurrence of sub "folder"
$ rm -rf ~/*/folder/*
Shell iterated. Lets remove the specific pre and post folders with one line
$ rm -rf ~/foo{1,2,3}/folder/{ab,cd,ef}
Shell iterated + var (BASH tested).
$ var=bar rm -rf ~/foo{1,2,3}/${var}/{ab,cd,ef}
The GPS icon seems to change its state according to received broadcast intents. You can change its state yourself with the following code samples:
Notify that the GPS has been enabled:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
Notify that the GPS is receiving fixes:
Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
Notify that the GPS is no longer receiving fixes:
Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
Notify that the GPS has been disabled:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
Example code to register receiver to the intents:
// MyReceiver must extend BroadcastReceiver
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter("android.location.GPS_ENABLED_CHANGE");
filter.addAction("android.location.GPS_FIX_CHANGE");
registerReceiver(receiver, filter);
By receiving these broadcast intents you can notice the changes in GPS status. However, you will be notified only when the state changes. Thus it is not possible to determine the current state using these intents.
You can use tool I've created to make this process easier: git-squash. For example to squash all commits on feature branch that has been branched from master branch, write:
git squash master
git push --force
After looking through all the answers, I found a slightly different way with minimum CSS and no JS, only the height of the header needs to be set correctly in #content
, in this case 60px
CSS:
#header {
position: fixed;
width: 100%;
top: 0;
z-index: 10;
}
#content {
margin-top: 60px;
z-index:1;
}
HTML:
<body>
<div id="header" style="background-color:GRAY; text-align:center; border-bottom:1px SOLID BLACK; color:WHITE; line-height:50px; font-size:40px">
My Large Static Header
</div>
<div id="content">
<!-- All page content here -->
</div>
</body>
The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.
Java EE 7 has a JSON API in javax.json
, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject
or a JsonArray
.
import javax.json.*;
JsonObject value = Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", Json.createObjectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021"))
.add("phoneNumber", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(Json.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();
But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.
I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.
outerLink {
overflow: hidden;
position: relative;
}
outerLink:hover:after {
background: #000;
content: "";
display: block;
height: 100%;
left: 0;
opacity: 0.5;
position: absolute;
top: 0;
width: 100%;
}
Opera Blocker and others check all files/urls in Network. Then compares to the list. It is EasyPrivacy and EasyList. If your file/url in this, your will be ban. Good luck.
So... I find FilterLists for all addBlockers!
I work with gcc 7.2. I specifically needed a function to be non-inlined, because it had to be instantiated in a library. I tried the __attribute__((noinline))
answer, as well as the asm("")
answer. Neither one solved the problem.
Finally, I figured that defining a static variable inside the function will force the compiler to allocate space for it in the static variable block, and to issue an initialization for it when the function is first called.
This is sort of a dirty trick, but it works.
you can use grep, then take lines in jumps:
grep -A1 'blah' logfile | awk 'NR%3==2'
you can also take n lines after match, for example:
seq 100 | grep -A3 .2 | awk 'NR%5==4'
15
25
35
45
55
65
75
85
95
explanation -
here we want to grep all lines that are *2 and take 3 lines after it, which is *5.
seq 100 | grep -A3 .2
will give you:
12
13
14
15
--
22
23
24
25
--
...
the number in the modulo (NR%5) is the added rows by grep (here it's 3 by the flag -A3), +2 extra lines because you have current matching line and also the -- line that the grep is adding.
I created the following Contains function using reflect package. This function can be used for various types like int32 or struct etc.
// Contains returns true if an element is present in a slice
func Contains(list interface{}, elem interface{}) bool {
listV := reflect.ValueOf(list)
if listV.Kind() == reflect.Slice {
for i := 0; i < listV.Len(); i++ {
item := listV.Index(i).Interface()
target := reflect.ValueOf(elem).Convert(reflect.TypeOf(item)).Interface()
if ok := reflect.DeepEqual(item, target); ok {
return true
}
}
}
return false
}
Usage of contains function is below
// slice of int32
containsInt32 := Contains([]int32{1, 2, 3, 4, 5}, 3)
fmt.Println("contains int32:", containsInt32)
// slice of float64
containsFloat64 := Contains([]float64{1.1, 2.2, 3.3, 4.4, 5.5}, 4.4)
fmt.Println("contains float64:", containsFloat64)
// slice of struct
type item struct {
ID string
Name string
}
list := []item{
item{
ID: "1",
Name: "test1",
},
item{
ID: "2",
Name: "test2",
},
item{
ID: "3",
Name: "test3",
},
}
target := item{
ID: "2",
Name: "test2",
}
containsStruct := Contains(list, target)
fmt.Println("contains struct:", containsStruct)
// Output:
// contains int32: true
// contains float64: true
// contains struct: true
Please see here for more details: https://github.com/glassonion1/xgo/blob/main/contains.go
worked for me to use manual transaction handling for the loop(postgres 9.1):
from django.db import transaction
with transaction.commit_on_success():
for item in items:
MyModel.objects.create(name=item.name)
in fact it's not the same, as 'native' database bulk insert, but it allows you to avoid/descrease transport/orms operations/sql query analyse costs
Running Visual Studio as administrator could fix the issue, but if you use Visual Studio with for example TortoiseSVN, you cannot commit any changes. Another possible solution would be to run the service as administrator and the rest Visual Studio as local user.
Use "for"
attribute of label
for input
.
<div>
<label for="files" class="btn">Select Image</label>
<input id="files" style="visibility:hidden;" type="file">
</div>
Below is the code to fetch name of the uploaded file
$("#files").change(function() {_x000D_
filename = this.files[0].name_x000D_
console.log(filename);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<label for="files" class="btn">Select Image</label>_x000D_
<input id="files" style="visibility:hidden;" type="file">_x000D_
</div>
_x000D_
Actually you can pass a parameter ( http://docs.angularjs.org/api/ng.filter:filter ) and don't need a custom function just for this. If you rewrite your HTML as below it'll work:
<div ng:app>
<div ng-controller="HelloCntl">
<ul>
<li ng-repeat="friend in friends | filter:{name:'!Adam'}">
<span>{{friend.name}}</span>
<span>{{friend.phone}}</span>
</li>
</ul>
</div>
</div>
If you want to use jQuery File Download , please note this for IE. You need to reset the response or it will not download
//The IE will only work if you reset response
getServletResponse().reset();
//The jquery.fileDownload needs a cookie be set
getServletResponse().setHeader("Set-Cookie", "fileDownload=true; path=/");
//Do the reset of your action create InputStream and return
Your action can implement ServletResponseAware
to access getServletResponse()
Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.
try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
// Here I was hoping to get an error code.
if (ExceptionContainsErrorCode(e, 10004))
{
// Execute desired actions
}
}
...
private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
Win32Exception winEx = e as Win32Exception;
if (winEx != null && ErrorCode == winEx.ErrorCode)
return true;
if (e.InnerException != null)
return ExceptionContainsErrorCode(e.InnerException, ErrorCode);
return false;
}
This code has been unit tested.
I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.
Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:
tar cvf allfiles.tar $(cat mylist.txt)
I think there is no need to specify
'http://localhost:8080`"
in the URI part.. because. if you specify it, You'll have to change it manually for every environment.
Only
"/restws/json/product/get" also works
<!DOCTYPE html>
<html>
<title>Welcome</title>
<style type="text/css">
.head1 {
width:300px;
border-right:1px solid #333;
float:left;
height:500px;
}
.head2 {
float:left;
padding-left:100PX;
padding-top:10PX;
}
</style>
<body>
<h1 class="head1">Ramya</h1>
<h2 class="head2">Reddy</h2>
</body>
</html>
I think you should be able to use the HTML escape character (&). They can be found at http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
Background
We started getting this today when we switched our WCF service from AnyCPU to x64 on a Windows 2012 R2 server running IIS 6.2.
First we checked the only referenced assembly 10 times, to ensure it was not actually an x86 dll. Next we checked the application pool many times to ensure it was not enabling 32 bit applications.
On a whim I tried toggling the setting. It turns out the application pools in IIS were defaulting to an Enable 32-Bit Applications value of False, but IIS was ignoring it on our server for some reason and always ran our service in x86 mode.
Solution
In your screenshot, you didn't specify any module: try setting "libsystem_c.dylib"
I did that, and it works : breakpoint stops here (although the stacktrace often rise from some obscure system lib...)
Here is one simple example.. you can download and test it http://www.pretechsol.com/2014/12/java-ee-websocket-simple-example.html
I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:
DisplayAttribute
System.ComponentModel.DataAnnotations
namespace in the System.ComponentModel.DataAnnotations.dll
assemblyDescription
or ShortName
DisplayNameAttribute
System.ComponentModel
namespace in System.dll
The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute
has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.
DisplayAttribute
was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.
EDIT: Looks like latest .NET Core source allows DisplayAttribute
to be used on classes now as well.
After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.
# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]
# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]
# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...
Requirements:
Assuming your example document is in the string variable doc
> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1
Above solutions did not work for bitbucket. I figured this does the trick:
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts \
&& eval `ssh-agent` \
&& ssh-add ~/.ssh/[key] \
&& git clone [email protected]:[team]/[repo].git
In addition to VonC's answer, you could tweak it to your liking even further.
After fetching from the remote branch, you would still have to merge the commits. I would replace
$ git fetch upstream
with
$ git pull upstream master
since git pull is essentially git fetch + git merge.
If MS SQL Server Express Edition is being used then SQL Server Agent is not available. I found the following worked for all editions:
USE Master
GO
IF EXISTS( SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MyBackgroundTask]
GO
CREATE PROCEDURE MyBackgroundTask
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- The interval between cleanup attempts
declare @timeToRun nvarchar(50)
set @timeToRun = '03:33:33'
while 1 = 1
begin
waitfor time @timeToRun
begin
execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
end
end
END
GO
-- Run the procedure when the master database starts.
sp_procoption @ProcName = 'MyBackgroundTask',
@OptionName = 'startup',
@OptionValue = 'on'
GO
Some notes:
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
And then you can use it like this:
int foo = B(1010);
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
Proof:
The following code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
View
objects are the basic building blocks of User Interface(UI) elements in Android.View
is a simple rectangle box which responds to the user's actions.EditText
, Button
, CheckBox
etc..View
refers to the android.view.View
class, which is the base class of all UI classes. ViewGroup
is the invisible container. It holds View
and ViewGroup
LinearLayout
is the ViewGroup
that contains Button(View), and other Layouts also.ViewGroup
is the base class for Layouts.Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id
(int), image
(blob) and image_name
(varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string()
, otherwise it will result in a syntax error.
For those using the very popular Json.Net project from Newtonsoft the task is trivial:
using Newtonsoft.Json;
....
var s = JsonConvert.ToString(@"a\b");
Console.WriteLine(s);
....
This code prints:
"a\\b"
That is, the resulting string value contains the quotes as well as the escaped backslash.
Public Function GetRange(ByVal sListName As String) As String
Dim oListObject As ListObject
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
For Each ws In wb.Sheets
For Each oListObject In ws.ListObjects
If oListObject.Name = sListName Then
GetRange = "[" & ws.Name & "$" & Replace(oListObject.Range.Address, "$", "") & "]"
Exit Function
End If
Next oListObject
Next ws
End Function
In your SQL use it like this
sSQL = "Select * from " & GetRange("NameOfTable") & ""
There exists two daemons that detect these events:
ifplugd and netplugd
You can't run two SQL statements into one like you are doing.
You can't "execute" a select query.
db is an object and you haven't set it to anything: (e.g. set db = currentdb)
In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.
You might want to be a bit more specific about the date you are inserting:
INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"
You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:
VAR=$(scan)
Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.
Preserving trailing Newlines:
One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.
function scan2 () {
local nl=$'\x0a'; # that's just \n
echo "output${nl}${nl}" # 2 in the string + 1 by echo
}
# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"
echo "${VAR}---"
prints (3 newlines kept):
output
---
Use an output parameter: avoiding the subshell (and preserving newlines)
If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref
. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.
function scan3() {
local -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
VAR="some prior value which will get overwritten"
# you pass the name of the variable. VAR will be modified.
scan3 VAR
# newlines are also preserved.
echo "${VAR}==="
prints:
output
===
This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.
Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"
This is relevant. https://stackoverflow.com/a/38997681/5556676
I use apache common IO to read a text file into a single string
String str = FileUtils.readFileToString(file);
simple and "clean". you can even set encoding of the text file with no hassle.
String str = FileUtils.readFileToString(file, "UTF-8");
openURL(:) was deprecated in iOS 10.0, instead you should use the following instance method on UIApplication: open(:options:completionHandler:)
Example using Swift
This will open "https://apple.com" in Safari.
if let url = URL(string: "https://apple.com") {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
https://developer.apple.com/reference/uikit/uiapplication/1648685-open
If you want to pick columns from a ps output, any reason to not use -o?
e.g.
ps ax -o pid,vsz
ps ax -o pid,cmd
Minimum column width allocated, no padding, only single space field separator.
ps ax --no-headers -o pid:1,vsz:1,cmd
3443 24600 -bash
8419 0 [xfsalloc]
8420 0 [xfs_mru_cache]
8602 489316 /usr/sbin/apache2 -k start
12821 497240 /usr/sbin/apache2 -k start
12824 497132 /usr/sbin/apache2 -k start
Pid and vsz given 10 char width, 1 space field separator.
ps ax --no-headers -o pid:10,vsz:10,cmd
3443 24600 -bash
8419 0 [xfsalloc]
8420 0 [xfs_mru_cache]
8602 489316 /usr/sbin/apache2 -k start
12821 497240 /usr/sbin/apache2 -k start
12824 497132 /usr/sbin/apache2 -k start
Used in a script:-
oldpid=12824
echo "PID: ${oldpid}"
echo "Command: $(ps -ho cmd ${oldpid})"
Here is a solution without using Jquery
var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
// Class exists
}
reference link
Another option would be file_get_contents()
:
// $xml_str = your xml
// $url = target url
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
For posterity sake,the answer maybe too late.You should check for the return value of the variable and throw an exception. In that case you are assured that the program will jump from where the exception is being raised to the catch block. Find below.
try{
$tableAresults = $dbHandler->doSomethingWithTableA();
if (!tableAresults)
throw new Exception('Problem with tableAresults');
$tableBresults = $dbHandler->doSomethingElseWithTableB();
if (!tableBresults)
throw new Exception('Problem with tableBresults');
} catch (Exception $e) {
echo $e->getMessage();
}
I've encountered similar problem on Ubuntu 16.04 and was able to solve it by creating a folder named "default-java" in /usr/lib/jvm
and copying into it all the contents of the /usr/lib/jvm/java-8-oracle
. I opted for this solution as correcting JAVA_HOME environment variable turned out to be of no use.
You could also use the parse_date_time
function from the lubridate
package:
library(lubridate)
day<-"31/08/2011"
as.Date(parse_date_time(day,"dmy"))
[1] "2011-08-31"
parse_date_time
returns a POSIXct object, so we use as.Date
to get a date object. The first argument of parse_date_time
specifies a date vector, the second argument specifies the order in which your format occurs. The orders
argument makes parse_date_time
very flexible.
If you are using Git Gui on windows,
It allows you to use a C# keyword as a variable. For example:
class MyClass
{
public string name { get; set; }
public string @class { get; set; }
}
At the beginning of your script you can add.
ini_set('MAX_EXECUTION_TIME', '-1');
There are multiple easy ways.
Just touch web.xml of any webapp.
touch /usr/share/tomcat/webapps/<WEBAPP-NAME>/WEB-INF/web.xml
You can also update a particular jar file in WEB-INF/lib and then touch web.xml, rather than building whole war file and deploying it again.
Delete webapps/YOUR_WEB_APP directory, Tomcat will start deploying war within 5 seconds (assuming your war file still exists in webapps folder).
Generally overwriting war file with new version gets redeployed by tomcat automatically. If not, you can touch web.xml as explained above.
Copy over an already exploded "directory" to your webapps folder
Explanation:
This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video>
or <audio>
tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.
Solution 1:
You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto"
.
Solution 2:
If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.
Solution 3: Force-open Sockets (Not recommended)
If you must, you can force-open the sockets in your browser (In Chrome only):
chrome://net-internals
.Sockets
from the menu.Flush socket pools
button.This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.
Observable
, Observer
)ContainerAdapter
, ComponentAdapter
, FocusAdapter
, KeyAdapter
, MouseAdapter
are not adapters; they are actually Null Objects. Poor naming choice by Sun.BufferedInputStream
can decorate other streams such as FilterInputStream
)java.lang.Runtime#getRuntime()
is SingletonButtonGroup
for Mediator patternAction
, AbstractAction
may be used for different visual representations to execute same code -> Command patternand many more I guess
If you're using Java 8, @JodaStephen's answer is obviously the best. However, if you're working with the JSR-310 backport, you unfortunately have to do something like this:
Date input = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(input);
LocalDate date = LocalDate.of(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH));
127.0.0.1,6283
Add a comma between the ip and port
Just for the record..
It is actually not a solution to your code, but I had the same error message when incorrectly accessing the method of a class instance pointed to by myPointerToClass
, e.g.
MyClass* myPointerToClass = new MyClass();
myPointerToClass.aMethodOfThatClass();
where
myPointerToClass->aMethodOfThatClass();
would obviously be correct.
You should check out Losswise (https://losswise.com), it has a plugin for Keras that's easier to use than Tensorboard and has some nice extra features. With Losswise you'd just use from losswise.libs import LosswiseKerasCallback
and then callback = LosswiseKerasCallback(tag='my fancy convnet 1')
and you're good to go (see https://docs.losswise.com/#keras-plugin).
You can't call _doPostBack()
because it forces submition of the form. Why don't you disable the PostBack
on the UpdatePanel
?
For Mac Users
I am using Mac and I was facing the same problem while I was trying to push a project from Android Studio. The reason for that is another user had previously logged into GitHub and his credentials were saved in Keychain Access.
The solution is to delete all the information store in keychain for that process
Some more info for Browser window : http://www.w3schools.com/js/js_window.asp?output=print
Why would you want to put a submit button inside an anchor? You are either trying to submit a form or go to a different page. Which one is it?
Either submit the form:
<input type="submit" class="button_active" value="1" />
Or go to another page:
<input type="button" class="button_active" onclick="location.href='1.html';" />
Using:
SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
...will show you the ctn_no
value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:
SELECT t.ctn_no
FROM YOUR_TABLE t
WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
If you want to see the other column values associated with the duplicate, you'll want to use a self join:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no
Suppose you bound your combobox to a List<Person>
List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource
pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;
Of course this means that you need to add a checking code when you try to use the info from the combobox
if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
MessageBox.Show("Please select a person name");
else
......
The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection
In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to
DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);
As stated in other answers, label is an inline element. However, you can apply display: inline-block
to the label and then center with text-align
.
#name_label {
display: inline-block;
width: 90%;
text-align: right;
}
Why display: inline-block
and not display: inline
? For the same reason that you can't align label
, it's inline.
Why display: inline-block
and not display: block
? You could use display: block
, but it will be on another line. display: inline-block
combines the properties of inline
and block
. It's inline, but you can also give it a width, height, and align it.
Could not edit the accepted response so adding it as an answer here,
to restore the file in git, use the following (note the '^' sign just after the SHA)
git checkout <SHA>^ -- /path/to/file
This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.
The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin
and xmax
are in the range [0,1].
On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin
and xmax
are the in the range of data limit of x axis.
Let's take a concrete example,
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')
plt.show()
It will produce the following plot:
The value for xmin
and xmax
are the same for the axhline
and hlines
method. But the length of produced line is different.
Put this in your CSS:
white-space:nowrap;
Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space
white-space
The white-space
property declares how white space inside the element is handled.
Values
normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.
pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.
nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.
pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
inherit
Takes the same specified value as the property for the element's parent.
Change the image source using jQuery click()
element:
<img class="letstalk btn" src="images/chatbuble.png" />
code:
$(".letstalk").click(function(){
var newsrc;
if($(this).attr("src")=="/images/chatbuble.png")
{
newsrc="/images/closechat.png";
$(this).attr("src", newsrc);
}
else
{
newsrc="/images/chatbuble.png";
$(this).attr("src", newsrc);
}
});
Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.
The arguments
object is where the functions arguments are stored.
The arguments object acts and looks like an array, it basically is, it just doesn't have the methods that arrays do, for example:
Array.forEach(callback[, thisArg]);
Array.map(callback[, thisArg])
Array.filter(callback[, thisArg]);
Array.indexOf(searchElement[, fromIndex])
I think the best way to convert a arguments
object to a real Array is like so:
argumentsArray = [].slice.apply(arguments);
That will make it an array;
reusable:
function ArgumentsToArray(args) {
return [].slice.apply(args);
}
(function() {
args = ArgumentsToArray(arguments);
args.forEach(function(value) {
console.log('value ===', value);
});
})('name', 1, {}, 'two', 3)
result:
>
value === name
>value === 1
>value === Object {}
>value === two
>value === 3