Since I've asked this question, I've started using python-symmetric-jsonrpc. It is quite good, can be used between python and non-python software and follow the JSON-RPC standard. But it lacks some examples.
The Problem to push mostly is because of the size of the files that need to be pushed. I was trying to push some libraries of just size 2 mb, then too the push was giving error of RPC with result 7. The line is of 4 mbps and is working fine. Some subsequent tries to the push got me success. If such error comes, wait for few minutes and keep on trying.
I also found out that there are some RPC failures if the github is down or is getting unstable network at their side.
So keeping up trying after some intervals is the only option!
The main scenario where JAX-WS RPC and Document style are used as follows:
The Remote Procedure Call (RPC) pattern is used when the consumer views the web service as a single logical application or component with encapsulated data. The request and response messages map directly to the input and output parameters of the procedure call.
Examples of this type the RPC pattern might include a payment service or a stock quote service.
The document-based pattern is used in situations where the consumer views the web service as a longer running business process where the request document represents a complete unit of information. This type of web service may involve human interaction for example as with a credit application request document with a response document containing bids from lending institutions. Because longer running business processes may not be able to return the requested document immediately, the document-based pattern is more commonly found in asynchronous communication architectures. The Document/literal variation of SOAP is used to implement the document-based web service pattern.
Byte Stream - Stream is sequence of data. Input stream - reads data from source. Output stream - writes data to desitnation. Java Byte Streams are used to perform input/output byte by byte(8bits at a time). A byte stream is suitable for processing raw data like binary files. Java Character Streams are used to perform input/output 2 bytes at a time, because Characters are stored using Unicode conventions in Java with 2 bytes for each character. Character stream is useful when we process(read/write) text files.
RMI(Remote Method Invocation) - an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM.
Both Serialization and Marshalling are loosely used as synonyms. Here are few differences.
Serialization - Data members of an object is written to binary form or Byte Stream(and then can be written in file/memory/database etc). No information about data-types can be retained once object data members are written to binary form.
Marshalling - Object is serialized(to byte stream in binary format) with data-type + Codebase attached and then passed Remote Object(RMI). Marshalling will transform the data-type into a predetermined naming convention so that it can be reconstructed with respect to the initial data-type.
So Serialization is part of Marshalling.
CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location. (Copied from @Nasir answer)
Serialization is almost like a stupid memory-dump of the memory used by the object(s), while Marshalling stores information about custom data-types.
In a way, Serialization performs marshalling with implematation of pass-by-value because no information of data-type is passed, just the primitive form is passed to byte stream.
Serialization may have some issues related to big-endian, small-endian if the stream is going from one OS to another if the different OS have different means of representing the same data. On the other hand, marshalling is perfectly fine to migrate between OS because the result is a higher-level representation.
The fundamental problem with RPC is coupling. RPC clients become tightly coupled to service implementation in several ways and it becomes very hard to change service implementation without breaking clients:
On the other hand in REST style it's very easy to guide clients by including control information in representations(HTTP headers + representation). For example:
There are many more differences and advantages on the REST side.
The main difference between RPC and RMI is that RMI involves objects. Instead of calling procedures remotely by use of a proxy function, we instead use a proxy object.
There is greater transparency with RMI, namely due the exploitation of objects, references, inheritance, polymorphism, and exceptions as the technology is integrated into the language.
RMI is also more advanced than RPC, allowing for dynamic invocation, where interfaces can change at runtime, and object adaption, which provides an additional layer of abstraction.
As far as your question goes: no, if activating from .ini
is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap
, yum install php-soap
). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).
In general, the double-dash --switches
are designed to be used when recompiling PHP from scratch.
You would download the PHP source package (as a compressed .tgz
tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script
./configure --prefix ...
The configure
command used by your PHP may be shown with phpinfo()
. Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap
will then enable SOAP in addition to everything else.
That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype
, gd
, libjpeg
, XML
, expat
, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg
installed might not be enough, and you might need libjpeg-dev
also).
I have to keep a separate virtual machine with everything installed for my recompilation purposes.
Try this:
USE YourDB;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE YourDB
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 50 MB.
DBCC SHRINKFILE (YourDB_log, 50);
GO
-- Reset the database recovery model.
ALTER DATABASE YourDB
SET RECOVERY FULL;
GO
I hope it helps.
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
$('#demoTable td').contents().each(function() {
if (this.nodeType === 3) {
this.textContent
? this.textContent = 'The text has been '
: this.innerText = 'The text has been '
} else {
this.innerHTML = 'changed';
return false;
}
})
I have used a tool in my work its LDRA tool suite
It is used for testing the c/c++ code but it also can check against coding standards such as MISRA etc.
If CURLOPT_FAILONERROR
is false
, http errors will not trigger curl
errors.
<?php
if (@$_GET['curl']=="yes") {
header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
$ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$response=curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errno= curl_errno($ch);
if ($http_status==503)
echo "HTTP Status == 503 <br/>";
echo "Curl Errno returned $curl_errno <br/>";
}
In Java there is no good reason.
A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:
if (o = null)
will not compile.
The only time this could matter in Java is if the variable is boolean:
int m1(boolean x)
{
if (x = true) // oops, assignment instead of equality
Try that:
$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');
Spring Docs explain that
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.
Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.
Another way is user BeanSelfAware
Try to make your javascript unobtrusive :
i had the same problem and found another little workaround: i have a provisioner script that is added form the docker build environment. In the script i set the environment variable dependent on a ping check:
Dockerfile:
ADD script.sh /tmp/script.sh
RUN /tmp/script.sh
script.sh:
if ping -c 1 ix.de ; then
echo "direct internet doing nothing"
else
echo "proxy environment detected setting proxy"
export http_proxy=<proxy address>
fi
this is still somewhat crude but worked for me
Probably not as fast as with buffered I/O, but quite terse:
String content;
try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
content = scanner.next();
}
The \Z
pattern tells the Scanner
that the delimiter is EOF.
Applies to Bootstrap 3 only.
Ignoring the letters (xs, sm, md, lg) for now, I'll start with just the numbers...
col-*-6
spans 6 of 12 columns (half the width), col-*-12
spans 12 of 12 columns (the entire width), etcSo, if you want two equal columns to span a div, write
<div class="col-xs-6">Column 1</div>
<div class="col-xs-6">Column 2</div>
Or, if you want three unequal columns to span that same width, you could write:
<div class="col-xs-2">Column 1</div>
<div class="col-xs-6">Column 2</div>
<div class="col-xs-4">Column 3</div>
You'll notice the # of columns always add up to 12. It can be less than twelve, but beware if more than 12, as your offending divs will bump down to the next row (not .row
, which is another story altogether).
You can also nest columns within columns, (best with a .row
wrapper around them) such as:
<div class="col-xs-6">
<div class="row">
<div class="col-xs-4">Column 1-a</div>
<div class="col-xs-8">Column 1-b</div>
</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-2">Column 2-a</div>
<div class="col-xs-10">Column 2-b</div>
</div>
</div>
Each set of nested divs also span up to 12 columns of their parent div. NOTE: Since each .col
class has 15px padding on either side, you should usually wrap nested columns in a .row
, which has -15px margins. This avoids duplicating the padding and keeps the content lined up between nested and non-nested col classes.
-- You didn't specifically ask about the xs, sm, md, lg
usage, but they go hand-in-hand so I can't help but touch on it...
In short, they are used to define at which screen size that class should apply:
Read the "Grid Options" chapter from the official Bootstrap documentation for more details.
You should usually classify a div using multiple column classes so it behaves differently depending on the screen size (this is the heart of what makes bootstrap responsive). eg: a div with classes col-xs-6
and col-sm-4
will span half the screen on the mobile phone (xs) and 1/3 of the screen on tablets(sm).
<div class="col-xs-6 col-sm-4">Column 1</div> <!-- 1/2 width on mobile, 1/3 screen on tablet) -->
<div class="col-xs-6 col-sm-8">Column 2</div> <!-- 1/2 width on mobile, 2/3 width on tablet -->
NOTE: as per comment below, grid classes for a given screen size apply to that screen size and larger unless another declaration overrides it (i.e. col-xs-6 col-md-4
spans 6 columns on xs
and sm
, and 4 columns on md
and lg
, even though sm
and lg
were never explicitly declared)
NOTE: if you don't define xs
, it will default to col-xs-12
(i.e. col-sm-6
is half the width on sm
, md
and lg
screens, but full-width on xs
screens).
NOTE: it's actually totally fine if your .row
includes more than 12 cols, as long as you are aware of how they will react. --This is a contentious issue, and not everyone agrees.
Using &
operator, don't forget to wrap the sub-statements with ()
:
males = df[(df[Gender]=='Male') & (df[Year]==2014)]
To store your dataframes in a dict
using a for loop:
from collections import defaultdict
dic={}
for g in ['male', 'female']:
dic[g]=defaultdict(dict)
for y in [2013, 2014]:
dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict
A demo for your getDF
:
def getDF(dic, gender, year):
return dic[gender][year]
print genDF(dic, 'male', 2014)
I tried find similiar as topic first post.
For my needs I find this
http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/
"\b[a-zA-Z0-9]{3}\b"
3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "
Use the change event of the select:
$('#my_select').change(function()
{
$(this).parents('td').css('background', '#000000');
});
I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string string.printable
(part of the built-in string
module). The use of compiled '[\W_]+'
and pattern.sub('', str)
was found to be fastest.
$ python -m timeit -s \
"import string" \
"''.join(ch for ch in string.printable if ch.isalnum())"
10000 loops, best of 3: 57.6 usec per loop
$ python -m timeit -s \
"import string" \
"filter(str.isalnum, string.printable)"
10000 loops, best of 3: 37.9 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]+', '', string.printable)"
100000 loops, best of 3: 15 usec per loop
$ python -m timeit -s \
"import re, string; pattern = re.compile('[\W_]+')" \
"pattern.sub('', string.printable)"
100000 loops, best of 3: 11.2 usec per loop
DELETE FROM table WHERE edit_user IS NULL;
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
I use LuaSocket to get more precision.
require "socket"
print("Milliseconds: " .. socket.gettime()*1000)
This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).
Form.Close() is use to close an instance of a Form with in .NET application it does not kill the entire application. Application.exit() kills your application.
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
Just to add to the other answers, if you would prefer to return a vector rather than a dataframe, you have the following options:
dplyr < 0.7.0
Enclose the dplyr functions in a parentheses and combine it with $
syntax:
(mtcars %>% distinct(cyl))$cyl
dplyr >= 0.7.0
Use the pull
verb:
mtcars %>% distinct(cyl) %>% pull()
In my instance the solution was moving the jQuery include just before the </head>
tag. With the Slick include at the bottom before the </body>
and just before my script include that initiates the slider.
sudo nginx -t
should test all files and return errors and warnings locations
Just needed to drill down to the last li.
#navigation li .navigationLevel2 li
Use the PS command in a little different way to ignore child process as well:
ps -eaf | grep -v grep | grep $PROCESS | grep -v $$
There are static libraries (LIB) and dynamic libraries (DLL) - but note that .LIB files can be either static libraries (containing object files) or import libraries (containing symbols to allow the linker to link to a DLL).
Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.
Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.
As an example, almost every program written in 'C' will need functions from a library called the 'C runtime library, though few programs will need all of the functions. The C runtime comes in both static and dynamic versions, so you can determine which version your program uses depending on particular needs.
You can use the VisualTreeHelper to find controls. Below is a method that uses the VisualTreeHelper to find a parent control of a specified type. You can use the VisualTreeHelper to find controls in other ways as well.
public static class UIHelper
{
/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the queried item.</param>
/// <returns>The first parent item that matches the submitted type parameter.
/// If not matching item can be found, a null reference is being returned.</returns>
public static T FindVisualParent<T>(DependencyObject child)
where T : DependencyObject
{
// get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
// we’ve reached the end of the tree
if (parentObject == null) return null;
// check if the parent matches the type we’re looking for
T parent = parentObject as T;
if (parent != null)
{
return parent;
}
else
{
// use recursion to proceed with next level
return FindVisualParent<T>(parentObject);
}
}
}
Call it like this:
Window owner = UIHelper.FindVisualParent<Window>(myControl);
Use AppContext. Make sure you create a bean in your context file.
private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);
public static void randomMethod() {
foo.doStuff();
}
Even though this is a really old question, this may work.
Django 1.5.5
In [1]: from django.utils.text import unescape_entities
In [2]: unescape_entities('<img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" />')
Out[2]: u'<img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" />'
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
Yes, $_SERVER["HTTP_X_FORWARDED_FOR"]
is how I see my ip when under a proxy on my nginx server.
But your best bet is to run phpinfo()
on a page requested from under a proxy so you can look at all the availabe variables and see what is the one that carries your real ip.
The problem that you are facing is : TypeError : str returned non-string (type NoneType)
Here you have to understand the str function's working: the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one. In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used. This was the explaination for your error
You can solve this problem by using the return in str function like: *simply returnig the string value instead of printing it
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return self.summary
but if the value you are returning in not of string type then you can do like this to return string value from your str function
*typeconverting the value to string that your str function returns
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return str(self.summary)
`
It works on either option tag or text field:
$("#idname option[value='option1']").remove();
Your problem essentially boils down to "not all browsers will support this".
You could try a workaround and serve the unzipped files from a Flash object, but then you'd lose the JS-only purity (anyway, I'm not sure whether you currently can "drag files into browser" without some sort of Flash workaround - is that a HTML5 feature maybe?)
If you are using Java 6, then you can use wildcards in the classpath.
Now it is possible to use wildcards in classpath definition:
javac -cp libs/* -verbose -encoding UTF-8 src/mypackage/*.java -d build/classes
AngularJS - Input number with 2 decimal places it could help... Filtering:
- Set the regular expression to validate the input using ng-pattern. Here I want to accept only numbers with a maximum of 2 decimal places and with a dot separator.
<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal | number : 2" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />
Reading forward this was pointed on the next answer ng-model="myDecimal | number : 2".
To summarize and a bit simplify, you can use:
-- 0 - 9
select floor(random() * 10);
-- 0 - 10
SELECT floor(random() * (10 + 1));
-- 1 - 10
SELECT ceil(random() * 10);
And you can test this like mentioned by @user80168
-- 0 - 9
SELECT min(i), max(i) FROM (SELECT floor(random() * 10) AS i FROM generate_series(0, 100000)) q;
-- 0 - 10
SELECT min(i), max(i) FROM (SELECT floor(random() * (10 + 1)) AS i FROM generate_series(0, 100000)) q;
-- 1 - 10
SELECT min(i), max(i) FROM (SELECT ceil(random() * 10) AS i FROM generate_series(0, 100000)) q;
If you still use OID, it would be better to remove the dependency on it, because in recent versions of Postgres it is no longer supported. This can stop (temporarily until you solve it) your migration from version 10 to 12 for example.
See also: https://dev.to/rafaelbernard/postgresql-pgupgrade-from-10-to-12-566i
string str = intVar.ToString();
In some conditions, you do not have to use ToString()
string str = "hi " + intVar;
I got same issue on Catalina mac. I also installed the R from the source in following diretory. ./Documents/R-4.0.3
Now from the terminal type
ls -a
and open
vim .bash_profile
type
export LANG="en_US.UTF-8"
save with :wq
then type
source .bash_profile
and then open
./Documents/R-4.0.3/bin/R
./Documents/R-4.0.3/bin/Rscript
I always have to run "source /Users/yourComputerName/.bash_profile" before running R scripts.
The following code is looking for '\0', and under the assumptions of the question the array can be considered sorted since all non-'\0' precede all '\0'. This assumption won't hold if the array can contain '\0' within the data.
Find the location of the first zero-byte using a binary search, then slice.
You can find the zero-byte like this:
package main
import "fmt"
func FirstZero(b []byte) int {
min, max := 0, len(b)
for {
if min + 1 == max { return max }
mid := (min + max) / 2
if b[mid] == '\000' {
max = mid
} else {
min = mid
}
}
return len(b)
}
func main() {
b := []byte{1, 2, 3, 0, 0, 0}
fmt.Println(FirstZero(b))
}
It may be faster just to naively scan the byte array looking for the zero-byte, especially if most of your strings are short.
To have the exact same output as you need, you need to format the file like that :
a very long string..........\t 112232432\t anotherfield\n
a smaller string\t 123124343\t anotherfield\n
And then using :
$ column -t -s $'\t' FILE
a very long string.......... 112232432 anotherfield
a smaller string 123124343 anotherfield
Using ed:
ed infile <<'EOE'
,s/^/prefix/
wq
EOE
This substitutes, for each line (,
), the beginning of the line (^
) with prefix
. wq
saves and exits.
If the replacement string contains a slash, we can use a different delimiter for s
instead:
ed infile <<'EOE'
,s#^#/opt/workdir/#
wq
EOE
I've quoted the here-doc delimiter EOE
("end of ed") to prevent parameter expansion. In this example, it would work unquoted as well, but it's good practice to prevent surprises if you ever have a $
in your ed script.
Recommended and Secure Method: SSH
Create an ssh Github key. Go to github.com -> Settings -> SSH and GPG keys -> New SSH Key. Now save your private key to your computer.
Then, if the private key is saved as id_rsa in the ~/.ssh/ directory, we add it for authentication as such:
ssh-add -K ~/.ssh/id_rsa
A More Secure Method: Caching
We can use git-credential-store to cache our username and password for a time period. Simply enter the following in your CLI (terminal or command prompt):
git config --global credential.helper cache
You can also set the timeout period (in seconds) as such:
git config --global credential.helper 'cache --timeout=3600'
An Even Less Secure Method
Git-credential-store may also be used, but saves passwords in plain text file on your disk as such:
git config credential.helper store
Outdated Answer - Quick and Insecure
This is an insecure method of storing your password in plain text. If someone gains control of your computer, your password will be exposed!
You can set your username and password like this:
git config --global user.name "your username"
git config --global user.password "your password"
That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character
pkill NAMEofAPP
Non rooted marshmallow, termux & terminal emulator.
I stumbled upon this thread because I wanted to always reference the "cell to the left" but CRUCIALLY in a non-volatile way (no OFFSET, INDIRECT and similar disasters). Looking the web up and down, no answers. (This thread does not actually provide an answer either.) After some tinkering about I stumbled upon the most astonishing method, which I like to share with this community:
Suppose a starting value of 100 in E6. Suppose I enter a delta to this value in F5, say 5. We would then calculate the continuation value (105) in F6 = E6+F5. If you want to add another step, easy: just copy column F to column G and enter a new delta in G5.
This is what we do, periodically. Each column has a date and these dates MUST BE in chronological order (to help with MATCH etc). Every so often it happens that we forget to enter a step. Now suppose you want to insert a column between F and G (to catch up with your omission) and copy F into the new G (to repopulate the continuation formula). This is NOTHING SHORT of a total disaster. Try it - H6 will now say =F6+H5 and NOT (as we absolutely need it to) =G6+H5. (The new G6 will be correct.)
To make this work, we can obfuscate this banal calculation in the most astonishing manner F6=index($E6:F6;1;columns($E1:F1)-1)+F5. Copy right and you get G6=index($E6:G6;1;columns($E1:G1)-1)+G5.
This should never work, right? Circular reference, clearly! Try it out and be amazed. Excel seems to realize that although the INDEX range spans the cell we are recalculating, that cell itself is not addressed by the INDEX and thus DOES NOT create a circular reference.
So now I am home and dry. Insert a column between F and G and we get exactly what we need: The continuation value in the old H will refer back to the continuation value we inserted in the new G.
The problem is that the execution policy is set on a per user basis. You'll need to run the following command in your application every time you run it to enable it to work:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned
There probably is a way to set this for the ASP.NET user as well, but this way means that you're not opening up your whole system, just your application.
(Source)
Here's my version:
$title = ucwords(str_replace('-', ' ', get_query_var('pagename')));
get_query_var('pagename') was just giving me the page slug. So the above replaces all the dashes, and makes the first letter of each word uppercase - so it can actually be used as a title.
You can do
$('.page-address-edit').addClass('test1 test2');
More here:
More than one class may be added at a time, separated by a space, to the set of matched elements, like so:
$("p").addClass("myClass yourClass");
IE supports CSS expressions:
width:expression(document.body.clientWidth > 955 ? "955px": "100%" );
but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.
You can use a Contains
query for this:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
You might want to check the GC.GetTotalMemory method.
It retrieves the number of bytes currently thought to be allocated by the garbage collector.
Similar as they are, merge!
and store
treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!
's key: "value"
syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.
hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash
{:key=>"value"}
hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash
{:key=>"value", "key"=>"value"}
To get the shovel operator <<
working, I would advise using Mark Thomas's answer.
AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.
Probably the closest you'll get is something like this
// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
var i = 0;
for ( var p in this ) i++;
return i;
}
alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3
But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?
Object.prototype.length = function()
{
var i = 0;
for ( var p in this )
{
if ( 'function' == typeof this[p] ) continue;
i++;
}
return i;
}
alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2
In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.
Convert the Special characters to apostrophe,
Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)
Below code it to remove extra ''' apostrophe
Data <- gsub("''","" , Data ,ignore.case = TRUE)
Use gsub(..)
function for replacing the special character with apostrophe
The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.
Also, the accepted answers demo fiddle has a lot of unnecessary styles.
So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.
.marquee {_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
height: 16px;_x000D_
display: block;_x000D_
}_x000D_
.marquee span {_x000D_
display: inline-block;_x000D_
text-indent: 0;_x000D_
overflow: hidden;_x000D_
-webkit-transition: 15s;_x000D_
transition: 15s;_x000D_
-webkit-animation: marquee 15s linear infinite;_x000D_
animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.
NPM is a package manager, you can install node.js packages using NPM
NPX is a tool to execute node.js packages.
It doesn't matter whether you installed that package globally or locally. NPX will temporarily install it and run it. NPM also can run packages if you configure a package.json file and include it in the script section.
So remember this, if you want to check/run a node package quickly without installing locally or globally use NPX.
npM - Manager
npX - Execute - easy to remember
According to the HTTP spec, there is no limit to a URL's length. Keep your URLs under 2048 characters; this will ensure the URLs work in all clients & server configurations. Also, search engines like URLs to remain under approximately 2000 characters.
Here is a var arg XOR method for java...
public static boolean XOR(boolean... args) {
boolean r = false;
for (boolean b : args) {
r = r ^ b;
}
return r;
}
Enjoy
You just need to:
Step 1: Go home directory of C:\ with typing cd.. (2 times)
Step 2: It appears now C:\>
Step 3: Type dir Windows\System32\run
That's all, it shows complete files & folder details inside target folder.
Details: I used Windows\System32\com
folder as example, you should type your own folder name etc. Windows\System32\run
if you have an object you can define it as @property
so you can get results without a call, e.g.
class Item:
@property
def results(self):
return something
then in the template:
<% for result in item.results %>
...
<% endfor %>
These files contain user preference configurations that are in general specific to your machine, so it's better not to put it in SCM. Also, VS will change it almost every time you execute it, so it will always be marked by the SCM as 'changed'. I don't include either, I'm in a project using VS for 2 years and had no problems doing that. The only minor annoyance is that the debug parameters (execution path, deployment target, etc.) are stored in one of those files (don't know which), so if you have a standard for them you won't be able to 'publish' it via SCM for other developers to have the entire development environment 'ready to use'.
Suggested way is StopIteration. Please see Fibonacci example from tutorialspoint
#!usr/bin/python3
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.
Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).
ALTER TABLE CHANGE ;
Example:
ALTER TABLE global_user CHANGE deviceToken deviceId VARCHAR(255) ;
If you want to generate a backtrace, you are looking for debug_backtrace
and/or debug_print_backtrace
.
The first one will, for instance, get you an array like this one (quoting the manual) :
array(2) {
[0]=>
array(4) {
["file"] => string(10) "/tmp/a.php"
["line"] => int(10)
["function"] => string(6) "a_test"
["args"]=>
array(1) {
[0] => &string(6) "friend"
}
}
[1]=>
array(4) {
["file"] => string(10) "/tmp/b.php"
["line"] => int(2)
["args"] =>
array(1) {
[0] => string(10) "/tmp/a.php"
}
["function"] => string(12) "include_once"
}
}
They will apparently not flush the I/O buffer, but you can do that yourself, with flush
and/or ob_flush
.
(see the manual page of the first one to find out why the "and/or" ;-) )
open Manifest and add attribute theme = "@style/Theme.AppCompat.Light.NoActionBar" to activity you want it without actionbar :
<application
...
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
...
</activity>
</application>
prevArrow/nextArrow
Type:
string (html|jQuery selector) | object (DOM node|jQuery object)
Some example code
$(document).ready(function(){
$('.slick-carousel-1').slick({
// @type {string} html
nextArrow: '<button class="any-class-name-you-want-next">Next</button>',
prevArrow: '<button class="any-class-name-you-want-previous">Previous</button>'
});
$('.slick-carousel-2').slick({
// @type {string} jQuery Selector
nextArrow: '.next',
prevArrow: '.previous'
});
$('.slick-carousel-3').slick({
// @type {object} DOM node
nextArrow: document.getElementById('slick-next'),
prevArrow: document.getElementById('slick-previous')
});
$('.slick-carousel-4').slick({
// @type {object} jQuery Object
nextArrow: $('.example-4 .next'),
prevArrow: $('.example-4 .previous')
});
});
A little note on styling
Once Slick knows about your new buttons, you can style them to your heart's content; looking at the above example, you could target them based on class
name, id
name or even element
.
Sometimes it's asking the question that makes the answer jump out. The methods and extra arguments are listed on the ggplot2 wiki stat_smooth page.
Which is alluded to on the geom_smooth()
page with:
"See stat_smooth for examples of using built in model fitting if you need some more flexible, this example shows you how to plot the fits from any model of your choosing".
It's not the first time I've seen arguments in examples for ggplot graphs that aren't specifically in the function. It does make it tough to work out the scope of each function, or maybe I am yet to stumble upon a magic explicit list that says what will and will not work within each function.
int rows = 5;
int cols = 10;
int[] multD = new int[rows * cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int index = r * cols + c;
multD[index] = index * 2;
}
}
Enjoy!
Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.
On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.
As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.
Try this.It work for me.
Navigation bar and also added background image to right button.
UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:[[UIImage
imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
self.navigationItem.rightBarButtonItem=Savebtn;
Crystal Reports SP 19 does not support Visual Studio 2017. According to SAP they are targeting Visual Studio 2017 compatibility in SP 20 which is tentatively scheduled for June 2017.
I save files in .XLSB format to cut size. The XLSB also allows for VBA and macros to stay with the file. I've seen 50 meg files down to less than 10 with the Binary formatting.
Try the maven-exec-plugin. From there:
mvn exec:java -Dexec.mainClass="com.example.Main"
This will run your class in the JVM. You can use -Dexec.args="arg0 arg1"
to pass arguments.
If you're on Windows, apply quotes for
exec.mainClass
andexec.args
:mvn exec:java -D"exec.mainClass"="com.example.Main"
If you're doing this regularly, you can add the parameters into the pom.xml as well:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Main</mainClass>
<arguments>
<argument>foo</argument>
<argument>bar</argument>
</arguments>
</configuration>
</plugin>
If you are using Visual Studio, there is a GUI solution as well:
Just:
document.getElementById('myDiv').innerHTMl += "New Content";
I wrote the following jquery plugin for html loading function: http://webtech-training.blogspot.in/2010/10/dyamic-html-loader.html
Since HTML5 you can use the <mark></mark>
tags to highlight text. You can use javascript to wrap some text/keyword between these tags. Here is a little example of how to mark and unmark text.
you can use this extension method and call it like this.
DataTable dt = YourList.ToDataTable();
public static DataTable ToDataTable<T>(this List<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection propertyDescriptorCollection =
TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < propertyDescriptorCollection.Count; i++)
{
PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[propertyDescriptorCollection.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
You just need to have your class inherit from Comparable.
then implement the compareTo method the way you like.
Yes. The same notation that works for non-empty dict/set works for empty ones.
Notice the difference between non-empty dict
and set
literals:
{1: 'a', 2: 'b', 3: 'c'}
-- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'}
-- a tuple of values inside makes a set
So:
{}
== zero number of key-value pairs == empty dict
{*()}
== empty tuple of values == empty set
However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:
a = set()
Performance:
The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):
>>> %timeit ({*()} & {*()}) | {*()} 214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit (set() & set()) | set() 252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
... and for completeness, Renato Garcia's
frozenset
proposal on the above expression is some 60% faster!>>> ? = frozenset() >>> %timeit (? & ?) | ? 100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
NB: As ctrueden noticed in comments, {()}
is not an empty set. It's a set with 1 element: empty tuple.
After losing time and reading for a while, I just wanted something simple, this css worked for my requirements.
.gm-style-iw > div { overflow: hidden !important; }
Also is not an instant solution but starring/commenting on the issue might make them fix it, as they believe it is fixed: http://code.google.com/p/gmaps-api-issues/issues/detail?id=5713
If this is about .css
and .js
changes, one way is to to "cache busting" is by appending something like "_versionNo
" to the file name for each release. For example:
script_1.0.css // This is the URL for release 1.0
script_1.1.css // This is the URL for release 1.1
script_1.2.css // etc.
Or alternatively do it after the file name:
script.css?v=1.0 // This is the URL for release 1.0
script.css?v=1.1 // This is the URL for release 1.1
script.css?v=1.2 // etc.
You can check out this link to see how it could work.
The code above didn't work for me in IE. Here's some code based on this answer.
I took out the getElementById
so I could reference the element in a different way.
function insertAtCaret(element, text) {_x000D_
if (document.selection) {_x000D_
element.focus();_x000D_
var sel = document.selection.createRange();_x000D_
sel.text = text;_x000D_
element.focus();_x000D_
} else if (element.selectionStart || element.selectionStart === 0) {_x000D_
var startPos = element.selectionStart;_x000D_
var endPos = element.selectionEnd;_x000D_
var scrollTop = element.scrollTop;_x000D_
element.value = element.value.substring(0, startPos) +_x000D_
text + element.value.substring(endPos, element.value.length);_x000D_
element.focus();_x000D_
element.selectionStart = startPos + text.length;_x000D_
element.selectionEnd = startPos + text.length;_x000D_
element.scrollTop = scrollTop;_x000D_
} else {_x000D_
element.value += text;_x000D_
element.focus();_x000D_
}_x000D_
}
_x000D_
input{width:100px}_x000D_
label{display:block;margin:10px 0}
_x000D_
<label for="in2copy">Copy text from: <input id="in2copy" type="text" value="x"></label>_x000D_
<label for="in2ins">Element to insert: <input id="in2ins" type="text" value="1,2,3" autofocus></label>_x000D_
<button onclick="insertAtCaret(document.getElementById('in2ins'),document.getElementById('in2copy').value)">Insert</button>
_x000D_
EDIT: Added a running snippet, jQuery is not being used.
One way using awk
:
tail -f file.txt | awk '/A1/ { print $NF }'
In case of ActionLink, it generally uses HttpUtility.Encode on the link text.
In that case
you can use
HttpUtility.HtmlDecode(myString)
it worked for me when using HtmlActionLink to decode the string that I wanted to pass. eg:
@Html.ActionLink(HttpUtility.HtmlDecode("myString","ActionName",..)
I implemented a pinch zoom for my TextView
, using this tutorial. The resulting code is this:
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;
and in onCreate():
// Zoom handlers
gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
// We can be in one of these 2 states
static final int NONE = 0;
static final int ZOOM = 1;
int mode = NONE;
static final int MIN_FONT_SIZE = 10;
static final int MAX_FONT_SIZE = 50;
float oldDist = 1f;
@Override
public boolean onTouch(View v, MotionEvent event) {
TextView textView = (TextView) findViewById(R.id.text);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
mode = ZOOM;
Log.d(TAG, "mode=ZOOM" );
}
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if (mode == ZOOM) {
float newDist = spacing(event);
// If you want to tweak font scaling, this is the place to go.
if (newDist > 10f) {
float scale = newDist / oldDist;
if (scale > 1) {
scale = 1.1f;
} else if (scale < 1) {
scale = 0.95f;
}
float currentSize = textView.getTextSize() * scale;
if ((currentSize < MAX_FONT_SIZE && currentSize > MIN_FONT_SIZE)
||(currentSize >= MAX_FONT_SIZE && scale < 1)
|| (currentSize <= MIN_FONT_SIZE && scale > 1)) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, currentSize);
}
}
}
break;
}
return false;
}
Magic constants 1.1 and 0.95 were chosen empirically (using scale
variable for this purpose made my TextView
behave kind of weird).
python2 and python3
it is good to use time module
import time
int(time.time())
1573708436
you can also use datetime module, but when you use strftime('%s'), but strftime convert time to your local time!
python2
from datetime import datetime
datetime.utcnow().strftime('%s')
python3
from datetime import datetime
datetime.utcnow().timestamp()
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
Any time the screen is less than 1026 pixels wide, anything inside the { }
will apply.
Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS
Convert.Tostring()
basically just calls the following value == null ? String.Empty: value.ToString()
(string)variable
will only cast when there is an implicit or explicit operator on what you are casting
ToString()
can be overriden by the type (it has control over what it does), if not it results in the name of the type
Obviously if an object is null, you can't access the instance member ToString()
, it will cause an exception
To prevent the jump, this is what I used
export function toggleBodyScroll(disable) {
if (!window.tempScrollTop) {
window.tempScrollTop = window.pageYOffset;
// save the current position in a global variable so I can access again later
}
if (disable) {
document.body.classList.add('disable-scroll');
document.body.style.top = `-${window.tempScrollTop}px`;
} else {
document.body.classList.remove('disable-scroll');
document.body.style.top = `0px`;
window.scrollTo({top: window.tempScrollTop});
window.tempScrollTop = 0;
}
}
and in my css
.disable-scroll {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}
From the output of java -X
:
-Xloggc:<file> log GC status to a file with time stamps
Documented here:
-Xloggc:filename
Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of
-verbose:gc
with the time elapsed since the first GC event preceding each logged event. The-Xloggc
option overrides-verbose:gc
if both are given with the samejava
command.Example:
-Xloggc:garbage-collection.log
So the output looks something like this:
0.590: [GC 896K->278K(5056K), 0.0096650 secs] 0.906: [GC 1174K->774K(5056K), 0.0106856 secs] 1.320: [GC 1670K->1009K(5056K), 0.0101132 secs] 1.459: [GC 1902K->1055K(5056K), 0.0030196 secs] 1.600: [GC 1951K->1161K(5056K), 0.0032375 secs] 1.686: [GC 1805K->1238K(5056K), 0.0034732 secs] 1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs] 1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]
Sometimes you want to filter the list based on public/private vars. E.g.
def pub_vars(self):
"""Gives the variable names of our instance we want to expose
"""
return [k for k in vars(self) if not k.startswith('_')]
I had the same issue earlier, but my situation was a bit different in the front-end. I'll share my scenario anyway, maybe someone might find it useful.
I had an api call to /api/user/register
in the frontend with email, password and username as request body. On submitting the form(register form), a handler function is called which initiates the fetch call to /api/user/register
. I used the event.preventDefault()
in the beginning line of this handler function, all other lines,like forming the request body as well the fetch call was written after the event.preventDefault()
. This returned a pending promise
.
But when I put the request body formation code above the event.preventDefault()
, it returned the real promise. Like this:
event.preventDefault();
const data = {
'email': email,
'password': password
}
fetch(...)
...
instead of :
const data = {
'email': email,
'password': password
}
event.preventDefault();
fetch(...)
...
the best thing to do is :
def wordListToFreqDict(wordlist):
wordfreq = [wordlist.count(p) for p in wordlist]
return dict(zip(wordlist, wordfreq))
then try to :
wordListToFreqDict(originallist)
Convert.ToIntXX doesn't like being passed strings of decimals.
To be safe use
Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))
i used eltima make virtual serial port for my modbus application debug work. it is really very good application at development stage to check serial port program without connecting hardware.
re.sub(r'(.)(.)',r"\2\1",'abcdef1234')
However re is a bit slow.
def swap(s):
i=iter(s)
while True:
a,b=next(i),next(i)
yield b
yield a
''.join(swap("abcdef1234"))
We're trying this on a short list that does not do any view recycling. So far so good.
XML:
<RitalinLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="@+id/cart_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarStyle="outsideOverlay"
/>
</RitalinLayout>
Java:
/**
* It helps you keep focused.
*
* For use as a parent of {@link android.widget.ListView}s that need to use EditText
* children for inline editing.
*/
public class RitalinLayout extends FrameLayout {
View sticky;
public RitalinLayout(Context context, AttributeSet attrs) {
super(context, attrs);
ViewTreeObserver vto = getViewTreeObserver();
vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
@Override public void onGlobalFocusChanged(View oldFocus, View newFocus) {
if (newFocus == null) return;
View baby = getChildAt(0);
if (newFocus != baby) {
ViewParent parent = newFocus.getParent();
while (parent != null && parent != parent.getParent()) {
if (parent == baby) {
sticky = newFocus;
break;
}
parent = parent.getParent();
}
}
}
});
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override public void onGlobalLayout() {
if (sticky != null) {
sticky.requestFocus();
}
}
});
}
}
This answer is much the same as others except I prefer not to use as many class names. But that's just personal preference. You could argue that using class names on each div is more transparent as declares up front the purpose of the nested divs.
<div id="MyDiv" class="proportional">
<div>
<div>
<p>Content</p>
</div>
</div>
</div>
Here's the generic CSS:
.proportional { position:relative; }
.proportional > div > div { position:absolute; top:0px; bottom:0px; left:0px; right:0px; }
Then target the first inner div to set width and height (padding-top):
#MyDiv > div { width:200px; padding-top:50%; }
Sometimes it's easier to do all the appending outside of pandas, then, just create the DataFrame in one shot.
>>> import pandas as pd
>>> simple_list=[['a','b']]
>>> simple_list.append(['e','f'])
>>> df=pd.DataFrame(simple_list,columns=['col1','col2'])
col1 col2
0 a b
1 e f
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
In my case, jvmTarget was already set in build.gradle
file as below.
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
But my issue was still there. Finally, it gets resolved after Changing Target JVM version from 1.6 to 1.8 in Preferences > Other Settings > Kotlin Compiler > Target JVM version. see attached picture,
When searching this topic I found the solution elsewhere but adding the answer here since I had the same problem as above together with the text "Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined". Cause was due to having one to many tags in the table body.
[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]
If you can rely on having ECMAScript5 features available, you can use the Object.keys
function to get an array of the keys (property names) in an object. All modern browsers have Object.keys
(including IE9+).
Object.keys(jsonData).forEach(function(key) {
var value = jsonData[key];
// ...
});
The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim
or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim
).
Here's the rest of the answer from 2011:
Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:
if (typeof Object.keys !== "function") {
(function() {
var hasOwn = Object.prototype.hasOwnProperty;
Object.keys = Object_keys;
function Object_keys(obj) {
var keys = [], name;
for (name in obj) {
if (hasOwn.call(obj, name)) {
keys.push(name);
}
}
return keys;
}
})();
}
That uses a for..in
loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty
to check that the property is owned directly by the object rather than being inherited.
(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)
When you write
from file2 import *
it actually copies the names defined in file2
into the namespace of file1
. So if you reassign those names in file1
, by writing
foo = "bar"
for example, it will only make that change in file1
, not file2
. Note that if you were to change an attribute of foo
, say by doing
foo.blah = "bar"
then that change would be reflected in file2
, because you are modifying the existing object referred to by the name foo
, not replacing it with a new object.
You can get the effect you want by doing this in file1.py
:
import file2
file2.foo = "bar"
test = SomeClass()
(note that you should delete from foo import *
) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.
From Interface Builder (Storyboard/XIB):
Programmatically:
SWift 4
Using label extension
extension UILabel {
// Pass value for any one of both parameters and see result
func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {
guard let labelText = self.text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = lineHeightMultiple
let attributedString:NSMutableAttributedString
if let labelattributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Line spacing attribute
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
Now call extension function
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) . // try values 1.0 to 5.0
// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0
Or using label instance (Just copy & execute this code to see result)
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
Swift 3
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
I think you can use SeriesGroupBy.nunique
:
print (df.groupby('param')['group'].nunique())
param
a 2
b 1
Name: group, dtype: int64
Another solution with unique
, then create new df
by DataFrame.from_records
, reshape to Series
by stack
and last value_counts
:
a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a 2
b 1
dtype: int64
Old topic, but I think I found another descent solution. Adding class="row"
to a div will result in this CSS configuration:
.row {
display: -webkit-box;
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
We want to keep the first 3 rules and we can do this with class="d-flex flex-wrap"
(see https://getbootstrap.com/docs/4.1/utilities/flex/):
.flex-wrap {
flex-wrap: wrap !important;
}
.d-flex {
display: -webkit-box !important;
display: flex !important;
}
It adds !important rules though but it shouldn't be a problem in most cases...
For me I upgraded NuGet.exe from 3.4 to 4.9 because 3.4 doesn't understand how to restore packages for .NET Core.
For details please see dotnet restore vs. nuget restore with teamcity
The following works in Firefox and Opera (sorry, I do not have access to other browsers at the moment):
<div class="form-field">
<input id="option1" type="radio" name="opt"/>
<label for="option1">Option 1</label>
</div>
The CSS:
.form-field * {
vertical-align: middle;
}
You can use simple JavaScript to print a specific div from a page.
var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.
The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.
select * from emp, dept where emp.dept_id=dept.dept_id(+)
So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!
Using the MaximumSize
and MinimumSize
properties of the form will fix the form size, and prevent the user from resizing the form, while keeping the form default FormBorderStyle
.
this.MaximumSize = new Size(XX, YY);
this.MinimumSize = new Size(X, Y);
The webpage is incorrect and I have pointed this out to MS and they will get it changed.
As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.
The ToolVersion for MSBuild remains at "4.0".
One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))
For example, if you have a vector as elements
and would like to get sum
of it
elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432
Apparently, the last digital as 1
been truncated, the ideal result should be -876.54321
, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements))
, redundant zero(s) generate as -876.5432100000
Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321
, there are 5 decimal digits need to print, then we can set up a parameter for format
function as below:
decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321
We can change the decimal_length
based on each time query, so it can satisfy different decimal printing requirement.
pretty sure you just want the plain old replace function. use like this:
myString.replace('username1','');
i suppose if you want to remove the trailing comma do this instead:
myString.replace('username1,','');
edit:
here is your site specific code:
jQuery("#post_like_list-510").text().replace(...)
@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.
Jon Skeet is right (unusual) about the codecs
module - it contains byte strings:
>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>>
Picking another nit, the BOM
has a standard Unicode name, and it can be entered as:
>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'
It is also accessible via unicodedata
:
>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>>
Obligatory Twisted example:
twistd -n ftp
And probably useful:
twistd ftp --help
Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
-p, --port= set the port number [default: 2121]
-r, --root= define the root of the ftp-site. [default:
/usr/local/ftp]
--userAnonymous= Name of the anonymous user. [default: anonymous]
--password-file= username:password-style credentials database
--version
--help Display this help and exit.
I know this isn't JavaScript, but you can also physically use the mouse-click to click a dynamic Javascript anchor:
public static void mouseClickByLocator( String cssLocator ) {
String locator = cssLocator;
WebElement el = driver.findElement( By.cssSelector( locator ) );
Actions builder = new Actions(driver);
builder.moveToElement( el ).click( el );
builder.perform();
}
In this code you just need to call this in your button click.
private void list_paired_Devices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<>();
for (BluetoothDevice bt : pairedDevices) {
devices.add(bt.getName() + "\n" + bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(bluetooth.this, android.R.layout.simple_list_item_1, devices);
emp.setAdapter(arrayAdapter);
}
Working fine for windows by navigating to %APPDATA%\syntevo\SmartGit\ and delete all settings.xml, then open the installed software
You dont need jquery-migrate. Summarizing previous answers, here is a working html:
<html>
<body>
<a id='linkButton'>ClickMe</a>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
<script type="text/javascript">
$(document).ready(function() {
toastr.options.timeOut = 1500; // 1.5s
toastr.info('Page Loaded!');
$('#linkButton').click(function() {
toastr.success('Click Button');
});
});
</script>
</body>
</html>
In Kibana Console:
POST calls-xin-test-2/_delete_by_query
{
"query": {
"match_all": {}
}
}
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
Simple assigning to window.location
or window.location.href
should be fine:
window.location = newUrl;
However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:
Use the URL hash. For example, you can go from example.com
to example.com#foo
without loading a new page. You can simply set window.location.hash
to make this easy. Then, you should listen to the HTML5 hashchange
event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.
You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo
to example.com/bar
. Using this is easy:
window.history.pushState("example.com/foo");
When the user presses "back", you'll receive the window's popstate
event, which you can easily listen to (jQuery):
$(window).bind("popstate", function(e) { alert("location changed"); });
Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.
Trying to answer a personal problem and similar to yours I found on Pandas Doc what I think would answer this question:
DataFrame.shift(periods=1, freq=None, axis=0) Shift index by desired number of periods with an optional time freq
Notes
If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would like to extend the index when shifting and preserve the original data.
Hope to help future questions in this matter.
What browser are you testing in?
What DOCType have you set?
How exactly are you declaring your CSS?
Are you sure you haven't missed a ;
before/after the overflow-y: scroll
?
I've just tested the following in IE7 and Firefox and it works fine
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents --> _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
</div>
_x000D_
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Kindly try below on postman :-
In header section example work for me..
Authorization : JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwiZ2V0dGVycyI6e30sIndhc1BvcHVsYXRlZCI6ZmFsc2UsImFjdGl2ZVBhdGhzIjp7InBhdGhzIjp7InBhc3N3b3JkIjoiaW5pdCIsImVtYWlsIjoiaW5pdCIsIl9fdiI6ImluaXQiLCJfaWQiOiJpbml0In0sInN0YXRlcyI6eyJpZ25vcmUiOnt9LCJkZWZhdWx0Ijp7fSwiaW5pdCI6eyJfX3YiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwiZW1pdHRlciI6eyJkb21haW4iOm51bGwsIl9ldmVudHMiOnt9LCJfZXZlbnRzQ291bnQiOjAsIl9tYXhMaXN0ZW5lcnMiOjB9fSwiaXNOZXciOmZhbHNlLCJfZG9jIjp7Il9fdiI6MCwicGFzc3dvcmQiOiIkMmEkMTAkdTAybWNnWHFjWVQvdE41MlkzZ2l3dVROd3ZMWW9ZTlFXejlUcThyaDIwR09IMlhHY3haZWUiLCJlbWFpbCI6Im1hZGFuLmRhbGUxQGdtYWlsLmNvbSIsIl9pZCI6IjU5MjEzYzYyYWM2ODZlMGMyNzI2MjgzMiJ9LCJfcHJlcyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbbnVsbCxudWxsLG51bGxdLCIkX19vcmlnaW5hbF92YWxpZGF0ZSI6W251bGxdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltudWxsXX0sIl9wb3N0cyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbXSwiJF9fb3JpZ2luYWxfdmFsaWRhdGUiOltdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltdfSwiaWF0IjoxNDk1MzUwNzA5LCJleHAiOjE0OTUzNjA3ODl9.BkyB0LjKB4FIsCtnM5FcpcBLvKed_j7rCCxZddwiYnU
Use request.args
to get parsed contents of query string:
from flask import request
@app.route(...)
def login():
username = request.args.get('username')
password = request.args.get('password')
Go to Tools->Options->Text Editor->c#->Advanced and uncheck the first checkbox Enter outlining mode when files open.
This will solve this problem forever
it seams that your ending quote comes too early. It should be after the last parameter.
This trick worked for me.
I noticed something interesting: when I start my application using the following command line:
java -Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
If I try to connect to this port from a remote machine using jconsole, the TCP connection succeeds, some data is exchanged between remote jconsole and local jmx agent where my MBean is deployed, and then, jconsole displays a connect error message. I performed a wireshark capture, and it shows data exchange coming from both agent and jconsole.
Thus, this is not a network issue, if I perform a netstat -an with or without java.rmi.server.hostname system property, I have the following bindings:
TCP 0.0.0.0:9999 0.0.0.0:0 LISTENING
TCP [::]:9999 [::]:0 LISTENING
It means that in both cases the socket created on port 9999 accepts connections from any host on any address.
I think the content of this system property is used somewhere at connection and compared with the actual IP address used by agent to communicate with jconsole. And if those address do not match, connection fails.
I did not have this problem while connecting from the same host using jconsole, only from real physical remote hosts. So, I suppose that this check is done only when connection is coming from the "outside".
You can try below code to solve your problem:
By default, first option select: jQuery('.select').find('option')[0].selected=true;
Thanks, Ketan T
Please also note that on certain environments and conditions (such as running on windows on dispatch level >= DISPATCH LEVEL), you cannot use mutex but rather spinlock. On unix - same thing.
Here is equivalent question on competitor stackexchange unix site: https://unix.stackexchange.com/questions/5107/why-are-spin-locks-good-choices-in-linux-kernel-design-instead-of-something-more
Info on dispatching on windows systems: http://download.microsoft.com/download/e/b/a/eba1050f-a31d-436b-9281-92cdfeae4b45/IRQL_thread.doc
You can achieve this directly in Xcode:
The very last checkbox, make sure secure
is checked .
Or you can do it using code:
Identifies whether the text object should hide the text being entered.
Declaration
optional var secureTextEntry: Bool { get set }
Discussion
This property is set to false
by default. Setting this property to true
creates a password-style text object, which hides the text being entered.
example:
texfield.secureTextEntry = true
Java 8:
int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();
None, because having an ORM takes too much control away with small benefits. The time savings gained are easily blown away when you have to debug abnormalities resulting from the use of the ORM. Furthermore, ORMs discourage developers from learning SQL and how relational databases work and using this for their benefit.
The other way to tackle it is to use this code snippet:
JSON.parse(JSON.stringify(response)).data
This feels so wrong but it works
I was able to achieve the desired result by using Alt + Shift + up/down and then typing the desired comment characters and additional character.
You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.
You actually don't need to define the class a second time just to implement the functions. Implement the functions like this:
#include "gameObject.h"
gameObject::gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
int gameObject::add()
{
return x+y;
}
etc
You can use any of the two based on your need:
Field[] fields = ClassName.class.getFields(); // returns inherited members but not private members.
Field[] fields = ClassName.class.getDeclaredFields(); // returns all members including private members but not inherited members.
To filter only the public fields from the above list (based on requirement) use below code:
List<Field> fieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPublic(field.getModifiers())).collect(
Collectors.toList());
What had caused this error on my side was the following line
include_once dirname(__FILE__) . './Config.php';
I managed to realize it was the culprit when i added the lines:
//error_reporting(E_ALL | E_DEPRECATED | E_STRICT);
//ini_set('display_errors', 1);
to all my php files.
To solve the path issue
i canged the offending line to:
include_once dirname(__FILE__) . '/Config.php';
public class GetFilesRecursive {
public static List <String> getFilesRecursively(File dir){
List <String> ls = new ArrayList<String>();
for (File fObj : dir.listFiles()) {
if(fObj.isDirectory()) {
ls.add(String.valueOf(fObj));
ls.addAll(getFilesRecursively(fObj));
} else {
ls.add(String.valueOf(fObj));
}
}
return ls;
}
public static List <String> getListOfFiles(String fullPathDir) {
List <String> ls = new ArrayList<String> ();
File f = new File(fullPathDir);
if (f.exists()) {
if(f.isDirectory()) {
ls.add(String.valueOf(f));
ls.addAll(getFilesRecursively(f));
}
} else {
ls.add(fullPathDir);
}
return ls;
}
public static void main(String[] args) {
List <String> ls = getListOfFiles("/Users/srinivasab/Documents");
for (String file:ls) {
System.out.println(file);
}
System.out.println(ls.size());
}
}
You could also check the request accept content type as specified in the rfc. That way you can render by default HTML and where your client accept application/jason you can return json in your response without a template being required
Taking all of the proposed answers and applying them to my situation - trying to check or uncheck a checkbox based on a retrieved value of true (should check the box) or false (should not check the box) - I tried all of the above and found that using .prop("checked", true) and .prop("checked", false) were the correct solution.
I can't add comments or up answers yet, but I felt this was important enough to add to the conversation.
Here is the longhand code for a fullcalendar modification that says if the retrieved value "allDay" is true, then check the checkbox with ID "even_allday_yn":
if (allDay)
{
$( "#even_allday_yn").prop('checked', true);
}
else
{
$( "#even_allday_yn").prop('checked', false);
}
You need an INSERT ... SELECT
INSERT INTO exception_codes( code, message )
SELECT code, message
FROM exception_code_tmp
UPDATE `table` SET table_column='test';
for (x in restaurants) {
if (restaurants[x].restaurant.food == 'chicken') {
return restaurants[x].restaurant.name;
}
}
You could add a span before the link with a specific class like so:
<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>
And then give that a specific width and a background image just like you are doing with the button itself.
.btn span.icon {
background: url(imgs/icon.png) no-repeat;
float: left;
width: 10px;
height: 40px;
}
I am no CSS guru but off the top of my head I think that should work.
I used a quick work around so I could keep the DropDownList style.
class DummyComboBoxItem
{
public string DisplayName
{
get
{
return "Make a selection ...";
}
}
}
public partial class mainForm : Form
{
private DummyComboBoxItem placeholder = new DummyComboBoxItem();
public mainForm()
{
InitializeComponent();
myComboBox.DisplayMember = "DisplayName";
myComboBox.Items.Add(placeholder);
foreach(object o in Objects)
{
myComboBox.Items.Add(o);
}
myComboBox.SelectedItem = placeholder;
}
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (myComboBox.SelectedItem == null) return;
if (myComboBox.SelectedItem == placeholder) return;
/*
do your stuff
*/
myComboBox.Items.Add(placeholder);
myComboBox.SelectedItem = placeholder;
}
private void myComboBox_DropDown(object sender, EventArgs e)
{
myComboBox.Items.Remove(placeholder);
}
private void myComboBox_Leave(object sender, EventArgs e)
{
//this covers user aborting the selection (by clicking away or choosing the system null drop down option)
//The control may not immedietly change, but if the user clicks anywhere else it will reset
if(myComboBox.SelectedItem != placeholder)
{
if(!myComboBox.Items.Contains(placeholder)) myComboBox.Items.Add(placeholder);
myComboBox.SelectedItem = placeholder;
}
}
}
If you use databinding you'll have to create a dummy version of the type you're bound to - just make sure you remove it before any persistence logic.
The following will produce the required results.
SELECT a.SomeDate,
a.SomeValue,
SUM(b.SomeValue) AS RunningTotal
FROM TestTable a
CROSS JOIN TestTable b
WHERE (b.SomeDate <= a.SomeDate)
GROUP BY a.SomeDate,a.SomeValue
ORDER BY a.SomeDate,a.SomeValue
Having a clustered index on SomeDate will greatly improve the performance.
Follow these 2 steps:
Follow these steps using the Services Tab:
Customize the New COnnection as follows:
localhost
3306
mysql
( mysql is the default or enter your database name)jdbc:mysql://localhost:3306/mysql
NB: DELETE the ?zeroDateTimeBehaviour=convertToNull
part in the URL.
Instead of mysql
in the URL, you should see your database name)
MySQL Server at localhost:3306:[username](...)
In the "MySQL Server Properties" dialog select the "Admin Properties" tab Enter the following in the textboxes specified:
For Linux users :
/usr/bin/mysql
/etc/init.d/mysql start
/usr/bin/mysql
/etc/init.d/mysql stop
For MS Windows users :
NOTE: Optional:
In the Path/URL to admin tool field, type or browse to the location of your MySQL Administration application such as the MySQL Admin Tool, PhpMyAdmin, or other web-based administration tools.
Note: mysqladmin is the MySQL admin tool found in the bin folder of the MySQL installation directory. It is a command-line tool and not ideal for use with the IDE.
We will use MySQL Workbench in this example. Please use the path of your installation if you have MySQL workbench and the path to MySQL.
C:\Program Files\MySQL\MySQL Workbench CE 5.2.47\MySQLWorkbench.exe
C:\mysql\bin\mysqld
(OR C:\mysql\bin\mysqld.exe
)C:\mysql\bin\mysqladmin
(OR C:\mysql\bin\mysqladmin.exe
)-u root shutdown
(Try -u root stop
)Possible exampes of MySQL bin folder locations for Windows Users:
C:\mysql\bin
C:\Program Files\MySQL\MySQL Server 5.1\bin\
~\xampp\mysql\bin
I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.
// Coordinated Universal Time string from
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z";
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date);
DateTime utcDateTime = localDateTime.ToUniversalTime();
// ID from:
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);
.loc
accept row and column selectors simultaneously (as do .ix/.iloc
FYI)
This is done in a single pass as well.
In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
In [2]: df
Out[2]:
a b c d e
0 0.669701 0.780497 0.955690 0.451573 0.232194
1 0.952762 0.585579 0.890801 0.643251 0.556220
2 0.900713 0.790938 0.952628 0.505775 0.582365
3 0.994205 0.330560 0.286694 0.125061 0.575153
In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]:
a d
0 0.669701 0.451573
1 0.952762 0.643251
2 0.900713 0.505775
And if you want the values (though this should pass directly to sklearn as is); frames support the array interface
In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]:
array([[ 0.66970138, 0.45157274],
[ 0.95276167, 0.64325143],
[ 0.90071271, 0.50577509]])
You are using Python 2 for which the input()
function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError
exception.
To fix the problem, in Python 2, you can use raw_input()
. This returns the string entered by the user and does not attempt to evaluate it.
Note that if you were using Python 3, input()
behaves the same as raw_input()
does in Python 2.
I have been using the snippet below when working with CLI tools and I want to know if some resource exist or not, but I don't care about the output.
if [ -z "$(cat no_exist 2>&1 >/dev/null)" ]; then
echo "none exist actually exist!"
fi
Before installing libgtk2.0-dev and pkg-config or libqt4-dev. Make sure that you have uninstalled opencv. You can confirm this by running import cv2 on your python shell. If it fails, then install the needed packages and re-run cmake .
When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.
In my case, CSS did not fix the issue. I noticed the problem while using jQuery re-render a button.
$("#myButton").html("text")
Try this
$("#myButton").html("<span>text</span>")
<script type="text/javascript" language="javascript">
function createDiv()
{
var divTag = document.createElement("div");
divTag.innerHTML = "Div tag created using Javascript DOM dynamically";
document.body.appendChild(divTag);
}
</script>
You can use nested.
There are tow function one is openTab()
and another is closeMobileMenue()
, Firstly we call openTab()
and call another function inside closeMobileMenue()
.
function openTab() {
window.open('https://play.google.com/store/apps/details?id=com.drishya');
closeMobileMenue() //After open new tab, Nav Menue will close.
}
onClick={openTab}
string myFile= File.ReadAllLines(Application.StartupPath.ToString() + @"..\..\..\Data\myTxtFile.txt")
What do you mean by delete
? In Python, removing a reference (or a name) can be done with the del
keyword, but if there are other names to the same object that object will not be deleted.
--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
compared to:
--> test = 5
--> other is test # check that both name refer to the exact same object
True
--> del test # gets rid of test, but the object is still referenced by other
--> print(other)
5
Try this:
Now you can extend %base-class in any of your classes (e.g. .my-class).
%base-class {
width: 80%;
margin-left: 10%;
margin-right: 10%;
}
.my-base-class {
@extend %base-class;
}
.my-class {
@extend %base-class;
margin-bottom: 40px;
}
string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);
$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10
Yes, there's in fact many reasons why you can access AWS Lambda like and HTTP Endpoint.
The architecture of AWS Lambda
It's a microservice. Running inside EC2 with Amazon Linux AMI (Version 3.14.26–24.46.amzn1.x86_64) and runs with Node.js. The memory can be beetwen 128mb and 1gb. When the data source triggers the event, the details are passed to a Lambda function as parameter's.
What happen?
AWS Lambda run's inside a container, and the code is directly uploaded to this container with packages or modules. For example, we NEVER can do SSH for the linux machine running your lambda function. The only things that we can monitor are the logs, with CloudWatchLogs and the exception that came from the runtime.
AWS take care of launch and terminate the containers for us, and just run the code. So, even that you use require('http'), it's not going to work, because the place where this code runs, wasn't made for this.
/**
* in_array function variant that performs case-insensitive comparison when needle is a string.
*
* @param mixed $needle
* @param array $haystack
* @param bool $strict
*
* @return bool
*/
function in_arrayi($needle, array $haystack, bool $strict = false): bool
{
if (is_string($needle)) {
$needle = strtolower($needle);
foreach ($haystack as $value) {
if (is_string($value)) {
if (strtolower($value) === $needle) {
return true;
}
}
}
return false;
}
return in_array($needle, $haystack, $strict);
}
/**
* in_array function variant that performs case-insensitive comparison when needle is a string.
* Multibyte version.
*
* @param mixed $needle
* @param array $haystack
* @param bool $strict
* @param string|null $encoding
*
* @return bool
*/
function mb_in_arrayi($needle, array $haystack, bool $strict = false, ?string $encoding = null): bool
{
if (null === $encoding) {
$encoding = mb_internal_encoding();
}
if (is_string($needle)) {
$needle = mb_strtolower($needle, $encoding);
foreach ($haystack as $value) {
if (is_string($value)) {
if (mb_strtolower($value, $encoding) === $needle) {
return true;
}
}
}
return false;
}
return in_array($needle, $haystack, $strict);
}
As others were saying, an easy solution is to put your script at the bottom of the page, because all DOM elements are loaded synchronously from top to bottom. Otherwise, I think what you're looking for is document.onload(() => {callback_body})
or window.onload(() => {callback_body})
as Erik said. These allow you to execute you script when the dom:loaded
event is fired as Douwe Maan said. Not sure about the properties of window.onload
, but document.onload
is triggered only after all elements, css, and scripts are loaded. In your case:
<script type="text/javascript">
document.onload(() =>
document.body.innerHTML = "";
)
</script>
or, If you are using an old browser:
<script type="text/javascript">
document.onload(function() {
document.body.innerHTML = "";
})
</script>
I was looking for a way to prevent all body scrolling when there's a popup with a scrollable area (a "shopping cart" popdown that has a scrollable view of your cart).
I wrote a far more elegant solution using minimal javascript to just toggle the class "noscroll" on your body when you have a popup or div that you'd like to scroll (and not "overscroll" the whole page body).
while desktop browsers observe overflow:hidden -- iOS seems to ignore that unless you set the position to fixed... which causes the whole page to be a strange width, so you have to set the position and width manually as well. use this css:
.noscroll {
overflow: hidden;
position: fixed;
top: 0;
left: 0;
width: 100%;
}
and this jquery:
/* fade in/out cart popup, add/remove .noscroll from body */
$('a.cart').click(function() {
$('nav > ul.cart').fadeToggle(100, 'linear');
if ($('nav > ul.cart').is(":visible")) {
$('body').toggleClass('noscroll');
} else {
$('body').removeClass('noscroll');
}
});
/* close all popup menus when you click the page... */
$('body').click(function () {
$('nav > ul').fadeOut(100, 'linear');
$('body').removeClass('noscroll');
});
/* ... but prevent clicks in the popup from closing the popup */
$('nav > ul').click(function(event){
event.stopPropagation();
});
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode
method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
object[] newarray = new object[oldarray.Length-1];
for(int x=0; x < array.Length; x++)
{
if(!(array[x] == value_of_array_to_delete))
// if(!(x == array_index_to_delete))
{
newarray[x] = oldarray[x];
}
}
There is no way to downsize an array after it is created, but you can copy the contents to another array of a lesser size.
Here is a function that does this:
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
Try:
event.putExtra("startTime", "10/05/2012");
And when you are accessing passed variables:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));
Well, the code you've given is invalid to start with - List
is a generic type, and it has an Add
method instead of add
etc.
But you could do something like:
List<Person> list = new List<Person>
{
new person{ID=1,Name="jhon",salary=2500},
new person{ID=2,Name="Sena",salary=1500},
new person{ID=3,Name="Max",salary=5500}.
new person{ID=4,Name="Gen",salary=3500}
};
// The "Where" LINQ operator filters a sequence
var highEarners = list.Where(p => p.salary > 3000);
foreach (var person in highEarners)
{
Console.WriteLine(person.Name);
}
If you want to learn details of what all the LINQ operators do, and how they can be implemented in LINQ to Objects, you might be interested in my Edulinq blog series.
public boolean isInternetConnection()
{
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else {
return false;
}
}
Assuming you're getting norm
from scipy.stats
, you probably just need to sort your list:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial
And so I get:
There are 2 ways to run Selenium python tests in Google Chrome. I'm considering Windows (Windows 10 in my case):
Prerequisite: Download the latest Chrome Driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads
Way 1:
i) Extract the downloaded zip file in a directory/location of your choice
ii) Set the executable path in your code as below:
self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')
Way 2:
i) Simply paste the chromedriver.exe under /Python/Scripts/ (In my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:
self.driver = webdriver.Chrome()
select (case when locate('(', LocationName) = 0
then
horse_name
else
left(LocationName, locate('(', LocationName) - 1)
end) as Country
from tblcountry;
The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .
To turn on that feature you need:
web.xml
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/<strike>*</strike></url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
RegistrationController
return "forward:/login?j_username=" + registrationModel.getUserEmail()
+ "&j_password=" + registrationModel.getPassword();
You need upper case property names in your structs in order to be used by the json packages.
Upper case property names are exported properties
. Lower case property names are not exported.
You also need to pass the your data object by reference (&data
).
package main
import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type tracks struct {
Toptracks []toptracks_info
}
type toptracks_info struct {
Track []track_info
Attr []attr_info
}
type track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []streamable_info
Artist []artist_info
Attr []track_attr_info
}
type attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type streamable_info struct {
Text string
Fulltrack string
}
type artist_info struct {
Name string
Mbid string
Url string
}
type track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data tracks
json.Unmarshal(body, &data)
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
The solution that worked for me with PHP / PDO.
public function createTrainingDatabase($p_iRecordnr){
// Methode: Create an database envirioment for a student by copying the original
// @parameter: $p_iRecordNumber, type:integer, scope:local
// @var: $this->sPdoQuery, type:string, scope:member
// @var: $bSuccess, type:boolean, scope:local
// @var: $aTables, type:array, scope:local
// @var: $iUsernumber, type:integer, scope:local
// @var: $sNewDBName, type:string, scope:local
// @var: $iIndex, type:integer, scope:local
// -- Create first the name of the new database --
$aStudentcard = $this->fetchUsercardByRecordnr($p_iRecordnr);
$iUserNumber = $aStudentcard[0][3];
$sNewDBName = $_SESSION['DB_name']."_".$iUserNumber;
// -- Then create the new database --
$this->sPdoQuery = "CREATE DATABASE `".$sNewDBName."`;";
$this->PdoSqlReturnTrue();
// -- Create an array with the tables you want to be copied --
$aTables = array('1eTablename','2ndTablename','3thTablename');
// -- Populate the database --
for ($iIndex = 0; $iIndex < count($aTables); $iIndex++)
{
// -- Create the table --
$this->sPdoQuery = "CREATE TABLE `".$sNewDBName."`.`".$aTables[$iIndex]."` LIKE `".$_SESSION['DB_name']."`.`".$aTables[$iIndex]."`;";
$bSuccess = $this->PdoSqlReturnTrue();
if(!$bSuccess ){echo("Could not create table: ".$aTables[$iIndex]."<BR>");}
else{echo("Created the table ".$aTables[$iIndex]."<BR>");}
// -- Fill the table --
$this->sPdoQuery = "REPLACE `".$sNewDBName."`.`".$aTables[$iIndex]."` SELECT * FROM `".$_SESSION['DB_name']."`.`".$aTables[$iIndex]."`";
$bSuccess = $this->PdoSqlReturnTrue();
if(!$bSuccess ){echo("Could not fill table: ".$aTables[$iIndex]."<BR>");}
else{echo("Filled table ".$aTables[$index]."<BR>");}
}
}
if (set no count== off)
{ then it will keep data of how many records affected so reduce performance } else { it will not track the record of changes hence improve perfomace } }
what about changing the position: relative on your #content #text div to position: absolute
#content #text {
position:absolute;
width:950px;
height:215px;
color:red;
}
then you can use the css properties left and top to position within the #content div
This worked for me. But it gives only the main menu name. That is if user has opened Settings --> Bluetooth --> Device Name screen, RunningAppProcessInfo calls it as just Settings. Not able to drill down furthur
ActivityManager activityManager = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
PackageManager pm = context.getPackageManager();
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses) {
if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(appProcess.processName, PackageManager.GET_META_DATA));
Log.i("Foreground App", "package: " + appProcess.processName + " App: " + c.toString());
}
}
I'm nowhere near as expert as others who have answered but I was having an issue with a procedure I was using to select a random row from a table (not overly relevant) but I needed to know the number of rows in my reference table to calculate the random index. Using the traditional Count(*) or Count(1) work but I was occasionally getting up to 2 seconds for my query to run. So instead (for my table named 'tbl_HighOrder') I am using:
Declare @max int
Select @max = Row_Count
From sys.dm_db_partition_stats
Where Object_Name(Object_Id) = 'tbl_HighOrder'
It works great and query times in Management Studio are zero.
If you use Apache Commons Lang (which I think a lot of projects use it), you can just use it like this:
int myInt = BooleanUtils.toInteger(boolean_expression);
toInteger
method returns 1 if boolean_expression
is true, 0 otherwise
Using a closure
let button: UIButton = {
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
...
return button
}()
If you use "format-table" you can use -hidetableheaders
it's very simply.use it and enjoy.
CREATE VIEW [dbo].[vwGetNewId]
AS
SELECT NEWID() AS Id
Creat FUNCTION [dbo].[fnGenerateRandomString](@length INT = 8)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @result CHAR(2000);
DECLARE @String VARCHAR(2000);
SET @String = 'abcdefghijklmnopqrstuvwxyz' + --lower letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + --upper letters
'1234567890'; --number characters
SELECT @result =
(
SELECT TOP (@length)
SUBSTRING(@String, 1 + number, 1) AS [text()]
FROM master..spt_values
WHERE number < DATALENGTH(@String)
AND type = 'P'
ORDER BY
(
SELECT TOP 1 Id FROM dbo.vwGetNewId
) --instead of using newid()
FOR XML PATH('')
);
RETURN @result;
END;
After doing some testing, i came up with this solution, let me know in case it helps.
Add this below 2 conditions in your query and it will find the records which don't contain numeric data
and REGEXP_LIKE(<column_name>, '\D') -- this selects non numeric data
and not REGEXP_LIKE(column_name,'^[-]{1}\d{1}') -- this filters out negative(-) values
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html