I created simple examples to clarify understanding of ManualResetEvent
vs AutoResetEvent
.
AutoResetEvent
: lets assume you have 3 workers thread. If any of those threads will call WaitOne()
all other 2 threads will stop execution and wait for signal. I am assuming they are using WaitOne()
. It is like; if I do not work, nobody works. In first example you can see that
autoReset.Set();
Thread.Sleep(1000);
autoReset.Set();
When you call Set()
all threads will work and wait for signal. After 1 second I am sending second signal and they execute and wait (WaitOne()
). Think about these guys are soccer team players and if one player says I will wait until manager calls me, and others will wait until manager tells them to continue (Set()
)
public class AutoResetEventSample
{
private AutoResetEvent autoReset = new AutoResetEvent(false);
public void RunAll()
{
new Thread(Worker1).Start();
new Thread(Worker2).Start();
new Thread(Worker3).Start();
autoReset.Set();
Thread.Sleep(1000);
autoReset.Set();
Console.WriteLine("Main thread reached to end.");
}
public void Worker1()
{
Console.WriteLine("Entered in worker 1");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker1 is running {0}", i);
Thread.Sleep(2000);
autoReset.WaitOne();
}
}
public void Worker2()
{
Console.WriteLine("Entered in worker 2");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker2 is running {0}", i);
Thread.Sleep(2000);
autoReset.WaitOne();
}
}
public void Worker3()
{
Console.WriteLine("Entered in worker 3");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker3 is running {0}", i);
Thread.Sleep(2000);
autoReset.WaitOne();
}
}
}
In this example you can clearly see that when you first hit Set()
it will let all threads go, then after 1 second it signals all threads to wait! As soon as you set them again regardless they are calling WaitOne()
inside, they will keep running because you have to manually call Reset()
to stop them all.
manualReset.Set();
Thread.Sleep(1000);
manualReset.Reset();
Console.WriteLine("Press to release all threads.");
Console.ReadLine();
manualReset.Set();
It is more about Referee/Players relationship there regardless of any of the player is injured and wait for playing others will continue to work. If Referee says wait (Reset()
) then all players will wait until next signal.
public class ManualResetEventSample
{
private ManualResetEvent manualReset = new ManualResetEvent(false);
public void RunAll()
{
new Thread(Worker1).Start();
new Thread(Worker2).Start();
new Thread(Worker3).Start();
manualReset.Set();
Thread.Sleep(1000);
manualReset.Reset();
Console.WriteLine("Press to release all threads.");
Console.ReadLine();
manualReset.Set();
Console.WriteLine("Main thread reached to end.");
}
public void Worker1()
{
Console.WriteLine("Entered in worker 1");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker1 is running {0}", i);
Thread.Sleep(2000);
manualReset.WaitOne();
}
}
public void Worker2()
{
Console.WriteLine("Entered in worker 2");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker2 is running {0}", i);
Thread.Sleep(2000);
manualReset.WaitOne();
}
}
public void Worker3()
{
Console.WriteLine("Entered in worker 3");
for (int i = 0; i < 5; i++) {
Console.WriteLine("Worker3 is running {0}", i);
Thread.Sleep(2000);
manualReset.WaitOne();
}
}
}
A DataSet
already contains DataTables
. You can just use:
DataTable firstTable = dataSet.Tables[0];
or by name:
DataTable customerTable = dataSet.Tables["Customer"];
Note that you should have using
statements for your SQL code, to ensure the connection is disposed properly:
using (SqlConnection conn = ...)
{
// Code here...
}
The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.
You should change it to something as follows
SortedMap<String, Double> myMap =
new TreeMap<String, Double>(new Comparator<String>()
{
public int compare(String o1, String o2)
{
return o1.compareTo(o2);
}
});
Update
You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -
List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
I don't think you can declare and use variables to define appSettings keys within a configuration file. I've always managed concatenations in code like you.
You could put the body of your script into a function and then you could return from that function.
def main():
done = True
if done:
return
# quit/stop/exit
else:
# do other stuff
if __name__ == "__main__":
#Run as main program
main()
This works, been tested...
SELECT n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',
n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM Batches t
Cross Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)
Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:
var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);
You can specify USER
in the Dockerfile. All subsequent actions will be performed using that account. You can specify USER
one line before the CMD
or ENTRYPOINT
if you only want to use that user when launching a container (and not when building the image). When you start a container from the resulting image, you will attach as the specified user.
Use this for example:
cv2.namedWindow('finalImg', cv2.WINDOW_NORMAL)
cv2.imshow("finalImg",finalImg)
To get the certificate of remote server you can use openssl
tool and you can find it between BEGIN CERTIFICATE
and END CERTIFICATE
which you need to copy and paste into your certificate file (CRT).
Here is the command demonstrating it:
ex +'/BEGIN CERTIFICATE/,/END CERTIFICATE/p' <(echo | openssl s_client -showcerts -connect example.com:443) -scq > file.crt
To return all certificates from the chain, just add g
(global) like:
ex +'g/BEGIN CERTIFICATE/,/END CERTIFICATE/p' <(echo | openssl s_client -showcerts -connect example.com:443) -scq
Then you can simply import your certificate file (file.crt
) into your keychain and make it trusted, so Java shouldn't complain.
On OS X you can double-click on the file or drag and drop in your Keychain Access, so it'll appear in login/Certificates. Then double-click on the imported certificated and make it Always Trust for SSL.
On CentOS 5 you can append them into /etc/pki/tls/certs/ca-bundle.crt
file (and run: sudo update-ca-trust force-enable
), or in CentOS 6 copy them into /etc/pki/ca-trust/source/anchors/
and run sudo update-ca-trust extract
.
In Ubuntu, copy them into /usr/local/share/ca-certificates
and run sudo update-ca-certificates
.
It has been said in one of the direct comments to your answer already, but just to state it officially. What you want to use is an overload:
virtual const ULONG Write(ULONG &State, bool sequence);
inline const ULONG Write()
{
ULONG state;
bool sequence = true;
Write (state, sequence);
}
Using function overloads also have additional benefits. Firstly you can default any argument you wish:
class A {};
class B {};
class C {};
void foo (A const &, B const &, C const &);
void foo (B const &, C const &); // A defaulted
void foo (A const &, C const &); // B defaulted
void foo (C const &); // A & B defaulted etc...
It is also possible to redefine default arguments to virtual functions in derived class, which overloading avoids:
class Base {
public:
virtual void f1 (int i = 0); // default '0'
virtual void f2 (int);
inline void f2 () {
f2(0); // equivalent to default of '0'
}
};
class Derived : public Base{
public:
virtual void f1 (int i = 10); // default '10'
using Base::f2;
virtual void f2 (int);
};
void bar ()
{
Derived d;
Base & b (d);
d.f1 (); // '10' used
b.f1 (); // '0' used
d.f2 (); // f1(int) called with '0'
b.f2 (); // f1(int) called with '0
}
There is only one situation where a default really needs to be used, and that is on a constructor. It is not possible to call one constructor from another, and so this technique does not work in that case.
View the source of the login page. Look for the form
HTML tag. Within that tag is something that will look like action=
Use that value as $url
, not the URL of the form itself.
Also, while you are there, verify the input boxes are named what you have them listed as.
For example, a basic login form will look similar to:
<form method='post' action='postlogin.php'>
Email Address: <input type='text' name='email'>
Password: <input type='password' name='password'>
</form>
Using the above form as an example, change your value of $url
to:
$url="http://www.myremotesite.com/postlogin.php";
Verify the values you have listed in $postdata
:
$postdata = "email=".$username."&password=".$password;
and it should work just fine.
The canonical T-SQL (SqlServer) answer is to use a DELETE
with JOIN
as such
DELETE o
FROM Orders o
INNER JOIN Customers c
ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'
This will delete all orders which have a customer with first name Sklivvz.
Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337
You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0
only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden
, you can eliminate this problem:
div {_x000D_
width:100px;_x000D_
height:20px;_x000D_
}_x000D_
.menu {_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
_x000D_
background:#eee;_x000D_
width:100px;_x000D_
margin:0;_x000D_
padding:5px;_x000D_
list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
visibility:visible;_x000D_
opacity:1;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">Open Menu</a>_x000D_
<ul class="menu">_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
Try this one in your css document,
-fx-background-color : #ffaadd;
or
-fx-base : #ffaadd;
Also, you can set background color on your object with this code directly.
yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
//Following is the example in jdk 1.8
package com;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class User {
private String firstName;
private String lastName;
private Integer age;
public Integer getAge() {
return age;
}
public User setAge(Integer age) {
this.age = age;
return this;
}
public String getFirstName() {
return firstName;
}
public User setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public String getLastName() {
return lastName;
}
public User setLastName(String lastName) {
this.lastName = lastName;
return this;
}
}
public class MultiFieldsComparision {
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
User u1 = new User().setFirstName("Pawan").setLastName("Singh").setAge(38);
User u2 = new User().setFirstName("Pawan").setLastName("Payal").setAge(37);
User u3 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(60);
User u4 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(43);
User u5 = new User().setFirstName("Pawan").setLastName("Chamoli").setAge(44);
User u6 = new User().setFirstName("Pawan").setLastName("Singh").setAge(5);
users.add(u1);
users.add(u2);
users.add(u3);
users.add(u4);
users.add(u5);
users.add(u6);
System.out.println("****** Before Sorting ******");
users.forEach(user -> {
System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());
});
System.out.println("****** Aftre Sorting ******");
users.sort(
Comparator.comparing(User::getFirstName).thenComparing(User::getLastName).thenComparing(User::getAge));
users.forEach(user -> {
System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());
});
}
}
Initialization is not require in case of zero because default value of int in Java is zero.
For values other than zero java.util.Arrays
provides a number of options, simplest one is fill method.
int[] arr = new int[5];
Arrays.fill(arr, -1);
System.out.println(Arrays.toString(arr)); //[-1, -1, -1, -1, -1 ]
int [] arr = new int[5];
// fill value 1 from index 0, inclusive, to index 3, exclusive
Arrays.fill(arr, 0, 3, -1 )
System.out.println(Arrays.toString(arr)); // [-1, -1, -1, 0, 0]
We can also use Arrays.setAll() if we want to fill value on condition basis:
int[] array = new int[20];
Arrays.setAll(array, p -> p > 10 ? -1 : p);
int[] arr = new int[5];
Arrays.setAll(arr, i -> i);
System.out.println(Arrays.toString(arr)); // [0, 1, 2, 3, 4]
I found this on Microsoft Dev Center. It works correctly and ignores double-clicking in wrong places. As you see, the point is that an item gets selected before double-click event is triggered.
private void listView1_DoubleClick(object sender, EventArgs e)
{
// user clicked an item of listview control
if (listView1.SelectedItems.Count == 1)
{
//do what you need to do here
}
}
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/588b1053-8a8f-44ab-8b44-2e42062fb663
Just as another option if you want to print only the key (doesn't write the .env file) you can use:
php artisan key:generate --show
In addition to the string operations (MOVS/INS/STOS/CMPS/SCASB/W/D/Q etc.) mentioned in the other answers, I wanted to add that there are also more "modern" x86 assembly instructions that implicitly use at least EDI/RDI:
The SSE2 MASKMOVDQU
(and the upcoming AVX VMASKMOVDQU
) instruction selectively write bytes from an XMM register to memory pointed to by EDI/RDI.
Here are the built-in ways to do head
and tail
. Don't use pipes because if you have a large file, it will be extremely slow. Using these built-in options will be extremely fast even for huge files.
gc log.txt -head 10
gc log.txt -tail 10
gc log.txt -tail 10 -wait # equivalent to tail -f
Use std::equal algorithm from <algorithms>
with reverse iteration:
std::string LogExt = ".log";
if (std::equal(LogExt.rbegin(), LogExt.rend(), filename.rbegin())) {
…
}
Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.
WhiteStarUML is a fork of StarUML that is still maintain http://sourceforge.net/projects/whitestaruml/?source=dlp.
If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat
class. It's very simple:
double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);
Which will output (depending on locale):
$2.30
Also, if currency isn't required (just the exact two decimal places) you can use this instead:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);
Which will output 2.30
Error: SSL certificate problem: self signed certificate in certificate chain
Solution:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
You can check the existence of a symlink and that it is not broken with:
[ -L ${my_link} ] && [ -e ${my_link} ]
So, the complete solution is:
if [ -L ${my_link} ] ; then
if [ -e ${my_link} ] ; then
echo "Good link"
else
echo "Broken link"
fi
elif [ -e ${my_link} ] ; then
echo "Not a link"
else
echo "Missing"
fi
-L
tests whether there is a symlink, broken or not. By combining with -e
you can test whether the link is valid (links to a directory or file), not just whether it exists.
According to this thread:
The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.
In Swift 2 you can do it in this way:
var dictionary: NSDictionary = ...
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary
In Swift 3:
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)
this is what i did to loose the double values when using the Html.CheckBox(...
Replace("true,false","true").Split(',')
with 4 boxes checked, unchecked, unchecked, checked it turns true,false,false,false,true,false into true,false,false,true. just what i needed
This bug is really annoying..
The only thing that did the trick for me is deleting the project from the workspace, then deleting the .project and .classpath files and then re import it back to the workspace.
Hope it will help others.
Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. calling Class.forName("ExampleClass").newInstance()
it is equivalent to calling new ExampleClass()
), on which you can call the methods that the class defines, access the visible fields etc.
Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity
to omit active connections from dropped users. These connections are also not shown inside pgAdminIII.
If you are doing automatic testing (in which you also create users) this might be a probable scenario.
In this case you need to revert to queries like:
SELECT pg_terminate_backend(procpid)
FROM pg_stat_get_activity(NULL::integer)
WHERE datid=(SELECT oid from pg_database where datname = 'your_database');
NOTE: In 9.2+ you'll have change procpid
to pid
.
JavaScript/ECMAScript is designed to live within a host environment. That is, JavaScript doesn't actually do anything unless the host environment decides to parse and execute a given script, and provide environment objects that let JavaScript actually be useful (such as the DOM in browsers).
I think a given function or script block will execute line-by-line and that is guaranteed for JavaScript. However, perhaps a host environment could execute multiple scripts at the same time. Or, a host environment could always provide an object that provides multi-threading. setTimeout
and setInterval
are examples, or at least pseudo-examples, of a host environment providing a way to do some concurrency (even if it's not exactly concurrency).
You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));
Element root = document.getDocumentElement();
for (Server newServer : Collection<Server> bunchOfNewServers){
Element server = Document.createElement("server");
/* create and setup the server node...*/
root.appendChild(server);
}
/* use whatever method to output DOM to XML (for example, using transformer like you did).*/
database_password: password
would between quotes: " or '.
like so:
database_password: "password"
You can't. The array doesn't have a name.
You just have two references to the array, one in the variable and another in the third array.
There is no way to find all the references that exist for a given object.
If the name is important, then store it with the data.
var size = { data: ["S", "M", "L", "XL", "XXL"], name: 'size' };
var color = { data: ["Red", "Blue", "Green", "White", "Black"], name: 'color' };
var options = [size, color];
Obviously you'll have to modify the existing code which accesses the data (since you now have options[0].data[0]
instead of options[0][0]
but you also have options[0].name
).
If you want client IP and your server is behind aws elb, then user the following code. Tested for laravel 5.3
$elbSubnet = '172.31.0.0/16';
Request::setTrustedProxies([$elbSubnet]);
$clientIp = $request->ip();
for i in range(100):
try:
#Your code here
break
except:
continue
This one worked for me.
A really easy way to do it is to create an ODBC link in EXCEL and run SP_WHO2 from there.
You can Refresh whenever you like and because it's EXCEL everything can be manipulated easily!
I was trying to use Web Api 2 attribute routing to allow for multiple Get methods, and I had incorporated the helpful suggestions from previous answers, but in the Controller I had only decorated the "special" method (example):
[Route( "special/{id}" )]
public IHttpActionResult GetSomethingSpecial( string id ) {
...without also also placing a [RoutePrefix] at the top of the Controller:
[RoutePrefix("api/values")]
public class ValuesController : ApiController
I was getting errors stating that no Route was found matching the submitted URI. Once I had both the [Route] decorating the method as well as [RoutePrefix] decorating the Controller as a whole, it worked.
You can use the limit(n)
function:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()
Or:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()
function add(){
var first=parseFloat($("#first").val());
var second=parseFloat($("#second").val());
$("#result").val(+(first+second).toFixed(2));
}
Always state the workbook, worksheet and the cell/range.
For example:
Thisworkbook.Worksheets("fred").cells(1,1)
Workbooks("bob").Worksheets("fred").cells(1,1)
Because end users will always just click buttons and as soon as the focus moves off of the workbook the code wants to work with then things go completely wrong.
And never use the index of a workbook.
Workbooks(1).Worksheets("fred").cells(1,1)
You don't know what other workbooks will be open when the user runs your code.
If you don't like libraries, how about this?
Note that you should not use this function on the whole URL, instead you should use this on the components...e.g. just the "a b" component, as you build up the URL - otherwise the computer won't know what characters are supposed to have a special meaning and which ones are supposed to have a literal meaning.
/** Converts a string into something you can safely insert into a URL. */
public static String encodeURIcomponent(String s)
{
StringBuilder o = new StringBuilder();
for (char ch : s.toCharArray()) {
if (isUnsafe(ch)) {
o.append('%');
o.append(toHex(ch / 16));
o.append(toHex(ch % 16));
}
else o.append(ch);
}
return o.toString();
}
private static char toHex(int ch)
{
return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private static boolean isUnsafe(char ch)
{
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
}
cvWaitKey(milliseconds)
simply wait for milliseconds provided as a parameter for a next key stroke of keyboard.
Human eyes not able to see the thing moving in less than 1/10 second, so we use this to hold same image frame for some time on screen. As soon as the key of keyboard is pressed the next operation will be perform.
In short cvWaitKey(milliseconds)
wait either for key press or millisecond
time provided.
__func__
is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:
The identifier
__func__
is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.
Note that it is not a macro and it has no special meaning during preprocessing.
__func__
was added to C++ in C++11, where it is specified as containing "an implementation-de?ned string" (C++11 §8.4.1[dcl.fct.def.general]/8), which is not quite as useful as the specification in C. (The original proposal to add __func__
to C++ was N1642).
__FUNCTION__
is a pre-standard extension that some C compilers support (including gcc and Visual C++); in general, you should use __func__
where it is supported and only use __FUNCTION__
if you are using a compiler that does not support it (for example, Visual C++, which does not support C99 and does not yet support all of C++0x, does not provide __func__
).
__PRETTY_FUNCTION__
is a gcc extension that is mostly the same as __FUNCTION__
, except that for C++ functions it contains the "pretty" name of the function including the signature of the function. Visual C++ has a similar (but not quite identical) extension, __FUNCSIG__
.
For the nonstandard macros, you will want to consult your compiler's documentation. The Visual C++ extensions are included in the MSDN documentation of the C++ compiler's "Predefined Macros". The gcc documentation extensions are described in the gcc documentation page "Function Names as Strings."
::
or REM
:: commenttttttttttt
REM commenttttttttttt
::
doesn't work inline; add &
character:your commands here & :: commenttttttttttt
IF/ELSE
, FOR
loops, etc...) ::
should be followed with normal line, otherwise it gives error (use REM
there).::
may also fail within setlocal ENABLEDELAYEDEXPANSION
This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.
input_string = eval('b"' + sys.argv[1] + '"')
It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?
So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:
These options work great with me and I can start apache service without errors.
The other option is to change apache listen port from httpd.conf and set another port number.
Hope this solution helps anyone who face the same problem again.
If it worked the way you expected it to (resulting in "abc9"
), what would "9" + 9
deliver? 18
or "99"
?
To remove this ambiguity, you are required to make explicit what you want to convert in this case:
"abc" + str(9)
you have to call set and add functions on chart object before calling redraw.
chart.xAxis[0].setCategories([2,4,5,6,7], false);
chart.addSeries({
name: "acx",
data: [4,5,6,7,8]
}, false);
chart.redraw();
So this is old but... just in case someone finds this in a search.
Just use "#/"
instead of "#"
and the page won't jump.
Actually most of the answers here doesn't really scale the image to the width of itself.
We need to have a width and height of auto on the img
element itself so we can start with it's original size.
After that a container element can scale the image for us.
Simple HTML example:
<div style="position: relative;">
<figure>
<img src="[email protected]" />
</figure>
</div>
And here are the CSS rules. I use an absolute container in this case:
figure {
position: absolute;
left: 0;
top: 0;
-webkit-transform: scale(0.5);
-moz-transform: scale(0.5);
-ms-transform: scale(0.5);
-o-transform: scale(0.5);
transform: scale(0.5);
transform-origin: left;
}
figure img {
width: auto;
height: auto;
}
You could tweak the image positioning with rules like transform: translate(0%, -50%);
.
<script type="text/javascript">
function numericValidation(txtvalue) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (!(document.getElementById(txtvalue.id).value))
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
else {
var val = document.getElementById(txtvalue.id).value;
if(charCode==46 || (charCode > 31 && (charCode > 47 && charCode < 58)) )
{
var points = 0;
points = val.indexOf(".", points);
if (points >= 1 && charCode == 46)
{
return false;
}
if (points == 1)
{
var lastdigits = val.substring(val.indexOf(".") + 1, val.length);
if (lastdigits.length >= 2)
{
alert("Two decimal places only allowed");
return false;
}
}
return true;
}
else {
alert("Only Numarics allowed");
return false;
}
}
}
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtHDLLevel" MaxLength="6" runat="server" Width="33px" onkeypress="return numericValidation(this);" />
</div>
</form>
Use SharedPreferences to store and retrieve global variables.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userid = preferences.getString("userid", null);
Use:
dir -Directory -Recurse | Select FullName
This will give you an output of the root structure with the folder name for directories only.
Another way to rename the database or taking an image of the database is by using the reverse engineering option in the database tab. It will create an ER diagram for the database. Rename the schema there.
After that, go to the File menu and go to export and forward engineer the database.
Then you can import the database.
arrays:
malloc
);sizeof
(hence the common idiom sizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer);std::vector
:
&vec[0]
is guaranteed to work as expected);begin()
/end()
methods, the usual STL typedef
s, ...)Also consider the "modern alternative" to arrays - std::array
; I already described in another answer the difference between std::vector
and std::array
, you may want to have a look at it.
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
How do these new categories relate to the existing rvalue and lvalue categories?
A C++03 lvalue is still a C++11 lvalue, whereas a C++03 rvalue is called a prvalue in C++11.
As of Twig 1.5, the correct answer is to use the dump function. It is fully documented in the Twig documentation. Here is the documentation to enable this inside Symfony2.
{{ dump(user) }}
In this post I described possible solution for Solaris case when neither SO_NOSIGPIPE nor MSG_NOSIGNAL is available.
Instead, we have to temporarily suppress SIGPIPE in the current thread that executes library code. Here's how to do this: to suppress SIGPIPE we first check if it is pending. If it does, this means that it is blocked in this thread, and we have to do nothing. If the library generates additional SIGPIPE, it will be merged with the pending one, and that's a no-op. If SIGPIPE is not pending then we block it in this thread, and also check whether it was already blocked. Then we are free to execute our writes. When we are to restore SIGPIPE to its original state, we do the following: if SIGPIPE was pending originally, we do nothing. Otherwise we check if it is pending now. If it does (which means that out actions have generated one or more SIGPIPEs), then we wait for it in this thread, thus clearing its pending status (to do this we use sigtimedwait() with zero timeout; this is to avoid blocking in a scenario where malicious user sent SIGPIPE manually to a whole process: in this case we will see it pending, but other thread may handle it before we had a change to wait for it). After clearing pending status we unblock SIGPIPE in this thread, but only if it wasn't blocked originally.
Example code at https://github.com/kroki/XProbes/blob/1447f3d93b6dbf273919af15e59f35cca58fcc23/src/libxprobes.c#L156
I know this is extremely old, but I understand that this error type is a common mistake for beginners to make since most beginners will call their functions upon their header element being loaded. Seeing as this solution is not addressed at all in this thread, I'll add it. It is very likely that this javascript function was placed before the actual html was loaded. Remember, if you immediately call your javascript before the document is ready then elements requiring an element from the document might find an undefined value.
Try this.It work for me. Add button to navigation bar programmatically, Also we set image to navigation bar button,
Below is Code:-
UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:
[[UIImage imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
self.navigationItem.rightBarButtonItem=Savebtn;
-(void)SaveButtonClicked
{
// Add save button code.
}
you can use follow code in asp.net core 2.0:
public IActionResult index()
{
return new ContentResult() { Content = "My error message", StatusCode = (int)HttpStatusCode.Unauthorized };
}
Do it like this: Remember to close iframe tag.
<iframe src="http://samplepdf.com/sample.pdf" width="800" height="600"></iframe>
String to Uri
Uri myUri = Uri.parse("https://www.google.com");
Uri to String
Uri uri;
String stringUri = uri.toString();
My simple, simple, simple approach! =D
Code
string_to_test = "The criminals stole $1,000,000 in jewels."
chars_to_check = ["$", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in chars_to_check:
if char in string_to_test:
print("Char \"" + char + "\" detected!")
Output
Char "$" detected!
Char "," detected!
Char "0" detected!
Char "1" detected!
Thanks!
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
With a thread:
private class LoadingThread extends Thread {
Handler handler;
LoadingThread(Handler h) {
handler = h;
}
@Override
public void run() {
Message m = handler.obtainMessage();
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String page = "";
String inLine;
while ((inLine = in.readLine()) != null) {
page += inLine;
}
in.close();
Bundle b = new Bundle();
b.putString("result", page);
m.setData(b);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(m);
}
}
function listAllItems(){
for (i=0; i<localStorage.length; i++)
{
key = localStorage.key(i);
alert(localStorage.getItem(key));
}
}
regexp_replace
UDF performs my task. Below is the definition and usage from apache Wiki.
regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT):
This returns the string resulting from replacing all substrings in INITIAL_STRING
that match the java regular expression syntax defined in PATTERN
with instances of REPLACEMENT
,
e.g.: regexp_replace("foobar", "oo|ar", "")
returns fb
var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/set',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});
Isn't
$(document).ready(function() {
});
what you are looking for?
You can just use a Hook
add_filter( 'nav_menu_submenu_css_class', 'some_function', 10, 3 );
function some_function( $classes, $args, $depth ){
foreach ( $classes as $key => $class ) {
if ( $class == 'sub-menu' ) {
$classes[ $key ] = 'my-sub-menu';
}
}
return $classes;
}
where
$classes(array) - The CSS classes that are applied to the menu <ul> element.
$args(stdClass) - An object of wp_nav_menu() arguments.
$depth(int) - Depth of menu item. Used for padding.
An easy fix to this question is to add '[' in the start of your json file, and ending it with a ']'. This solved it for me.
An alternative, but a bit slower alternative is to do it over indexing.
np.isnan(data)[np.isnan(data) == False].size
In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop
The double use of np.isnan(data)
and the ==
operator might be a bit overkill and so I posted the answer only for completeness.
@loneSomeday explained it beautifully , here one solution which might also give you good idea how to achieve play/pause functionality
You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:
txtBox.CaretIndex=txtBox.Text.Length;
You need to set the caret index at the length, not length-1, because this would put the caret before the last character.
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
While sizeof
works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str
is pointer (sizeof
returns size of pointer, usually 4 or 8) or array with specified length (sizeof
will return the byte count matching specified length, which for char type are same).
Just use strlen()
.
I know this is an old question but here is something to try: Make your multidimensional array, and place it inside an html tag. This way you can precisely aim your array'd input:
//Your Holding tag for your inputs!
<div id='input-container' class='funky'></div>
<script>
//With VAR: you can seperate each variable with a comma instead of:
//creating var at the beginning and a semicolon at the end.
//Creates a cleaner layout of your variables
var
arr=[['input1-1','input1-2'],['input2-1','input2-2']],
//globall calls these letters var so you dont have to recreate variable below
i,j
;
//Instead of the general 'i<array.length' you can go even further
//by creating array[i] in place of 'i<array.length'
for(i=0;arr[i];i++){
for(j=0;arr[i][j];j++){
document.getElementById('input-container').innerHTML+=
"<input class='inner-funky'>"+arr[i][j]+"</input>"
;
}}
</script>
Its simply a neater way to write your code and easier to invoke. You can check my demo here!
You probably want os.makedirs as it will create intermediate directories as well, if needed.
import os
#dir is not keyword
def makemydir(whatever):
try:
os.makedirs(whatever)
except OSError:
pass
# let exception propagate if we just can't
# cd into the specified directory
os.chdir(whatever)
Actually, the internal behavior is translating the anonymous object to a dictionary. So what I do in these scenarios is go for a dictionary:
@{
var htmlAttributes = new Dictionary<string, object>
{
{ "class" , "form-control"},
{ "placeholder", "Why?" }
};
if (Model.IsDisabled)
{
htmlAttributes.Add("disabled", "disabled");
}
}
@Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })
Or, as Stephen commented here:
@Html.EditorFor(m => m.Description,
Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })
I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:
split -l 100000 database.sql database-
It will give files like:
database-aaa
database-aab
database-aac
...
After searching for an hour or two ,I've found a simple solution below.
const date = new Date(`${date from client} GMT`);
inside double ticks, there is a date from client side plust GMT.
I'm first time commenting, constructive criticism will be welcomed.
I am note sure, what you are expecting. Have a look at this fiddle, this might help you.
You HTML should have the class navbar-fixed-top
or navbar-fixed-bottom
.
HTML
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
JS
$(document).scroll(function(e){
var scrollTop = $(document).scrollTop();
if(scrollTop > 0){
console.log(scrollTop);
$('.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
} else {
$('.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
}
});
If you have deleted lot of files and folders, just do this
git commit -a -m .
git push
Update
As of 2019 this can be easily achieved using ProgressIndicator
, in Material Components library, used with the Widget.MaterialComponents.ProgressIndicator.Circular.Indeterminate
style.
For more details please check Gabriele Mariotti's answer below.
Old implementation
Here is an awesome implementation of the material design circular intermediate progress bar https://gist.github.com/castorflex/4e46a9dc2c3a4245a28e. The implementation only lacks the ability add various colors like in inbox by android app but this does a pretty great job.
Here it is in batch file form:
@echo off
set source=%1
set dest=%2
for %%f in (%source%\*) do if not exist "%dest%\%%~nxf" copy "%%f" "%dest%\%%~nxf"
THe easiest way to do so is:
function findChild(idOfElement, idOfChild){
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
or better readable:
findChild = (idOfElement, idOfChild) => {
let element = document.getElementById(idOfElement);
return element.querySelector(`[id=${idOfChild}]`);
}
I second Kristopher's recommendation of K&R for C.
I've found the "Essential Actionscript 2.0" book quite useful for AS coding (there's an AS3 version out now I believe).
I've found that having real books to thumb through is more helpful than an online reference in some cases. Not really sure why though.
We don't need to plt.ioff()
or plt.show()
(if we use %matplotlib inline
). You can test above code without plt.ioff()
. plt.close()
has the essential role. Try this one:
%matplotlib inline
import pylab as plt
# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')
If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2)
to the end of it, you will see nothing.
In conclusion, if you close figure by plt.close(fig)
, it won't be displayed.
If that is the entire line, it very well might be because you are missing a ;
at the end of the line.
This probably isn't the most elegant way to do it, but it gets the job done.
In[1]: import numpy as np
In[2]: import pandas as pd
In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])
In[4]: df
Out[4]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
Just replace '/Users/spencerlyon2/Desktop/test.csv'
with the path to your file
In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).
This may be off topic, but for those who are struggling on how to exactly change also the font of the button text (that was my case and Skatephone's answer helped me) here's how I did it (if you made buttons ind design mode):
First we need to have the button's string name "converted" (it's a foul way to explain, but straightforward) into java from the xml, and so we paste the aforementioned code into our MainActivity.java
IMPORTANT! place the code under the OnCreate method!
import android.widget.RemoteViews;
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");
Keep in mind:
my_layout
has to be substituted with the xml file where your buttons are
Counter
has to be substituted with the id name of your button ("@+id/ButtonName"
)
if you want to change the button text just insert the text in place of "Set button text here"
here comes the part where you change the font:
Now that you "converted" from xml to java, you can set a Typeface method for TextView. Paste the following code exactly under the previous one just described above
TextView txt = (TextView) findViewById(R.id.text_your_text_view_id);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MyFontName.ttf");
txt.setTypeface(font);
where in place of text_your_text_view_id
you put your button's id name (like as previous code) and in place of MyFontName.ttf
you put your desired font
WARNING! This assumes you already put your desired font into the assets/font folder. e.g. assets/fonts/MyFontName.ttf
To expand on the answers others have given:
We've got lots of languages with lots of characters that computers should ideally display. Unicode assigns each character a unique number, or code point.
Computers deal with such numbers as bytes... skipping a bit of history here and ignoring memory addressing issues, 8-bit computers would treat an 8-bit byte as the largest numerical unit easily represented on the hardware, 16-bit computers would expand that to two bytes, and so forth.
Old character encodings such as ASCII are from the (pre-) 8-bit era, and try to cram the dominant language in computing at the time, i.e. English, into numbers ranging from 0 to 127 (7 bits). With 26 letters in the alphabet, both in capital and non-capital form, numbers and punctuation signs, that worked pretty well. ASCII got extended by an 8th bit for other, non-English languages, but the additional 128 numbers/code points made available by this expansion would be mapped to different characters depending on the language being displayed. The ISO-8859 standards are the most common forms of this mapping; ISO-8859-1 and ISO-8859-15 (also known as ISO-Latin-1, latin1, and yes there are two different versions of the 8859 ISO standard as well).
But that's not enough when you want to represent characters from more than one language, so cramming all available characters into a single byte just won't work.
There are essentially two different types of encodings: one expands the value range by adding more bits. Examples of these encodings would be UCS2 (2 bytes = 16 bits) and UCS4 (4 bytes = 32 bits). They suffer from inherently the same problem as the ASCII and ISO-8859 standards, as their value range is still limited, even if the limit is vastly higher.
The other type of encoding uses a variable number of bytes per character, and the most commonly known encodings for this are the UTF encodings. All UTF encodings work in roughly the same manner: you choose a unit size, which for UTF-8 is 8 bits, for UTF-16 is 16 bits, and for UTF-32 is 32 bits. The standard then defines a few of these bits as flags: if they're set, then the next unit in a sequence of units is to be considered part of the same character. If they're not set, this unit represents one character fully. Thus the most common (English) characters only occupy one byte in UTF-8 (two in UTF-16, 4 in UTF-32), but other language characters can occupy six bytes or more.
Multi-byte encodings (I should say multi-unit after the above explanation) have the advantage that they are relatively space-efficient, but the downside that operations such as finding substrings, comparisons, etc. all have to decode the characters to unicode code points before such operations can be performed (there are some shortcuts, though).
Both the UCS standards and the UTF standards encode the code points as defined in Unicode. In theory, those encodings could be used to encode any number (within the range the encoding supports) - but of course these encodings were made to encode Unicode code points. And that's your relationship between them.
Windows handles so-called "Unicode" strings as UTF-16 strings, while most UNIXes default to UTF-8 these days. Communications protocols such as HTTP tend to work best with UTF-8, as the unit size in UTF-8 is the same as in ASCII, and most such protocols were designed in the ASCII era. On the other hand, UTF-16 gives the best average space/processing performance when representing all living languages.
The Unicode standard defines fewer code points than can be represented in 32 bits. Thus for all practical purposes, UTF-32 and UCS4 became the same encoding, as you're unlikely to have to deal with multi-unit characters in UTF-32.
Hope that fills in some details.
You might also checkout http://www.concretejs.com which is a modern, lightweight, Html5 canvas framework that enables hit detection, layering, and lots of other peripheral things. You can do things like this:
var wrapper = new Concrete.Wrapper({
width: 500,
height: 300,
container: el
});
var layer1 = new Concrete.Layer();
var layer2 = new Concrete.Layer();
wrapper.add(layer1).add(layer2);
// draw stuff
layer1.sceneCanvas.context.fillStyle = 'red';
layer1.sceneCanvas.context.fillRect(0, 0, 100, 100);
// reorder layers
layer1.moveUp();
// destroy a layer
layer1.destroy();
print("{latitude} {longitude}".format(**geopoint))
First of all, when you put that code in applicationDidFinishLaunching, it might be the case that controllers instantiated from Interface Builder are not yet linked to your application (so "red" and "blue" are still nil
).
But to answer your initial question, what you're doing wrong is that you're calling dismissModalViewControllerAnimated:
on the wrong controller! It should be like this:
[blue presentModalViewController:red animated:YES];
[red dismissModalViewControllerAnimated:YES];
Usually the "red" controller should decide to dismiss himself at some point (maybe when a "cancel" button is clicked). Then the "red" controller could call the method on self
:
[self dismissModalViewControllerAnimated:YES];
If it still doesn't work, it might have something to do with the fact that the controller is presented in an animation fashion, so you might not be allowed to dismiss the controller so soon after presenting it.
The call to time(NULL)
returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t
variable, that pointer variable will point to the current time.
I found this for online php validation:-
http://www.icosaedro.it/phplint/phplint-on-line.html
Hope this helps.
... and so you should do something like this:
set(tuple ((a,b) for a in range(3)) for b in range(3))
... and if needed convert back to list
You could just use normal Python argument passing syntax to specify your crontab. For example, suppose we define an Event class as below:
from datetime import datetime, timedelta
import time
# Some utility classes / functions first
class AllMatch(set):
"""Universal set - match everything"""
def __contains__(self, item): return True
allMatch = AllMatch()
def conv_to_set(obj): # Allow single integer to be provided
if isinstance(obj, (int,long)):
return set([obj]) # Single item
if not isinstance(obj, set):
obj = set(obj)
return obj
# The actual Event class
class Event(object):
def __init__(self, action, min=allMatch, hour=allMatch,
day=allMatch, month=allMatch, dow=allMatch,
args=(), kwargs={}):
self.mins = conv_to_set(min)
self.hours= conv_to_set(hour)
self.days = conv_to_set(day)
self.months = conv_to_set(month)
self.dow = conv_to_set(dow)
self.action = action
self.args = args
self.kwargs = kwargs
def matchtime(self, t):
"""Return True if this event should trigger at the specified datetime"""
return ((t.minute in self.mins) and
(t.hour in self.hours) and
(t.day in self.days) and
(t.month in self.months) and
(t.weekday() in self.dow))
def check(self, t):
if self.matchtime(t):
self.action(*self.args, **self.kwargs)
(Note: Not thoroughly tested)
Then your CronTab can be specified in normal python syntax as:
c = CronTab(
Event(perform_backup, 0, 2, dow=6 ),
Event(purge_temps, 0, range(9,18,2), dow=range(0,5))
)
This way you get the full power of Python's argument mechanics (mixing positional and keyword args, and can use symbolic names for names of weeks and months)
The CronTab class would be defined as simply sleeping in minute increments, and calling check() on each event. (There are probably some subtleties with daylight savings time / timezones to be wary of though). Here's a quick implementation:
class CronTab(object):
def __init__(self, *events):
self.events = events
def run(self):
t=datetime(*datetime.now().timetuple()[:5])
while 1:
for e in self.events:
e.check(t)
t += timedelta(minutes=1)
while datetime.now() < t:
time.sleep((t - datetime.now()).seconds)
A few things to note: Python's weekdays / months are zero indexed (unlike cron), and that range excludes the last element, hence syntax like "1-5" becomes range(0,5) - ie [0,1,2,3,4]. If you prefer cron syntax, parsing it shouldn't be too difficult however.
Use transparent borders if possible.
https://jsfiddle.net/74q3na62/
HTML
<div class="table">
<div class="row">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2</div>
<div class="cell">Cell 3</div>
</div>
</div>
CSS
.table {
display: table;
border: 1px solid black;
}
.row { display:table-row; }
.cell {
display: table-cell;
background-clip: padding-box;
background-color: gold;
border-right: 10px solid transparent;
}
.cell:last-child {
border-right: 0 none;
}
You could use the border-spacing
property, as the accepted answer suggests, but this not only generates space between the table cells but also between the table cells and the table container. This may be unwanted.
If you don't need visible borders on your table cells you should therefore use transparent
borders to generate cell margins. Transparent borders require setting background-clip: padding-box;
because otherwise the background color of the table cells is displayed on the border.
Transparent borders and background-clip are supported in IE9 upwards (and all other modern browsers). If you need IE8 compatibility or don't need actual transparent space you can simply set a white border color and leave the background-clip
out.
you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}
In the past I have used HttpUtility.HtmlEncode to encode text for xml. It performs the same task, really. I havent ran into any issues with it yet, but that's not to say I won't in the future. As the name implies, it was made for HTML, not XML.
You've probably already read it, but here is an article on xml encoding and decoding.
EDIT: Of course, if you use an xmlwriter or one of the new XElement classes, this encoding is done for you. In fact, you could just take the text, place it in a new XElement instance, then return the string (.tostring) version of the element. I've heard that SecurityElement.Escape will perform the same task as your utility method as well, but havent read much about it or used it.
EDIT2: Disregard my comment about XElement, since you're still on 2.0
I know this topic is so old but here is my solution about passing parameters in setInterval
function.
Html:
var fiveMinutes = 60 * 2;
var display = document.querySelector('#timer');
startTimer(fiveMinutes, display);
JavaScript:
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
--timer; // put boolean value for minus values.
}, 1000);
}
Check the version of cvtrs.exe
:
dir "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe"
Wrong version:
date
: 03/18/2010
time
: 01:16 PM
size
: 31,048 bytes
name
: cvtres.exe
Correct version:
date
: 02/21/2011
time
: 06:03 PM
size
: 31,056 bytes
name
: cvtres.exe
If you have wrong version you should copy the correct version from:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cvtres.exe
and replace the one here:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe
i.e.
copy "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cvtres.exe" "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe"
off of @IRadha's answer
in vector drawable setting android:height="_dp"
and setting the scale type to android:scaleType="center"
sets the drawable to whatever size was set
I strongly recommend using a combination of GitLens & GitGraph.
Below snapshot highlights how gitlens is showing commit over time
And the below picture is for the the amazing vivid GitGraph
I change the class with implements TextWatcher to use Brasil currency formats and adjusting cursor position when editing the value.
public class MoneyTextWatcher implements TextWatcher { private EditText editText; private String lastAmount = ""; private int lastCursorPosition = -1; public MoneyTextWatcher(EditText editText) { super(); this.editText = editText; } @Override public void onTextChanged(CharSequence amount, int start, int before, int count) { if (!amount.toString().equals(lastAmount)) { String cleanString = clearCurrencyToNumber(amount.toString()); try { String formattedAmount = transformToCurrency(cleanString); editText.removeTextChangedListener(this); editText.setText(formattedAmount); editText.setSelection(formattedAmount.length()); editText.addTextChangedListener(this); if (lastCursorPosition != lastAmount.length() && lastCursorPosition != -1) { int lengthDelta = formattedAmount.length() - lastAmount.length(); int newCursorOffset = max(0, min(formattedAmount.length(), lastCursorPosition + lengthDelta)); editText.setSelection(newCursorOffset); } } catch (Exception e) { //log something } } } @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { String value = s.toString(); if(!value.equals("")){ String cleanString = clearCurrencyToNumber(value); String formattedAmount = transformToCurrency(cleanString); lastAmount = formattedAmount; lastCursorPosition = editText.getSelectionStart(); } } public static String clearCurrencyToNumber(String currencyValue) { String result = null; if (currencyValue == null) { result = ""; } else { result = currencyValue.replaceAll("[(a-z)|(A-Z)|($,. )]", ""); } return result; } public static boolean isCurrencyValue(String currencyValue, boolean podeSerZero) { boolean result; if (currencyValue == null || currencyValue.length() == 0) { result = false; } else { if (!podeSerZero && currencyValue.equals("0,00")) { result = false; } else { result = true; } } return result; } public static String transformToCurrency(String value) { double parsed = Double.parseDouble(value); String formatted = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")).format((parsed / 100)); formatted = formatted.replaceAll("[^(0-9)(.,)]", ""); return formatted; } }
You are looking for the OS native module for Node.js:
v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform
or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform
os.platform()
Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.
Code for Python 3.6.1
print("This first text and " , end="")
print("second text will be on the same line")
print("Unlike this text which will be on a newline")
Output
>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline
You can choose filling zero data or create zero Mat.
Filling zero data with setTo():
img.setTo(Scalar::all(0));
Create zero data with zeros():
img = zeros(img.size(), img.type());
The img changes address of memory.
You'll need to use a static
readonly
list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T>
rather than List<T>
.
private static readonly ReadOnlyCollection<string> _metrics =
new ReadOnlyCollection<string>(new[]
{
SourceFile.LOC,
SourceFile.MCCABE,
SourceFile.NOM,
SourceFile.NOA,
SourceFile.FANOUT,
SourceFile.FANIN,
SourceFile.NOPAR,
SourceFile.NDC,
SourceFile.CALLS
});
public static ReadOnlyCollection<string> Metrics
{
get { return _metrics; }
}
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
You can create a <p>
element:
<!DOCTYPE html>_x000D_
<html>_x000D_
<script>_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
p = document.createElement("p");_x000D_
p.innerHTML = "Your name is "+lengthOfName+" characters long.";_x000D_
document.body.appendChild(p);_x000D_
</script>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
Make a timer, that activates whatever code you want to when it ticks. Make sure the first line in the timer's code is:
timer.enabled = false
Replace timer with whatever you named your timer.
Then use this in your code:
WebBrowser1.Document.Window.DomWindow.execscript("checkPasswordConfirm();","JavaScript")
timer.enabled = true
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
If webpageelement.InnerText = "Sign Up" Then
webpageelement.InvokeMember("click")
End If
Next
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
I found the solution described above with :
spring.jackson.serialization-inclusion=non_null
To only work starting at the 1.4.0.RELEASE version of spring boot. In all other cases the config is ignored.
I verified this by experimenting with a modification of the spring boot sample "spring-boot-sample-jersey"
Let's keep it simple. What is a call back function?
Example by Parable and Analogy
I have a secretary. Everyday I ask her to: (i) drop off the firm's outgoing mail at the post office, and after she's done that, to do: (ii) whatever task I wrote for her on one of those sticky notes.
Now, what is the task on the sticky-note? The task varies from day to day.
Suppose on this particular day, I require her to print off some documents. So I write that down on the sticky note, and I pin it on her desk along with the outgoing mail she needs to post.
In summary:
The call back function is that second task: printing off those documents. Because it is done AFTER the mail is dropped off, and also because the sticky note telling her to print the document is given to her along with the mail she needs to post.
Let's now tie this in with programming vocabulary
That's all it is. Nothing more. I hope that cleared it up for you - and if not, post a comment and I'll do my best to clarify.
Do it in the controller
$timeout(function(){
$scope.checked = true;
}, 1);
_x000D_
then remove ng-checked.
In the other question I suggested autoexnt. That is also possible in this situation. Just set the service to run manually (ie not automatic at startup). When you want to run your batch, modify the autoexnt.bat file to call the batch file you want, and start the autoexnt service.
The batchfile to start this, can look like this (untested):
echo call c:\path\to\batch.cmd %* > c:\windows\system32\autoexnt.bat
net start autoexnt
Note that batch files started this way run as the system user, which means you do not have access to network shares automatically. But you can use net use to connect to a remote server.
You have to download the Windows 2003 Resource Kit to get it. The Resource Kit can also be installed on other versions of windows, like Windows XP.
Simply omitting the attribute or element works well in less formal data.
If you need more sophisticated information, the GML schemas add the attribute nilReason, eg: in GeoSciML:
xsi:nil
with a value of "true" is used to indicate that no value is availablenilReason
may be used to record additional information for missing values; this may be one of the standard GML reasons (missing, inapplicable, withheld, unknown
), or text prepended by other:
, or may be a URI link to a more detailed explanation.When you are exchanging data, the role for which XML is commonly used, data sent to one recipient or for a given purpose may have content obscured that would be available to someone else who paid or had different authentication. Knowing the reason why content was missing can be very important.
Scientists also are concerned with why information is missing. For example, if it was dropped for quality reasons, they may want to see the original bad data.
ES6 solution:
import DefaultImage from '../assets/image.png';
const DEFAULT_IMAGE = Image.resolveAssetSource(DefaultImage).uri;
and then:
<Image source={{uri: DEFAULT_IMAGE}} />
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
Real example from my code:
return selected.Select(query => query.Name).Aggregate((a, b) => a + ", " + b);
A query is an object that has a Name property which is a string, and I want the names of all the queries on the selected list, separated by commas.
You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}
You can use the class org.apache.commons.lang.StringEscapeUtils:
String s = StringEscapeUtils.unescapeHtml("Happy & Sad")
It is working.
Simply remove the .value
from your code.
Set envFrmwrkPath = ActiveSheet.Range("D6").Value
instead of this, use:
Set envFrmwrkPath = ActiveSheet.Range("D6")
Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:
SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);
You can use pandas library and reference the rows and columns like this:
import pandas as pd
input = pd.read_csv("path_to_file");
#for accessing ith row:
input.iloc[i]
#for accessing column named X
input.X
#for accessing ith row and column named X
input.iloc[i].X
The standard SQL way is to use like:
where @stringVar like '%thisstring%'
That is in a query statement. You can also do this in TSQL:
if @stringVar like '%thisstring%'
Here's the calling order:
app.config()
app.run()
app.controller()
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
From Angular's module docs:
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One situation where run blocks are used is during authentications.
numpy.dot(a, b, out=None)
Dot product of two arrays.
For N dimensions it is a sum product over the last axis of a
and the second-to-last of b
.
Documentation: numpy.dot.
You could use the NumberFormatter class with its parse
method.
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";
That is a working configuration.
try to replace what you have
more_itertools.is_sorted
I'm not sure when this was added, but this hasn't been mentioned yet:
import more_itertools
ls = [1, 4, 2]
print(more_itertools.is_sorted(ls))
ls2 = ["ab", "c", "def"]
print(more_itertools.is_sorted(ls2, key=len))
Read the input continuously within the loop so that the variable line
is assigned a value other than the initial value
while ((line = br.readLine()) !=null) {
...
}
Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files
Would this CSS fix it?
iframe {
display:block;
width:100%;
}
From this example: http://jsfiddle.net/HNyJS/2/show/
The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).
http / https createServer
which simply takes a callback(req,res) e.g.
var server = http.createServer(function (request, response) {
// respond
response.write('hello client!');
response.end();
});
server.listen(3000);
Middleware is basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework
The way it does that is pretty simple (and in fact the code is really short!). As soon as you call var connect = require('connect'); var app = connect();
you get a function app
that can:
.use
(source) to manage plugins (that comes from here because of this simple line of code). Because of 1.) you can do the following :
var app = connect();
// Register with http
http.createServer(app)
.listen(3000);
Combine with 2.) and you get:
var connect = require('connect');
// Create a connect dispatcher
var app = connect()
// register a middleware
.use(function (req, res, next) { next(); });
// Register with http
http.createServer(app)
.listen(3000);
Connect provides a utility function to register itself with http
so that you don't need to make the call to http.createServer(app)
. Its called listen
and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen
. From source
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, you can do:
var connect = require('connect');
// Create a connect dispatcher and register with http
var app = connect()
.listen(3000);
console.log('server running on port 3000');
It's still your good old http.createServer
with a plugin framework on top.
ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use
function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:
createServer
like connect since it too is just a function that can take a req
/res
pair (source). listen
function to register itself with httpIn addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.
The use
function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.
My opinion: you are informed enough ^based on above^ to make your own choice.
http.createServer
if you are creating something like connect / expressjs from scratch. http.createServer
Most people should just use ExpressJS.
These might have been true as some point in time, but wrong now:
that inherits an extended version of http.Server
Wrong. It doesn't extend it and as you have seen ... uses it
Express does to Connect what Connect does to the http module
Express 4.0 doesn't even depend on connect. see the current package.json dependencies section
If you use UPPER(text)
, the like '%lah%'
will always return zero results. Use '%LAH%'
.
The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.
You can use the Random generator to generate a random index and return the element at that index:
//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];
If the request body is empty, then it simply means that it's already been consumed beforehand. For example, by a request.getParameter()
, getParameterValues()
or getParameterMap()
call. Just remove the lines doing those calls from your code.
If the emulator is already open or executing it will tell you is offline. You can double check on the Command Line (Ubuntu) and execute:
adb devices
You must see your emulator offline, you have to close the running instance of the emulator (since the port will show as busy) and after that you can run your application. Hope this helps someone.
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
If you are using asp.net mvc, here is a simple way to access the session.
From a Controller:
{Controller}.ControllerContext.HttpContext.Session["{name}"]
From a View:
<%=Session["{name}"] %>
This is definitely not the best way to access your session variables, but it is a direct route. So use it with caution (preferably during rapid prototyping), and use a Wrapper/Container and OnSessionStart when it becomes appropriate.
HTH
You can also use position fixed css property.
<!-- html code -->
<div class="box" id="myElement"></div>
/* css code */
.box {
position: fixed;
}
// js code
document.getElementById('myElement').style.top = 0; //or whatever
document.getElementById('myElement').style.left = 0; // or whatever
Some of the time savers:
The Canoo blog contains some (+8) articles on some more advanced IntelliJ keyboard shortcuts.
The Key Promoter and Shortcut keys list plugins are really helpful for (constantly) learning new IntelliJ keyboard shortcuts.
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
In my case, it was very slow and i needed to change inspections settings, i tried everything, the only thing that worked was going from 2018.2 version to 2016.2, sometimes is better to be some updates behind...
Try adding a cachebreaker at the end of the url:
newImage.src = "http://localhost/image.jpg?" + new Date().getTime();
This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.
MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]
. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.
To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED
.
You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.
Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:
"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*
As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.
If you're getting "Cannot resolve method getSupportFragmentManager()", try using
this.getSupportFragmentManager()
It works for me when dealing with DialogFragments in android
In my case, since my Java code is meant to be ported to other languages in the near future (Mainly C++), I at least want to pay lip service to freeing memory properly so it helps the porting process later on.
I personally rely on nulling variables as a placeholder for future proper deletion. For example, I take the time to nullify all elements of an array before actually deleting (making null) the array itself.
But my case is very particular, and I know I'm taking performance hits when doing this.
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }
Suppose you have Vue project created with vue-cli (e.g. vue init webpack my-project). Go to project dir and run
npm install jquery --save
Open file build/webpack.base.conf.js
and add plugins
:
module.exports = {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
...
}
Also at top of file add:
const webpack = require('webpack')
If you are using ESLint, open .eslintrc.js
and add next globals: {
module.exports = {
globals: {
"$": true,
"jQuery": true
},
...
Now you are ready to go. Use $ anywhere in your js.
NOTE You don't need to include expose loader or any other stuff to use this.
Originally from https://maketips.net/tip/223/how-to-include-jquery-into-vuejs
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>
In addition to the answer by Scott Barta above, you may still have import problems if there are references to Eclipse workspace library files, with e.g.
/workspace/android-support-v7-appcompat
being a common one.
In this case the import will halt until you provide a reference (and if you've cloned from a git repo, it probably won't be there) and even pointing to your own install (e.g. something like /android-sdk-macosx/extras/android/m2repository/com/android/support/appcompat-v7) won't be recognised and will halt the import, leaving you in no-man's land.
To get around this, look for refs in the project.properties or .classpath files that came in from the Eclipse project and remove/comment them out, e.g.
<classpathentry combineaccessrules="false" kind="src" path="/android-support-v7-appcompat"/>
That will get you past the import stage and you can then add these refs in your build.gradle (Module:app) as indicated in the Android tutorial, like below:
dependencies {
compile 'com.android.support:appcompat-v7:22.2.0'
}
You can use the onsubmit function.
If you return false the form won't get submitted. Read up about it here.
$('#myform').submit(function() {
// your code here
});
Why not use a Single liner ...
IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
I find using these interactive tools help visualize what's happening, and whats possible
http://css3gen.com/box-shadow/
http://www.cssmatic.com/box-shadow
Edit: Check out the other tools for experimenting with the other generators and combinations. I have to remind myself sometimes that just because you can, doesn't mean you should - its easy to get carried away!
your_string = 'Hello world';
words_array = your_tring.split(' ');
string_without_space = '';
for(i=0; i<words_array.length; i++){
new_text += words_array[i];
}
console.log("The new word:" new_text);
The output:
HelloWorld
While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.
Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.
You can get the output of that command and put it in a variable. then use heredoc
. for example:
nc -l -p 80 <<< "tested like a charm";
can be written like:
nc -l -p 80 <<EOF
tested like a charm
EOF
and like this (this is what you want):
text="tested like a charm"
nc -l -p 80 <<EOF
$text
EOF
Practical example in busybox
under docker
container:
kasra@ubuntu:~$ docker run --rm -it busybox
/ # nc -l -p 80 <<< "tested like a charm";
sh: syntax error: unexpected redirection
/ # nc -l -p 80 <<EOL
> tested like a charm
> EOL
^Cpunt! => socket listening, no errors. ^Cpunt! is result of CTRL+C signal.
/ # text="tested like a charm"
/ # nc -l -p 80 <<EOF
> $text
> EOF
^Cpunt!
Note: Commenting out bind_ip can make your system vulnerable to security flaws. Please see Security Checklist. It is a better idea to add more IP addresses than to open up your system to everything.
You need to edit your /etc/mongod.conf file's bind_ip variable to include the IP of the computer you're using, or eliminate it altogether.
I was able to connect using the following mongod.conf file. I commented out bind_ip and uncommented port.
# mongod.conf
# Where to store the data.
# Note: if you run MongoDB as a non-root user (recommended) you may
# need to create and set permissions for this directory manually.
# E.g., if the parent directory isn't mutable by the MongoDB user.
dbpath=/var/lib/mongodb
# Where to log
logpath=/var/log/mongodb/mongod.log
logappend=true
port = 27017
# Listen to local interface only. Comment out to listen on all
interfaces.
#bind_ip = 127.0.0.1
# Disables write-ahead journaling
# nojournal = true
# Enables periodic logging of CPU utilization and I/O wait
#cpu = true
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
# Verbose logging output.
#verbose = true
# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true
# Enable db quota management
#quota = true
# Set oplogging level where n is
# 0=off (default)
# 1=W
# 2=R
# 3=both
# 7=W+some reads
#diaglog = 0
# Ignore query hints
#nohints = true
# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true
# Turns off server-side scripting. This will result in greatly limited
# functionality
#noscripting = true
# Turns off table scans. Any query that would do a table scan fails.
#notablescan = true
# Disable data file preallocation.
#noprealloc = true
# Specify .ns file size for new databases.
# nssize = <size>
# Replication Options
# In replicated MongoDB databases, specify the replica set name here
#replSet=setname
# Maximum size in megabytes for replication operation log
#oplogSize=1024
# Path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile
Don't forget to restart the mongod service before trying to connect:
service mongod restart
From Robomongo, I used the following connection settings:
Connection Tab:
SSH Tab:
SSH Address: [VPS IP] : 22
SSH User Name: [Username for sudo enabled user]
SSH Auth Method: Password
User Password: Supersecret
RStudio has a good free IDE that allows for Markdown and LaTeX.
The PDB file is a Visual Studio specific file that has the debugging symbols for your project. You can ignore those messages, unless you're hoping to step into the code for those dlls with the debugger (which is doubtful, as those are system dlls). In other words, you can and should ignore them, as you won't have the PDB files for any of those dlls (by default at least, it turns out you can actually obtain them when debugging via the Microsoft Symbol Server). All it means is that when you set a breakpoint and are stepping through the code, you won't be able to step into any of those dlls (which you wouldn't want to do anyways).
Just for completeness, here's the official PDB description from MSDN:
A program database (PDB) file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A PDB file is created when you compile a C/C++ program with /ZI or /Zi
Also for future reference, if you want to have PDB files for your own code, you would would have to build your project with either the /ZI or /Zi options enabled (you can set them via project properties --> C/C++ --> General, then set the field for "Debug Information Format"). Not relevant to your situation, but I figured it might be useful in the future
terrific answer from DuckPuncher, for Python3 make sure you install pdfminer2 and do:
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = io.StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,
password=password,
caching=caching,
check_extractable=True):
interpreter.process_page(page)
fp.close()
device.close()
text = retstr.getvalue()
retstr.close()
return text
This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.
.
character as a wildcard to match any single character.Example regex: a.c
abc // match
a c // match
azc // match
ac // no match
abbc // no match
[]
to match any characters in a set.\w
to match any single alphanumeric character: 0-9
, a-z
, A-Z
, and _
(underscore).\d
to match any single digit.\s
to match any single whitespace character.Example 1 regex: a[bcd]c
abc // match
acc // match
adc // match
ac // no match
abbc // no match
Example 2 regex: a[0-7]c
a0c // match
a3c // match
a7c // match
a8c // no match
ac // no match
a55c // no match
Use the hat in square brackets [^]
to match any single character except for any of the characters that come after the hat ^
.
Example regex: a[^abc]c
aac // no match
abc // no match
acc // no match
a c // match
azc // match
ac // no match
azzc // no match
(Don't confuse the ^
here in [^]
with its other usage as the start of line character: ^
= line start, $
= line end.)
Use the optional character ?
after any character to specify zero or one occurrence of that character. Thus, you would use .?
to match any single character optionally.
Example regex: a.?c
abc // match
a c // match
azc // match
ac // match
abbc // no match
Option 1 allows you to initialize const
members. This cannot be done with option 2 (as they are assigned to, not initialized).
Why must const members be intialized in the constructor initializer rather than in its body?
I was stuck here too. copy-webpack-plugin worked for me.
However, 'copy-webpack-plugin' was not necessary in my case (i learned later).
webpack ignores root paths
example
<img src="/images/logo.png'>
Hence, to make this work without using 'copy-webpack-plugin' use '~' in paths
<img src="~images/logo.png'>
'~' tells webpack to consider 'images' as a module
note: you might have to add the parent directory of images directory in
resolve: {
modules: [
'parent-directory of images',
'node_modules'
]
}
The constructor of PetStore
will call a constructor of Farm
; there's
no way you can prevent it. If you do nothing (as you've done), it will
call the default constructor (Farm()
); if you need to pass arguments,
you'll have to specify the base class in the initializer list:
PetStore::PetStore()
: Farm( neededArgument )
, idF( 0 )
{
}
(Similarly, the constructor of PetStore
will call the constructor of
nameF
. The constructor of a class always calls the constructors of
all of its base classes and all of its members.)
I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:
componentDidMount(){
fetch('./data/json-data.json')
.then ( resp1 => resp1.json() )
.then ( users1 => this.setState( {cards : users1} ) )
}
so I created public/data/json-data.json
and everything was fine then :)
You can do like this:
a {font-size: 100px}
Try avoid using font tag because it's deprecated. Use CSS like above instead. You can give your anchors specific class and apply any style for them.
A bit more along the same lines
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <- d
}
f(20)
print(attrs.a)
will print "1"
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <<- d
}
f(20)
print(attrs.a)
Will print "20"
https://jumpcloud.com/blog/difference-between-ldap-and-active-directory/
Realistically, there are probably more differences than similarities between the two directory solutions. Microsoft’s AD is largely a directory for Windows users, devices, and applications. AD requires a Microsoft Domain Controller to be present and when it is, users are able to single sign-on to Windows resources that live within the domain structure.
LDAP, on the other hand, has largely worked outside of the Windows structure focusing on the Linux / Unix environment and with more technical applications. LDAP doesn’t have the same concepts of domains or single sign-on. LDAP is largely implemented with open source solutions and as a result has more flexibility than AD.
Another critical difference between LDAP and Active Directory is how AD and LDAP each approach device management. AD manages Windows devices through and Group Policy Objects (GPOs). A similar concept doesn’t exist within LDAP. Both LDAP and AD are highly different solutions and as a result many organization must leverage both to serve different purposes.
This is why there’s an obvious opportunity for innovation. Why leverage and manage two complete systems, when one system can effectively merge the two?
Table A
+--------+-----------+
| A-num | text |
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
+--------+-----------+
Table B
+------+------+--------------+
| B-num| date | A-num |
| 22 | 01.08.2003 | 2 |
| 23 | 02.08.2003 | 2 |
| 24 | 03.08.2003 | 1 |
| 25 | 04.08.2003 | 4 |
| 26 | 05.03.2003 | 4 |
I will update field text in table A with
UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`
and come to this result:
Table A
+--------+------------------------+
| A-num | text |
| 1 | 24 from 03 08 2003 / |
| 2 | 22 from 01 08 2003 / |
| 3 | |
| 4 | 25 from 04 08 2003 / |
| 5 | |
--------+-------------------------+
where only one field from Table B is accepted, but I will come to this result:
Table A
+--------+--------------------------------------------+
| A-num | text |
| 1 | 24 from 03 08 2003 |
| 2 | 22 from 01 08 2003 / 23 from 02 08 2003 / |
| 3 | |
| 4 | 25 from 04 08 2003 / 26 from 05 03 2003 / |
| 5 | |
+--------+--------------------------------------------+
Another options is Matteo Bicocchi's jQuery mb.extruder tabs plug-in: http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-extruder/
eval:
This is very powerful, but is also very dangerous if you accept strings to evaluate from untrusted input. Suppose the string being evaluated is "os.system('rm -rf /')" ? It will really start deleting all the files on your computer.
ast.literal_eval:
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets.
Syntax:
eval(expression, globals=None, locals=None)
import ast
ast.literal_eval(node_or_string)
Example:
# python 2.x - doesn't accept operators in string format
import ast
ast.literal_eval('[1, 2, 3]') # output: [1, 2, 3]
ast.literal_eval('1+1') # output: ValueError: malformed string
# python 3.0 -3.6
import ast
ast.literal_eval("1+1") # output : 2
ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}") # output : {'a': 2, 'b': 3, 3:'xyz'}
# type dictionary
ast.literal_eval("",{}) # output : Syntax Error required only one parameter
ast.literal_eval("__import__('os').system('rm -rf /')") # output : error
eval("__import__('os').system('rm -rf /')")
# output : start deleting all the files on your computer.
# restricting using global and local variables
eval("__import__('os').system('rm -rf /')",{'__builtins__':{}},{})
# output : Error due to blocked imports by passing '__builtins__':{} in global
# But still eval is not safe. we can access and break the code as given below
s = """
(lambda fc=(
lambda n: [
c for c in
().__class__.__bases__[0].__subclasses__()
if c.__name__ == n
][0]
):
fc("function")(
fc("code")(
0,0,0,0,"KABOOM",(),(),(),"","",0,""
),{}
)()
)()
"""
eval(s, {'__builtins__':{}})
In the above code ().__class__.__bases__[0]
nothing but object itself.
Now we instantiated all the subclasses, here our main enter code here
objective is to find one class named n from it.
We need to code
object and function
object from instantiated subclasses. This is an alternative way from CPython
to access subclasses of object and attach the system.
From python 3.7 ast.literal_eval() is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. link
Although this is an old thread I thought that I would add a comment as I have come across it whilst trying to solve a similar issue; this might help anyone else who may find themselves here:
The backslash character is used to ignore the next character; once added to the font name in my gvimrc it worked; I am on a GNU/Linux machine which does not like spaces. I suspect that the initial post was an error due to the back slash being used on a windows machine.
In example:
:set guifont? ## From gvim command, would give the following:
set guifont=DejaVu Sans Mono for Powerline 11
Where as I needed to add this line to the gvimrc file for it to be read:
set guifont=DejaVu\ Sans\ Mono\ for\ Powerline\ 11
Watcher with the deep option didn't work for me.
Instead, I use updated() lifecycle hook which gets executed everytime the component's data changes. Just use it like you do with mounted().
mounted() {
/* to be executed when mounted */
},
updated() {
console.log(this.$route)
}
For your reference, visit the documentation.
One of the fast ways to create a dict from equal-length tuples:
>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }
Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/
Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.
@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront
. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.
Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.
Sorry but that's just much too much overhead (above), short and quick, if you have the MapFragment, you also have to map, just do the following:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true)
} else {
// Show rationale and request permission.
}
Code is in Kotlin, hope you don't mind.
have fun
Btw I think this one is a duplicate of: Show Current Location inside Google Map Fragment
with EF 6.2 it worked for me
var query = context.People
.GroupBy(p => new {p.name})
.Select(g => new { name = g.Key.name, count = g.Count() });