Depending on your version:
Python 2.x:
for key, val in PIX0.iteritems():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
Python 3.x:
for key, val in PIX0.items():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
You should also get in the habit of using the new string formatting syntax ({}
instead of %
operator) from PEP 3101:
Updated Solution - using the schema solution that we were debating. This gets you to your answer:
Sample Schema:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<complexType name="sportType">
<attribute name="type" type="string" />
<attribute name="gender" type="string" />
</complexType>
<element name="sports">
<complexType>
<sequence>
<element name="sport" minOccurs="0" maxOccurs="unbounded"
type="tns:sportType" />
</sequence>
</complexType>
</element>
Code Generated
SportType:
package org.example.sport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public String getGender() {
return gender;
}
public void setGender(String value) {
this.gender = value;
}
}
Sports:
package org.example.sport;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"sport"
})
@XmlRootElement(name = "sports")
public class Sports {
protected List<SportType> sport;
public List<SportType> getSport() {
if (sport == null) {
sport = new ArrayList<SportType>();
}
return this.sport;
}
}
Output class files are produced by running xjc against the schema on the command line
There isn't any graph api for this, you need to use facebook xmpp chat api to send the message, good news is: I have made a php class which is too easy to use,call a function and message will be sent, its open source, check it out: facebook message api php the description says its a closed source but the it was made open source later, see the first comment, you can clone from github. It's a open source now.
This is an alternative answer for the case where tqdm_notebook doesn't work for you.
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values)) as pbar:
for i in values:
pbar.write('processed: %d' %i)
pbar.update(1)
sleep(1)
The output would look something like this (progress would show up red):
0%| | 0/3 [00:00<?, ?it/s]
processed: 1
67%|¦¦¦¦¦¦? | 2/3 [00:01<00:00, 1.99it/s]
processed: 2
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
processed: 3
The problem is that the output to stdout and stderr are processed asynchronously and separately in terms of new lines.
If say Jupyter receives on stderr the first line and then the "processed" output on stdout. Then once it receives an output on stderr to update the progress, it wouldn't go back and update the first line as it would only update the last line. Instead it will have to write a new line.
One workaround would be to output both to stdout instead:
import sys
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
for i in values:
pbar.write('processed: %d' % (1 + i))
pbar.update(1)
sleep(1)
The output will change to (no more red):
processed: 1 | 0/3 [00:00<?, ?it/s]
processed: 2 | 0/3 [00:00<?, ?it/s]
processed: 3 | 2/3 [00:01<00:00, 1.99it/s]
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
Here we can see that Jupyter doesn't seem to clear until the end of the line. We could add another workaround for that by adding spaces. Such as:
import sys
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
for i in values:
pbar.write('processed: %d%s' % (1 + i, ' ' * 50))
pbar.update(1)
sleep(1)
Which gives us:
processed: 1
processed: 2
processed: 3
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
It might in general be more straight forward not to have two outputs but update the description instead, e.g.:
import sys
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
for i in values:
pbar.set_description('processed: %d' % (1 + i))
pbar.update(1)
sleep(1)
With the output (description updated while it's processing):
processed: 3: 100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
You can mostly get it to work fine with plain tqdm. But if tqdm_notebook works for you, just use that (but then you'd probably not read that far).
Another option could be using an Attribute Selector:
[class^="your-class-name"]{
//your style here
}
Whereas every class starting with "your-class-name" uses this style.
So in your case, you could do it like so:
[class^="class"]{
display: inline-block;
//some other properties
&:hover{
color: darken(#FFFFFF, 10%);
}
}
.class-b{
//specifically for class b
width: 100px;
&:hover{
color: darken(#FFFFFF, 20%);
}
}
More about Attribute Selectors on w3Schools
Besides using multiple proxies or proxy-networks, you might want to try the planet-lab. (And probably there are other similar institutions around).
The social solution would be to post a question on some board that you are searching for volunteers that proxy your requests. (They only have to allow for one destination in their proxy config thus the danger of becoming spam-whores is relatively low.) You should prepare credentials that ensure your partners of the authenticity of the claim that the destination is indeed your computer.
Restarting visual studio code worked for me !
I think the following is the easiest way to do it.
<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>
Try this way:
public class Bin {
public static void main(String[] args) {
System.out.println(toBinary(0x94, 8));
}
public static String toBinary(int a, int bits) {
if (--bits > 0)
return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
else
return (a&0x1)==0?"0":"1";
}
}
10010100
I think your question is, "why am I getting one more line than there is in the file?"
Imagine a file:
line 1
line 2
line 3
The file may be represented in ASCII like this:
line 1\nline 2\nline 3\n
(Where \n
is byte 0x10
.)
Now let's see what happens before and after each getline
call:
Before 1: line 1\nline 2\nline 3\n
Stream: ^
After 1: line 1\nline 2\nline 3\n
Stream: ^
Before 2: line 1\nline 2\nline 3\n
Stream: ^
After 2: line 1\nline 2\nline 3\n
Stream: ^
Before 2: line 1\nline 2\nline 3\n
Stream: ^
After 2: line 1\nline 2\nline 3\n
Stream: ^
Now, you'd think the stream would mark eof
to indicate the end of the file, right? Nope! This is because getline
sets eof
if the end-of-file marker is reached "during it's operation". Because getline
terminates when it reaches \n
, the end-of-file marker isn't read, and eof
isn't flagged. Thus, myfile.eof()
returns false, and the loop goes through another iteration:
Before 3: line 1\nline 2\nline 3\n
Stream: ^
After 3: line 1\nline 2\nline 3\n
Stream: ^ EOF
How do you fix this? Instead of checking for eof()
, see if .peek()
returns EOF
:
while(myfile.peek() != EOF){
getline ...
You can also check the return value of getline
(implicitly casting to bool):
while(getline(myfile,line)){
cout<< ...
The comment in your code is wrong. INADDR_ANY
doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.
You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.
Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.
The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.
If you'd like to do it for all dialogs throughout the site try the following code...
$.extend( $.ui.dialog.prototype.options, {
open: function() {
var dialog = this;
$('.ui-widget-overlay').bind('click', function() {
$(dialog).dialog('close');
});
}
});
In your specific example they are the same, because the optimizer has figured out what you are trying to do is the same in both examples. But it is possible that in non-trivial examples the optimizer may not do this, and in that case there are reasons to prefer one to other on occasion.
NOT IN
should be preferred if you are testing multiple rows in your outer select. The subquery inside the NOT IN
statement can be evaluated at the beginning of the execution, and the temporary table can be checked against each value in the outer select, rather than re-running the subselect every time as would be required with the NOT EXISTS
statement.
If the subquery must be correlated with the outer select, then NOT EXISTS
may be preferable, since the optimizer may discover a simplification that prevents the creation of any temporary tables to perform the same function.
I achieved it by placing the image tag before the li's:
HTML
<img src="https://www.pinclipart.com/picdir/big/1-17498_plain-right-white-arrow-clip-art-at-clipart.png" class="listImage">
CSS
.listImage{
float:left;
margin:2px;
width:25px
}
.li{
margin-left:29px;
}
ADD
(docs)The ADD
command can accept as a <src>
parameter:
ADD folder /path/inside/your/container
or
tar -cvzf newArchive.tar.gz /path/to/your/folder
You would then add a line to your Dockerfile like this:
ADD /path/to/archive/newArchive.tar.gz /path/inside/your/container
Notes:
ADD
will automatically extract your archive.For API level 3+, nothing more then one line of code:
Intent intent = context.getPackageManager().getLaunchIntentForPackage("name.of.package");
Return a CATEGORY_INFO launch Intent (apps with no launcher activity, wallpapers for example, often use this to provide some information about app) and, if no find it, returns the CATEGORY_LAUNCH of package, if exists.
The differences are covered at the PostgreSQL documentation for date/time types. Yes, the treatment of TIME
or TIMESTAMP
differs between one WITH TIME ZONE
or WITHOUT TIME ZONE
. It doesn't affect how the values are stored; it affects how they are interpreted.
The effects of time zones on these data types is covered specifically in the docs. The difference arises from what the system can reasonably know about the value:
With a time zone as part of the value, the value can be rendered as a local time in the client.
Without a time zone as part of the value, the obvious default time zone is UTC, so it is rendered for that time zone.
The behaviour differs depending on at least three factors:
WITH TIME ZONE
or WITHOUT TIME ZONE
) of the value.Here are examples covering the combinations of those factors:
foo=> SET TIMEZONE TO 'Japan';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+09
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 06:00:00+09
(1 row)
foo=> SET TIMEZONE TO 'Australia/Melbourne';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+11
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 08:00:00+11
(1 row)
It seems that you are asking multiple things. To answer them:
You can extract the numbers by catching them in capturing parentheses:
.*(\d+) rofl.*
and using $1
to get the string out (.*
is for "the rest before and after on the same line)
With sed as example, the idea becomes this to replace all strings in a file with only the matching number:
sed -e 's/.*(\d+) rofl.*/$1/g' inputFileName > outputFileName
or:
echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'
It's nano seconds, what are the chances of getting the same seed twice.
Anyway, thanks for the help, here is my end solution based on all the input.
package main
import (
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
// generates a random string
func srand(min, max int, readable bool) string {
var length int
var char string
if min < max {
length = min + rand.Intn(max-min)
} else {
length = min
}
if readable == false {
char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
} else {
char = "ABCDEFHJLMNQRTUVWXYZabcefghijkmnopqrtuvwxyz23479"
}
buf := make([]byte, length)
for i := 0; i < length; i++ {
buf[i] = char[rand.Intn(len(char)-1)]
}
return string(buf)
}
// For testing only
func main() {
println(srand(5, 5, true))
println(srand(5, 5, true))
println(srand(5, 5, true))
println(srand(5, 5, false))
println(srand(5, 7, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 4, true))
println(srand(5, 400, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
}
Disallow Nulls on the column and set a default on the column of getdate()
/*Deal with any existing NULLs*/
UPDATE YourTable SET created_date=GETDATE() /*Or some sentinel value
'19000101' maybe?*/
WHERE created_date IS NULL
/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN created_date DATE NOT NULL
/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
DF_YourTable_created_date DEFAULT GETDATE() FOR created_date
I also tried to get the field1 = 'a' OR field2 = 'b'
Your code didn't work for me.
Here is my solution
$results = Mage::getModel('xyz/abc')->getCollection();
$results->addFieldToSelect('name');
$results->addFieldToSelect('keywords');
$results->addOrder('name','ASC');
$results->setPageSize(5);
$results->getSelect()->where("keywords like '%foo%' or additional_keywords like '%bar%'");
$results->load();
echo json_encode($results->toArray());
It gives me
SELECT name, keywords FROM abc WHERE keywords like '%foo%' OR additional_keywords like '%bar%'
.
It is maybe not the "magento's way" but I was stuck 5 hours on that.
Hope it will help
Just after running mysql query from php
get it by
$lastid=mysql_insert_id();
this give you the alst auto increment id value
Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.
Use the typedef
specifier to avoid re-using the struct
statement everytime you declare a struct variable:
typedef struct
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}Body;
Then declare your array of structs. Initialization of each element goes along with the declaration:
Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};
To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
Though having things on the stack might be an advantage in terms of allocation and automatic freeing, it has some disadvantages.
You might not want to allocate huge objects on the Stack.
Dynamic dispatch! Consider this code:
#include <iostream>
class A {
public:
virtual void f();
virtual ~A() {}
};
class B : public A {
public:
virtual void f();
};
void A::f() {cout << "A";}
void B::f() {cout << "B";}
int main(void) {
A *a = new B();
a->f();
delete a;
return 0;
}
This will print "B". Now lets see what happens when using Stack:
int main(void) {
A a = B();
a.f();
return 0;
}
This will print "A", which might not be intuitive to those who are familiar with Java or other object oriented languages. The reason is that you don't have a pointer to an instance of B
any longer. Instead, an instance of B
is created and copied to a
variable of type A
.
Some things might happen unintuitively, especially when you are new to C++. In C you have your pointers and that's it. You know how to use them and they do ALWAYS the same. In C++ this is not the case. Just imagine what happens, when you use a in this example as an argument for a method - things get more complicated and it DOES make a huge difference if a
is of type A
or A*
or even A&
(call-by-reference). Many combinations are possible and they all behave differently.
They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"
Try using this: http://home.wlu.edu/~levys/software/kbhit.py It's non-blocking (that means that you can have a while loop and detect a key press without stopping it) and cross-platform.
import os
# Windows
if os.name == 'nt':
import msvcrt
# Posix (Linux, OS X)
else:
import sys
import termios
import atexit
from select import select
class KBHit:
def __init__(self):
'''Creates a KBHit object that you can call to do various keyboard things.'''
if os.name == 'nt':
pass
else:
# Save the terminal settings
self.fd = sys.stdin.fileno()
self.new_term = termios.tcgetattr(self.fd)
self.old_term = termios.tcgetattr(self.fd)
# New terminal setting unbuffered
self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)
# Support normal-terminal reset at exit
atexit.register(self.set_normal_term)
def set_normal_term(self):
''' Resets to normal terminal. On Windows this is a no-op.
'''
if os.name == 'nt':
pass
else:
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)
def getch(self):
''' Returns a keyboard character after kbhit() has been called.
Should not be called in the same program as getarrow().
'''
s = ''
if os.name == 'nt':
return msvcrt.getch().decode('utf-8')
else:
return sys.stdin.read(1)
def getarrow(self):
''' Returns an arrow-key code after kbhit() has been called. Codes are
0 : up
1 : right
2 : down
3 : left
Should not be called in the same program as getch().
'''
if os.name == 'nt':
msvcrt.getch() # skip 0xE0
c = msvcrt.getch()
vals = [72, 77, 80, 75]
else:
c = sys.stdin.read(3)[2]
vals = [65, 67, 66, 68]
return vals.index(ord(c.decode('utf-8')))
def kbhit(self):
''' Returns True if keyboard character was hit, False otherwise.
'''
if os.name == 'nt':
return msvcrt.kbhit()
else:
dr,dw,de = select([sys.stdin], [], [], 0)
return dr != []
An example to use this:
import kbhit
kb = kbhit.KBHit()
while(True):
print("Key not pressed") #Do something
if kb.kbhit(): #If a key is pressed:
k_in = kb.getch() #Detect what key was pressed
print("You pressed ", k_in, "!") #Do something
kb.set_normal_term()
Or you could use the getch module from PyPi. But this would block the while loop
I'd like to second Polin's answer and just add one thing in case you are still stuck. This code certainly does work to set a specific cookie expiration time. One issue you may be having is that if you are using Chrome and accessing your page via "http://localhost..." or "file://", Chrome will not store cookies. The easy fix for this is to use a simple http server (like node's http-server if you haven't already) and navigate to your page explicitly as "http://127.0.0.1" in which case Chrome WILL store cookies for local development. This had me hung up for a bit as, if you don't do this, your expires key will simply have the value of "session" when you investigate it in the console or in Dev Tools.
If it's not possible to start the main process again (for long enough), there is also the possibility to commit
the container to a new image and run a new container from this image. While this is not the usual best practice workflow, I find it really useful to debug a failing script once in a while.
docker exec -it 6198ef53d943 bash
Error response from daemon: Container 6198ef53d9431a3f38e8b38d7869940f7fb803afac4a2d599812b8e42419c574 is not running
docker commit 6198ef53d943
sha256:ace7ca65e6e3fdb678d9cdfb33a7a165c510e65c3bc28fecb960ac993c37ef33
docker run -it ace7ca65e6e bash
root@72d38a8c787d:/#
To open the Eye Dropper simply:
Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.
update q
set q.QuestionID = a.QuestionID
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want
I recommend to check what the result set to update is before running the update (same query, just with a select):
select *
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want
Particularly whether each answer id has definitely only 1 associated question id.
It will already work, as David pointed out!
>>> def machineEpsilon(func=float):
... machine_epsilon = func(1)
... while func(1)+func(machine_epsilon) != func(1):
... machine_epsilon_last = machine_epsilon
... machine_epsilon = func(machine_epsilon) / func(2)
... return machine_epsilon_last
...
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07
Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':
<input type="checkbox" id="chk0" name="chk0" value="true" disabled>
$('#chk0').attr("disabled", "disabled");
You'll also need to remove the attribute for disabled
to enable the checkbox. Something like:
$('#chk0').removeAttr("disabled");
See the docs for removeAttr
The value XHTML for disabling/enabling an input element is as follows:
<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />
Note that it's the absence of the disabled attribute that makes the input element enabled.
Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/
edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/
The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
In my case, the accepted solution was just too slow. For a table with 180K rows the rate of updates was about 10 rows per second. This is with the indexes on the join elements.
I finally resolved my issue using a procedure:
CREATE DEFINER=`my_procedure`@`%` PROCEDURE `rescue`()
BEGIN
declare str VARCHAR(255) default '';
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE cur_name VARCHAR(45) DEFAULT '';
DECLARE cur_value VARCHAR(10000) DEFAULT '';
SELECT COUNT(*) FROM tableA INTO n;
SET i=0;
WHILE i<n DO
SELECT namea,valuea FROM tableA limit i,1 INTO cur_name,cur_value;
UPDATE tableB SET nameb=cur_name where valueb=cur_value;
SET i = i + 1;
END WHILE;
END
I hope it will help someone in the future like it helped me
Here are the outputs of isset()
and empty()
for the 4 possibilities: undeclared, null, false and true.
$a=null;
$b=false;
$c=true;
var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared
//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) }
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) }
You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false
. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset
and false when tested by 'empty'.
So use isset()
when you're concerned about the existence of a variable. And use empty
when you're testing for true or false. If the actual type of emptiness matters, use is_null
and ===0
, ===false
, ===''
.
Input Dimension Clarified:
Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:
It (the word dimension alone) can refer to:
a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"
b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or
"Input Layer / Input Feature Dimension"
c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.
"N Dimensionality of Input"
d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:
Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature
model = Sequential()
model.add(Dense(32, input_dim=784)) #or 3 in the current posted example above
model.add(Activation('relu'))
In Keras LSTM, it refers to the total Time Steps
The term has been very confusing, is correct and we live in a very confusing world!!
I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.
I ended up creating new Provisioning profiles, not sure if it was because of:
"The ad hoc distribution provisioning profile is corrupted and the device is having an issue with it."
Why not use the <textarea>
tag?
?<textarea id="txtArea" rows="10" cols="70"></textarea>
Here's the SQL code I would use.
SELECT
f.name AS 'Name of Foreign Key',
OBJECT_NAME(f.parent_object_id) AS 'Table name',
COL_NAME(fc.parent_object_id,fc.parent_column_id) AS 'Fieldname',
OBJECT_NAME(t.object_id) AS 'References Table name',
COL_NAME(t.object_id,fc.referenced_column_id) AS 'References fieldname',
'ALTER TABLE [' + OBJECT_NAME(f.parent_object_id) + '] DROP CONSTRAINT [' + f.name + ']' AS 'Delete foreign key',
'ALTER TABLE [' + OBJECT_NAME(f.parent_object_id) + '] WITH NOCHECK ADD CONSTRAINT [' +
f.name + '] FOREIGN KEY([' + COL_NAME(fc.parent_object_id,fc.parent_column_id) + ']) REFERENCES ' +
'[' + OBJECT_NAME(t.object_id) + '] ([' +
COL_NAME(t.object_id,fc.referenced_column_id) + '])' AS 'Create foreign key'
-- , delete_referential_action_desc AS 'UsesCascadeDelete'
FROM sys.foreign_keys AS f,
sys.foreign_key_columns AS fc,
sys.tables t
WHERE f.OBJECT_ID = fc.constraint_object_id
AND t.OBJECT_ID = fc.referenced_object_id
AND OBJECT_NAME(t.object_id) = 'Employees' -- Just show the FKs which reference a particular table
ORDER BY 2
It's not particularly clear SQL, so let's look at an example.
So, supposing I wanted to drop the Employees
table in Microsoft's beloved Northwind
database, but SQL Server told me that one or more Foreign Keys were preventing me from doing this.
The SQL command above would return these results...
It shows me that there are 3 Foreign Keys which reference the Employees
table. In other words, I wouldn't be allowed to delete (drop) this table until these three Foreign Keys are first deleted.
In the results, the first row is how the following Foreign Key constraint would be shown in the results.
ALTER TABLE [dbo].[Employees] WITH NOCHECK
ADD CONSTRAINT [FK_Employees_Employees] FOREIGN KEY([ReportsTo])
REFERENCES [dbo].[Employees] ([EmployeeID])
The second-to-last column shows the SQL command I would need to use to delete one of these Foreign Keys, eg:
ALTER TABLE [Employees] DROP CONSTRAINT [FK_Employees_Employees]
...and the right-hand column shows the SQL to create it...
ALTER TABLE [Employees] WITH NOCHECK
ADD CONSTRAINT [FK_Employees_Employees]
FOREIGN KEY([ReportsTo]) REFERENCES [Employees] ([EmployeeID])
With all of these commands, you have everything you need to delete the relevant Foreign Keys to allow you to delete a table, then recreate them later.
Phew. Hope this helps.
Add a $event
to the ng-click
, for example:
<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>
Then the jQuery.Event
was passed to the callback:
The PHP.net recommended way of setting the charset is now this:
<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">
Total: {{num1 + num2}}
and in js :
parseInt($scope.num1) + parseInt($scope.num2)
As stated from David Cournapeau, use figure().
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
Or subplot(121) / subplot(122) for the same plot, different position.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
"most convenient block of data" probably refers to the width (in bits) of the WORD, in correspondance to the system bus width, or whatever underlying "bandwidth" is available. On a 16 bit system, with WORD being defined as 16 bits wide, moving data around in chunks the size of a WORD will be the most efficient way. (On hardware or "system" level.)
With Java being more or less platform independant, it just defines a "WORD" as the next size from a "BYTE", meaning "full bandwidth". I guess any platform that's able to run Java will use 32 bits for a WORD.
If you are looking to have multiple subscripts in one text then use the star(*) to separate the sections:
plot(1:10, xlab=expression('hi'[5]*'there'[6]^8*'you'[2]))
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:
Short answer: Don't push amended commits to a public repo.
Long answer: A few Git commands, like git commit --amend
and git rebase
, actually rewrite the history graph. This is fine as long as you haven't published your changes, but once you do, you really shouldn't be mucking around with the history, because if someone already got your changes, then when they try to pull again, it might fail. Instead of amending a commit, you should just make a new commit with the changes.
However, if you really, really want to push an amended commit, you can do so like this:
$ git push origin +master:master
The leading +
sign will force the push to occur, even if it doesn't result in a "fast-forward" commit. (A fast-forward commit occurs when the changes you are pushing are a direct descendant of the changes already in the public repo.)
I always try to factor out complex boolean expressions into meaningful variables (you could probably think of better names based on what these columns are used for):
bool notColumnsABC = (columnname != a && columnname != b && columnname != c);
bool notColumnA2OrBoxIsChecked = ( columnname != A2 || checkbox.checked );
if ( notColumnsABC
&& notColumnA2OrBoxIsChecked )
{
"statement 1"
}
Recently Selenium has launched Selenium 3 and if you are trying to use Firefox latest version then you have to use GeckoDriver:
System.setProperty("webdriver.gecko.driver","G:\\Selenium\\Firefox driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).
I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.
So, as an example:
cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]
The problem you have with the SelectedValue
is not converting into integer. This is the main problem so usinge the following code snippet will help you:
int selectedValue;
bool parseOK = Int32.TryParse(cmb.SelectedValue.ToString(), out selectedValue);
k-a-f's answer works for selecting one column, if selecting multiple column, we can.
DECLARE a BIGINT DEFAULT 1;
DECLARE b BIGINT DEFAULT "name";
SELECT id, name from table into a,b;
Then we just need to check a,b for values.
For deployment better to set up classpath exactly and keep environment clear. Or at *.bat (the same for linux, but with correct variables symbols):
CLASSPATH="c:\lib;d:\temp\test.jar;<long classpath>"
CLASSPATH=%CLASSPATH%;"<another_logical_droup_of_classpath"
java -cp %CLASSPATH% com.test.MainCLass
Or at command line or *.bat (for *.sh too) if classpath id not very long:
java -cp "c:\lib;d:\temp\test.jar;<short classpath>"
If the remote branch already exists then you can (probably) get away with..
git checkout branch_name
and git will automatically set up to track the remote branch with the same name on origin.
public ActionResult Index()
{
return View();
}
public ActionResult Test(string Name)
{
return RedirectToAction("Index");
}
Return View
Directly displays your view
but
Redirect ToAction
Action is performed
DefaultThreadCurrentCulture
and DefaultThreadCurrentUICulture
are present in Framework 4.0 too, but they are Private. Using Reflection you can easily set them. This will affect all threads where CurrentCulture
is not explicitly set (running threads too).
Public Sub SetDefaultThreadCurrentCulture(paCulture As CultureInfo)
Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentCulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentUICulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
End Sub
Turn off "Print Layout" from the "View" menu.
If you are ok using an external plugin to do that you can use Header and Footer Scripts plugin
From the description:
Many WordPress Themes do not have any options to insert header and footer scripts in your site or . It helps you to keep yourself from theme lock. But, sometimes it also causes some pain for many. like where should I insert Google Analytics code (or any other web-analytics codes). This plugin is one stop and lightweight solution for that. With this "Header and Footer Script" plugin will be able to inject HTML tags, JS and CSS codes to and easily.
$pdf->Output()
takes a second parameter $dest
, which accepts a single character. The default, $dest='I'
opens the PDF in the browser.
Use F
to save to file
$pdf->Output('/path/to/file.pdf', 'F')
If you use AND
and OR
, you'll eventually get tripped up by something like this:
$this_one = true;
$that = false;
$truthiness = $this_one and $that;
Want to guess what $truthiness
equals?
If you said false
... bzzzt, sorry, wrong!
$truthiness
above has the value true
. Why? =
has a higher precedence than and
. The addition of parentheses to show the implicit order makes this clearer:
($truthiness = $this_one) and $that
If you used &&
instead of and
in the first code example, it would work as expected and be false
.
As discussed in the comments below, this also works to get the correct value, as parentheses have higher precedence than =
:
$truthiness = ($this_one and $that)
I found that useful, stabbing service function as sinon.stub().returns($q.when({})):
this.myService = {
myFunction: sinon.stub().returns( $q.when( {} ) )
};
this.scope = $rootScope.$new();
this.angularStubs = {
myService: this.myService,
$scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );
controller:
this.someMethod = function(someObj) {
myService.myFunction( someObj ).then( function() {
someObj.loaded = 'bla-bla';
}, function() {
// failure
} );
};
and test
const obj = {
field: 'value'
};
this.ctrl.someMethod( obj );
this.scope.$digest();
expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );
old question but just to mention the solution for MVC5 developers, you can use the Model
property same as in view.
The Model
property in both view and layout is assosiated with the same ViewDataDictionary
object, so you don't have to do any extra work to pass your model to the layout page, and you don't have to declare @model MyModelName
in the layout.
But notice that when you use @Model.XXX
in the layout the intelliSense context menu will not appear because the Model
here is a dynamic object just like ViewBag
.
You can edit Rprofile
in the base
library (in 'C:/Program Files/R.Files/library/base/R'
by default) to include code to be run on startup. Append
######## User code ########
.libPaths('C:/my/dir')
to Rprofile
using any text editor (like Notepad) to cause R to add 'C:/my/dir'
to the list of libraries it knows about.
(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)
You need to add position:relative
to #wrap element.
When you add this, all child elements will be positioned in this element, not browser window.
Mac: cmd + k
Windows: ctrl + k
If the shortcuts do not work for you, the most likely scenario is that either you or an extension you installed has added an open ended ctrl + k / cmd + k chord to another shortcut.
Open ended meaning, the shortcut does not have an explicit when
clause that excludes terminal focus. There are two possible solutions here.
Solution 1:
If you added the shortcut, simply go to your keybindings.json file and add a when
clause that does not include terminal focus. Example:
{
"key": "cmd+k cmd+c",
"command": "someCommandHere",
"when": "editorTextFocus",
}
Solution 2:
Alternatively, you can add the workbench.action.terminal.clear
command to the very bottom of keybindings.json
, ensuring it takes precedence over other shortcuts. It'd be wise to add a comment so you don't forget and later place new chords below it. Example:
// Keep this keybinding at very bottom of file to ensure terminal clearing.
{
"key": "cmd+k",
"command": "workbench.action.terminal.clear",
"when": "terminalFocus",
}
For additional information, check out this GitHub issue.
As told above, To declare global accessible variables you can do it outside functions preceded with the public keyword.
And, since the affectation is NOT PERMITTED outside the procedures, you can, for example, create a sub called InitGlobals that initializes your public variables, then you just call this subroutine at the beginning of your statements
Here is an example of it:
Public Coordinates(3) as Double
Public Heat as double
Public Weight as double
Sub InitGlobals()
Coordinates(1)=10.5
Coordinates(2)=22.54
Coordinates(3)=-100.5
Heat=25.5
Weight=70
End Sub
Sub MyWorkSGoesHere()
Call InitGlobals
'Now you can do your work using your global variables initialized as you wanted them to be.
End Sub
jQuery: Best Way, delegate the actions to jQuery (jQuery = jQuery).
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
return !val;
});
When I am reading numbers from contact book, then it doesn't worked I used
number=number.replaceAll("\\s+", "");
It worked and for url you may use
url=url.replaceAll(" ", "%20");
I use TeXMaker. If you're using Ubuntu, it should be in the apt-get repository. To install texmaker
, run:
sudo apt-get install texmaker
In the newer version of mongodb v2.6.4 try:
grep dbpath /etc/mongod.conf
It will give you something like this:
dbpath=/var/lib/mongodb
And that is where it stores the data.
I didn't want to install a package just for that purpose so I ended up using this in my init.coffee
:
spawn = require('child_process').spawn
atom.commands.add 'atom-text-editor', 'open-terminal', ->
file = atom.workspace.getActiveTextEditor().getPath()
dir = atom.project.getDirectoryForProjectPath(file).path
spawn 'mate-terminal', ["--working-directory=#{dir}"], {
detached: true
}
With that, I could map ctrl-shift-t
to the open-terminal
command and it opens a mate-terminal.
Maybe it's is completely possible with only CSS but I prefer to avoid "float" as much as I can because it interferes with it's parent's height.
If you are using jQuery, you can create a simple `wrapN` plugin that is similar to `wrapAll` except it only wraps "N" elements and then breaks and wraps the next "N" elements using a loop. Then set your wrappers class to `display: block;`.
(function ($) {
$.fn.wrapN = function (wrapper, n, start) {
if (wrapper === undefined || n === undefined) return false;
if (start === undefined) start = 0;
for (var i = start; i < $(this).size(); i += n)
$(this).slice(i, i + n).wrapAll(wrapper);
return this;
};
}(jQuery));
$(document).ready(function () {
$("li").wrapN("<span class='break' />", 3);
});
Here is a JSFiddle of the finished product:
In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.
I had this error and in my case, the problem was that I was using "localhost" in the URL.
I resolved that changing the localhost word for the respective IP, (Windows + R -> cmd -> ipconfig)
then read the IP and write it to the URL replacing the "localhost" word
The flag Xmx
specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms
specifies the initial memory allocation pool.
This means that your JVM will be started with Xms
amount of memory and will be able to use a maximum of Xmx
amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:
java -Xms256m -Xmx2048m
The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.
-Xmx1024k
-Xmx512m
-Xmx8g
The Xms
flag has no default value, and Xmx
typically has a default value of 256 MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError
.
When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can and will use more memory than just the size allocated to the heap. From Oracle's documentation:
Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.
There's a much easier way than recompiling PHP. Just yum install the required mbstring library:
Example: How to install PHP mbstring on CentOS 6.2
yum --enablerepo=remi install php-mbstring
Oh, and don't forget to restart apache afterward.
You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.
For example, add an empty file called .gitkeep
to the folder you want to keep, then in your .gitignore
file write:
# exclude everything
somefolder/*
# exception to the rule
!somefolder/.gitkeep
Commit your .gitignore
and .gitkeep
files and this should resolve your issue.
to open a local file or url with chrome, i used:
const open = require('open'); // npm i open
// open('http://google.com')
open('build_mytest/index.html', {app: "chrome.exe"})
It means that trackDAO
should not be serialized.
Simply using "target=_blank" will respect the user/browser preference of whether to use a tab or a new window, which in most cases is "doing the right thing".
If you specify the dimensions of the new window, some browsers will use this as an indicator that a certain size is needed, in which case a new window will always be used. Stack overflow code example Stack Overflow
The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8_bin which is for comparing characters in binary format.
utf8_general_ci
is somewhat faster than utf8_unicode_ci
, but less accurate (for sorting). The specific language utf8 encoding (such as utf8_swedish_ci
) contain additional language rules that make them the most accurate to sort for those languages. Most of the time I use utf8_unicode_ci
(I prefer accuracy to small performance improvements), unless I have a good reason to prefer a specific language.
You can read more on specific unicode character sets on the MySQL manual - http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html
As of 7.0.0, most of the above solutions no longer work.
BrowserWindow.setMenu()
has been replaced by Menu.setApplicationMenu()
, which now changes the menu on all windows. setMenu()
, removeMenu()
no longer do anything, Which by the way are still mentioned in the docs.
setAutoHideMenuBar()
still works, but could be a nuisance if you planned to use Alt as a hotkey modifier. Once menu is visible you have to click away from window (loose focus) to hide menu again.
If your application has more than one window, you can't set/remove menus separately on each window. The only way to remove a menu is to use the frameless window approach. That happens to be what I want in my current application, but not a good solution in all cases.
I am using:
String.prototype.format = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
usage: "Hello {0}".format("World");
I found it at Equivalent of String.format in JQuery
UPDATED:
In ES6/ES2015 you can use string templating for instance
'use strict';
let firstName = 'John',
lastName = 'Smith';
console.log(`Full Name is ${firstName} ${lastName}`);
// or
console.log(`Full Name is ${firstName + ' ' + lastName}');
For Ubuntu,
First, run this command :-
sudo a2enmod rewrite
Then, edit the file /etc/apache2/sites-available/000-default.conf
using nano or vim using this command :-
sudo nano /etc/apache2/sites-available/000-default.conf
Then in the 000-default.conf
file, add this after the line DocumentRoot /var/www/html
. If your root html directory is something other, then write that :-
<Directory "/var/www/html">
AllowOverride All
</Directory>
After doing everything, restart apache using the command sudo service apache2 restart
If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.
Otherwise, you will need to create a UDF.
Here's a sample trigger solution:
CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
FOR EACH ROW BEGIN
/* START THE WRITING OF THE EMAIL FILE HERE*/
SELECT concat("To: ",NEW.To),
concat("From: ",NEW.From),
concat("Subject: ",NEW.Subject),
NEW.Body
INTO OUTFILE
"C:\\inetpub\\mailroot\\pickup\\mail.txt"
FIELDS TERMINATED by '\r\n' ESCAPED BY '';
END;
To markup the message body you will need something like this...
CREATE FUNCTION `HTMLBody`(Msg varchar(8192))
RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
BEGIN
declare tmpMsg varchar(17408);
set tmpMsg = cast(concat(
'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
'MIME-Version: 1.0','\r\n',
'Content-Type: multipart/alternative;','\r\n',
' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
'Content-Class: urn:content-classes:message','\r\n',
'Importance: normal','\r\n',
'Priority: normal','\r\n','','\r\n','','\r\n',
'This is a multi-part message in MIME format.','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/plain;','\r\n',
' charset=\"iso-8859-1\"','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
Msg,
'\r\n','','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/html','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
Msg,
'\r\n','------=_NextPart_000_0000_01CA4B3F.8C263EE0--'
) as char);
RETURN tmpMsg;
END ;
Here is yet another explanation of how the factorial calculation using recursion works.
Let's modify source code slightly:
int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
Here is calculation of 3! in details:
Source: RECURSION (Java, C++) | Algorithms and Data Structures
If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this)
.
class A {
public function create1() {
$class = get_class($this);
return new $class();
}
public function create2() {
return new static();
}
}
class B extends A {
}
$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));
The results:
string(1) "B"
string(1) "B"
I used the code below to add a certain time interval to the current time.
int interval = 30;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar time = Calendar.getInstance();
Log.i("Time ", String.valueOf(df.format(time.getTime())));
time.add(Calendar.MINUTE, interval);
Log.i("New Time ", String.valueOf(df.format(time.getTime())));
There is also proc.time()
You can use in the same way as Sys.time
but it gives you a similar result to system.time
.
ptm <- proc.time()
#your function here
proc.time() - ptm
the main difference between using
system.time({ #your function here })
is that the proc.time()
method still does execute your function instead of just measuring the time...
and by the way, I like to use system.time
with {}
inside so you can put a set of things...
angular gives a very sweet function called slice.. using this you can achieve what you are looking for. e.g. ng-repeat="ab in abc.slice(startIndex,endIndex)"
this demo :http://jsfiddle.net/sahilosheal/LurcV/39/ will help you out and tell you how to use this "making life easy" function. :)
html:
<div class="div" ng-app >
<div ng-controller="Main">
<h2>sliced list(conditional NG-repeat)</h2>
<ul ng-controller="ctrlParent">
<li ng-repeat="ab in abc.slice(2,5)"><span>{{$index+1}} :: {{ab.name}} </span></li>
</ul>
<h2>unsliced list( no conditional NG-repeat)</h2>
<ul ng-controller="ctrlParent">
<li ng-repeat="ab in abc"><span>{{$index+1}} :: {{ab.name}} </span></li>
</ul>
</div>
CSS:
ul
{
list-style: none;
}
.div{
padding:25px;
}
li{
background:#d4d4d4;
color:#052349;
}
ng-JS:
function ctrlParent ($scope) {
$scope.abc = [
{ "name": "What we do", url: "/Home/AboutUs" },
{ "name": "Photo Gallery", url: "/home/gallery" },
{ "name": "What we work", url: "/Home/AboutUs" },
{ "name": "Photo play", url: "/home/gallery" },
{ "name": "Where", url: "/Home/AboutUs" },
{ "name": "playground", url: "/home/gallery" },
{ "name": "What we score", url: "/Home/AboutUs" },
{ "name": "awesome", url: "/home/gallery" },
{ "name": "oscar", url: "/Home/AboutUs" },
{ "name": "american hustle", url: "/home/gallery" }
];
}
function Main($scope){
$scope.items = [{sort: 1, name: 'First'},
{sort: 2, name: 'Second'},
{sort: 3, name: 'Third'},
{sort: 4, name:'Last'}];
}
I got the same error since Application pool was stopped in IIS. After starting the App Pool, the issue was resolved.
By default, git will update execute file permissions if you change them. It will not change or track any other permissions.
If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.
Look into your project, in the .git
folder for the config
file and you should see something like this:
[core]
filemode = false
You can either change it to true
in your favorite text editor, or run:
git config core.filemode true
Then, you should be able to commit normally your files. It will only commit the permission changes.
You have to select and send the form data as well:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serialize
method, which encodes the data from the form fields into a data-string to be sent to the server.
Install ejs if it is not.
npm install ejs
Then after just paste below two lines in your main file. (like app.js, main.js)
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
data d is in row 0 and column 3 for value d :
DataTable table;
String d = (String)table.Rows[0][3];
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
for springboot 2.1.7 working with url seems not to work. change with jdbcUrl instead.
In properties:
security:
datasource:
jdbcUrl: jdbc:mysql://ip:3306/security
username: user
password: pass
In java:
@ConfigurationProperties(prefix = "security.datasource")
@Bean("dataSource")
@Primary
public DataSource dataSource(){
return DataSourceBuilder
.create()
.build();
}
Installing webpack with -g option installs webpack in a folder in
C:\Users\<.profileusername.>\AppData\Roaming\npm\node_modules
same with webpack-cli and webpack-dev-server
Outside the global node_modules a link is created for webpack to be run from commandline
C:\Users\<.profileusername.>\AppData\Roaming\npm
to make this work locally, I did the following
Problem with this approach is you'd have to maintain links for each project you have. Theres no other way since you are using the command line editor to run webpack command when installing with a -g option.
So if you had proj1, proj2 and proj3 all with their local node_modules and local webpack installed( not using -g when installing), then you'd have to create non-generic link names instead of just webpack.
example here would be to create webpack_proj1.cmd, webpack_proj2.cmd and webpack_proj3.cmd and in each cmd follow point 2 and 3 above
PS: dont forget to update your package.json with these changes or else you'll get errors as it won't find webpack command
hsThumbList.setLayoutParams(new LayoutParams(100, 400));
Most likely there is an error somewhere in the get_profile() call. In your view, before you return the request object, put this line:
request.user.get_profile()
It should raise the error, and give you a more detailed traceback, which you can then use to further debug.
In SQL*Plus, you can do something very similar
SQL> variable v_emp_id number;
SQL> select 1234 into :v_emp_id from dual;
1234
----------
1234
SQL> select *
2 from emp
3 where empno = :v_emp_id;
no rows selected
In SQL Developer, if you run a statement that has any number of bind variables (prefixed with a colon), you'll be prompted to enter values. As Alex points out, you can also do something similar using the "Run Script" function (F5) with the alternate EXEC syntax Alex suggests does.
variable v_count number;
variable v_emp_id number;
exec :v_emp_id := 1234;
exec select count(1) into :v_count from emp;
select *
from emp
where empno = :v_emp_id
exec print :v_count;
This Status Code 500 is an Internal Server Error. This code indicates that a part of the server (for example, a CGI program) has crashed or encountered a configuration error.
i think the problem does'nt lie on your side, but rather on the side of the Http server. the resources you used to access may have been moved or get corrupted, or its configuration just may have altered or spoiled
Basically http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
UPDATE 3 (Sep 24 '17)
Check VBA-JSON-parser on GitHub for the latest version and examples. Import JSON.bas module into the VBA project for JSON processing.
UPDATE 2 (Oct 1 '16)
However if you do want to parse JSON on 64-bit Office with ScriptControl
, then this answer may help you to get ScriptControl
to work on 64-bit.
UPDATE (Oct 26 '15)
Note that a ScriptControl
-based approachs makes the system vulnerable in some cases, since they allows a direct access to the drives (and other stuff) for the malicious JS code via ActiveX's. Let's suppose you are parsing web server response JSON, like JsonString = "{a:(function(){(new ActiveXObject('Scripting.FileSystemObject')).CreateTextFile('C:\\Test.txt')})()}"
. After evaluating it you'll find new created file C:\Test.txt
. So JSON parsing with ScriptControl
ActiveX is not a good idea.
Trying to avoid that, I've created JSON parser based on RegEx's. Objects {}
are represented by dictionaries, that makes possible to use dictionary's properties and methods: .Count
, .Exists()
, .Item()
, .Items
, .Keys
. Arrays []
are the conventional zero-based VB arrays, so UBound()
shows the number of elements. Here is the code with some usage examples:
Option Explicit
Sub JsonTest()
Dim strJsonString As String
Dim varJson As Variant
Dim strState As String
Dim varItem As Variant
' parse JSON string to object
' root element can be the object {} or the array []
strJsonString = "{""a"":[{}, 0, ""value"", [{""stuff"":""content""}]], b:null}"
ParseJson strJsonString, varJson, strState
' checking the structure step by step
Select Case False ' if any of the checks is False, the sequence is interrupted
Case IsObject(varJson) ' if root JSON element is object {},
Case varJson.Exists("a") ' having property a,
Case IsArray(varJson("a")) ' which is array,
Case UBound(varJson("a")) >= 3 ' having not less than 4 elements,
Case IsArray(varJson("a")(3)) ' where forth element is array,
Case UBound(varJson("a")(3)) = 0 ' having the only element,
Case IsObject(varJson("a")(3)(0)) ' which is object,
Case varJson("a")(3)(0).Exists("stuff") ' having property stuff,
Case Else
MsgBox "Check the structure step by step" & vbCrLf & varJson("a")(3)(0)("stuff") ' then show the value of the last one property.
End Select
' direct access to the property if sure of structure
MsgBox "Direct access to the property" & vbCrLf & varJson.Item("a")(3)(0).Item("stuff") ' content
' traversing each element in array
For Each varItem In varJson("a")
' show the structure of the element
MsgBox "The structure of the element:" & vbCrLf & BeautifyJson(varItem)
Next
' show the full structure starting from root element
MsgBox "The full structure starting from root element:" & vbCrLf & BeautifyJson(varJson)
End Sub
Sub BeautifyTest()
' put sourse JSON string to "desktop\source.json" file
' processed JSON will be saved to "desktop\result.json" file
Dim strDesktop As String
Dim strJsonString As String
Dim varJson As Variant
Dim strState As String
Dim strResult As String
Dim lngIndent As Long
strDesktop = CreateObject("WScript.Shell").SpecialFolders.Item("Desktop")
strJsonString = ReadTextFile(strDesktop & "\source.json", -2)
ParseJson strJsonString, varJson, strState
If strState <> "Error" Then
strResult = BeautifyJson(varJson)
WriteTextFile strResult, strDesktop & "\result.json", -1
End If
CreateObject("WScript.Shell").PopUp strState, 1, , 64
End Sub
Sub ParseJson(ByVal strContent As String, varJson As Variant, strState As String)
' strContent - source JSON string
' varJson - created object or array to be returned as result
' strState - Object|Array|Error depending on processing to be returned as state
Dim objTokens As Object
Dim objRegEx As Object
Dim bMatched As Boolean
Set objTokens = CreateObject("Scripting.Dictionary")
Set objRegEx = CreateObject("VBScript.RegExp")
With objRegEx
' specification http://www.json.org/
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = """(?:\\""|[^""])*""(?=\s*(?:,|\:|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "str"
.Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)e(?:[+-])?\d+(?=\s*(?:,|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "num"
.Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)(?=\s*(?:,|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "num"
.Pattern = "\b(?:true|false|null)(?=\s*(?:,|\]|\}))"
Tokenize objTokens, objRegEx, strContent, bMatched, "cst"
.Pattern = "\b[A-Za-z_]\w*(?=\s*\:)" ' unspecified name without quotes
Tokenize objTokens, objRegEx, strContent, bMatched, "nam"
.Pattern = "\s"
strContent = .Replace(strContent, "")
.MultiLine = False
Do
bMatched = False
.Pattern = "<\d+(?:str|nam)>\:<\d+(?:str|num|obj|arr|cst)>"
Tokenize objTokens, objRegEx, strContent, bMatched, "prp"
.Pattern = "\{(?:<\d+prp>(?:,<\d+prp>)*)?\}"
Tokenize objTokens, objRegEx, strContent, bMatched, "obj"
.Pattern = "\[(?:<\d+(?:str|num|obj|arr|cst)>(?:,<\d+(?:str|num|obj|arr|cst)>)*)?\]"
Tokenize objTokens, objRegEx, strContent, bMatched, "arr"
Loop While bMatched
.Pattern = "^<\d+(?:obj|arr)>$" ' unspecified top level array
If Not (.Test(strContent) And objTokens.Exists(strContent)) Then
varJson = Null
strState = "Error"
Else
Retrieve objTokens, objRegEx, strContent, varJson
strState = IIf(IsObject(varJson), "Object", "Array")
End If
End With
End Sub
Sub Tokenize(objTokens, objRegEx, strContent, bMatched, strType)
Dim strKey As String
Dim strRes As String
Dim lngCopyIndex As Long
Dim objMatch As Object
strRes = ""
lngCopyIndex = 1
With objRegEx
For Each objMatch In .Execute(strContent)
strKey = "<" & objTokens.Count & strType & ">"
bMatched = True
With objMatch
objTokens(strKey) = .Value
strRes = strRes & Mid(strContent, lngCopyIndex, .FirstIndex - lngCopyIndex + 1) & strKey
lngCopyIndex = .FirstIndex + .Length + 1
End With
Next
strContent = strRes & Mid(strContent, lngCopyIndex, Len(strContent) - lngCopyIndex + 1)
End With
End Sub
Sub Retrieve(objTokens, objRegEx, strTokenKey, varTransfer)
Dim strContent As String
Dim strType As String
Dim objMatches As Object
Dim objMatch As Object
Dim strName As String
Dim varValue As Variant
Dim objArrayElts As Object
strType = Left(Right(strTokenKey, 4), 3)
strContent = objTokens(strTokenKey)
With objRegEx
.Global = True
Select Case strType
Case "obj"
.Pattern = "<\d+\w{3}>"
Set objMatches = .Execute(strContent)
Set varTransfer = CreateObject("Scripting.Dictionary")
For Each objMatch In objMatches
Retrieve objTokens, objRegEx, objMatch.Value, varTransfer
Next
Case "prp"
.Pattern = "<\d+\w{3}>"
Set objMatches = .Execute(strContent)
Retrieve objTokens, objRegEx, objMatches(0).Value, strName
Retrieve objTokens, objRegEx, objMatches(1).Value, varValue
If IsObject(varValue) Then
Set varTransfer(strName) = varValue
Else
varTransfer(strName) = varValue
End If
Case "arr"
.Pattern = "<\d+\w{3}>"
Set objMatches = .Execute(strContent)
Set objArrayElts = CreateObject("Scripting.Dictionary")
For Each objMatch In objMatches
Retrieve objTokens, objRegEx, objMatch.Value, varValue
If IsObject(varValue) Then
Set objArrayElts(objArrayElts.Count) = varValue
Else
objArrayElts(objArrayElts.Count) = varValue
End If
varTransfer = objArrayElts.Items
Next
Case "nam"
varTransfer = strContent
Case "str"
varTransfer = Mid(strContent, 2, Len(strContent) - 2)
varTransfer = Replace(varTransfer, "\""", """")
varTransfer = Replace(varTransfer, "\\", "\")
varTransfer = Replace(varTransfer, "\/", "/")
varTransfer = Replace(varTransfer, "\b", Chr(8))
varTransfer = Replace(varTransfer, "\f", Chr(12))
varTransfer = Replace(varTransfer, "\n", vbLf)
varTransfer = Replace(varTransfer, "\r", vbCr)
varTransfer = Replace(varTransfer, "\t", vbTab)
.Global = False
.Pattern = "\\u[0-9a-fA-F]{4}"
Do While .Test(varTransfer)
varTransfer = .Replace(varTransfer, ChrW(("&H" & Right(.Execute(varTransfer)(0).Value, 4)) * 1))
Loop
Case "num"
varTransfer = Evaluate(strContent)
Case "cst"
Select Case LCase(strContent)
Case "true"
varTransfer = True
Case "false"
varTransfer = False
Case "null"
varTransfer = Null
End Select
End Select
End With
End Sub
Function BeautifyJson(varJson As Variant) As String
Dim strResult As String
Dim lngIndent As Long
BeautifyJson = ""
lngIndent = 0
BeautyTraverse BeautifyJson, lngIndent, varJson, vbTab, 1
End Function
Sub BeautyTraverse(strResult As String, lngIndent As Long, varElement As Variant, strIndent As String, lngStep As Long)
Dim arrKeys() As Variant
Dim lngIndex As Long
Dim strTemp As String
Select Case VarType(varElement)
Case vbObject
If varElement.Count = 0 Then
strResult = strResult & "{}"
Else
strResult = strResult & "{" & vbCrLf
lngIndent = lngIndent + lngStep
arrKeys = varElement.Keys
For lngIndex = 0 To UBound(arrKeys)
strResult = strResult & String(lngIndent, strIndent) & """" & arrKeys(lngIndex) & """" & ": "
BeautyTraverse strResult, lngIndent, varElement(arrKeys(lngIndex)), strIndent, lngStep
If Not (lngIndex = UBound(arrKeys)) Then strResult = strResult & ","
strResult = strResult & vbCrLf
Next
lngIndent = lngIndent - lngStep
strResult = strResult & String(lngIndent, strIndent) & "}"
End If
Case Is >= vbArray
If UBound(varElement) = -1 Then
strResult = strResult & "[]"
Else
strResult = strResult & "[" & vbCrLf
lngIndent = lngIndent + lngStep
For lngIndex = 0 To UBound(varElement)
strResult = strResult & String(lngIndent, strIndent)
BeautyTraverse strResult, lngIndent, varElement(lngIndex), strIndent, lngStep
If Not (lngIndex = UBound(varElement)) Then strResult = strResult & ","
strResult = strResult & vbCrLf
Next
lngIndent = lngIndent - lngStep
strResult = strResult & String(lngIndent, strIndent) & "]"
End If
Case vbInteger, vbLong, vbSingle, vbDouble
strResult = strResult & varElement
Case vbNull
strResult = strResult & "Null"
Case vbBoolean
strResult = strResult & IIf(varElement, "True", "False")
Case Else
strTemp = Replace(varElement, "\""", """")
strTemp = Replace(strTemp, "\", "\\")
strTemp = Replace(strTemp, "/", "\/")
strTemp = Replace(strTemp, Chr(8), "\b")
strTemp = Replace(strTemp, Chr(12), "\f")
strTemp = Replace(strTemp, vbLf, "\n")
strTemp = Replace(strTemp, vbCr, "\r")
strTemp = Replace(strTemp, vbTab, "\t")
strResult = strResult & """" & strTemp & """"
End Select
End Sub
Function ReadTextFile(strPath As String, lngFormat As Long) As String
' lngFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 1, False, lngFormat)
ReadTextFile = ""
If Not .AtEndOfStream Then ReadTextFile = .ReadAll
.Close
End With
End Function
Sub WriteTextFile(strContent As String, strPath As String, lngFormat As Long)
With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 2, True, lngFormat)
.Write (strContent)
.Close
End With
End Sub
One more opportunity of this JSON RegEx parser is that it works on 64-bit Office, where ScriptControl isn't available.
INITIAL (May 27 '15)
Here is one more method to parse JSON in VBA, based on ScriptControl
ActiveX, without external libraries:
Sub JsonTest()
Dim Dict, Temp, Text, Keys, Items
' Converting JSON string to appropriate nested dictionaries structure
' Dictionaries have numeric keys for JSON Arrays, and string keys for JSON Objects
' Returns Nothing in case of any JSON syntax issues
Set Dict = GetJsonDict("{a:[[{stuff:'result'}]], b:''}")
' You can use For Each ... Next and For ... Next loops through keys and items
Keys = Dict.Keys
Items = Dict.Items
' Referring directly to the necessary property if sure, without any checks
MsgBox Dict("a")(0)(0)("stuff")
' Auxiliary DrillDown() function
' Drilling down the structure, sequentially checking if each level exists
Select Case False
Case DrillDown(Dict, "a", Temp, "")
Case DrillDown(Temp, 0, Temp, "")
Case DrillDown(Temp, 0, Temp, "")
Case DrillDown(Temp, "stuff", "", Text)
Case Else
' Structure is consistent, requested value found
MsgBox Text
End Select
End Sub
Function GetJsonDict(JsonString As String)
With CreateObject("ScriptControl")
.Language = "JScript"
.ExecuteStatement "function gettype(sample) {return {}.toString.call(sample).slice(8, -1)}"
.ExecuteStatement "function evaljson(json, er) {try {var sample = eval('(' + json + ')'); var type = gettype(sample); if(type != 'Array' && type != 'Object') {return er;} else {return getdict(sample);}} catch(e) {return er;}}"
.ExecuteStatement "function getdict(sample) {var type = gettype(sample); if(type != 'Array' && type != 'Object') return sample; var dict = new ActiveXObject('Scripting.Dictionary'); if(type == 'Array') {for(var key = 0; key < sample.length; key++) {dict.add(key, getdict(sample[key]));}} else {for(var key in sample) {dict.add(key, getdict(sample[key]));}} return dict;}"
Set GetJsonDict = .Run("evaljson", JsonString, Nothing)
End With
End Function
Function DrillDown(Source, Prop, Target, Value)
Select Case False
Case TypeName(Source) = "Dictionary"
Case Source.exists(Prop)
Case Else
Select Case True
Case TypeName(Source(Prop)) = "Dictionary"
Set Target = Source(Prop)
Value = Empty
Case IsObject(Source(Prop))
Set Value = Source(Prop)
Set Target = Nothing
Case Else
Value = Source(Prop)
Set Target = Nothing
End Select
DrillDown = True
Exit Function
End Select
DrillDown = False
End Function
ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)
EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/
var pause_menu = {
pause_button : { someProperty : "prop1", someOther : "prop2" },
resume_button : { resumeProp : "prop", resumeProp2 : false },
quit_button : false
};
then:
pause_menu.pause_button.someProperty //evaluates to "prop1"
etc etc.
If you have to log all args or your method have one argument, you can simply use getArgs like described in previous answers.
If you have to log a specific arg, you can annoted it and then recover its value like this :
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Data {
String methodName() default "";
}
@Aspect
public class YourAspect {
@Around("...")
public Object around(ProceedingJoinPoint point) throws Throwable {
Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
Object[] args = point.getArgs();
StringBuilder data = new StringBuilder();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
if (!(paramAnnotation instanceof Data)) {
continue;
}
Data dataAnnotation = (Data) paramAnnotation;
if (dataAnnotation.methodName().length() > 0) {
Object obj = args[argIndex];
Method dataMethod = obj.getClass().getMethod(dataAnnotation.methodName());
data.append(dataMethod.invoke(obj));
continue;
}
data.append(args[argIndex]);
}
}
}
}
Examples of use :
public void doSomething(String someValue, @Data String someData, String otherValue) {
// Apsect will log value of someData param
}
public void doSomething(String someValue, @Data(methodName = "id") SomeObject someData, String otherValue) {
// Apsect will log returned value of someData.id() method
}
Try installing this, it's a known workaround for enabling the C++ compiler for Python 2.7.
In my experience, when pip does not find vcvarsall.bat compiler, all I do is opening a Visual Studio console as it set the path variables to call vcvarsall.bat directly and then I run pip on this command line.
Avoid line break
<meta http-equiv="Content-Security-Policy" content="
default-src 'FOO';
script-src 'FOO';
style-src 'FOO';
font-src 'FOO';">
Works with Firefox 45.0.1
<meta http-equiv="Content-Security-Policy" content=" default-src 'FOO'; script-src 'FOO'; style-src 'FOO'; font-src 'FOO';">
One example of when I found it convenient was when trying to embed binary data in XML. Some of the binary data was being misinterpreted by the SAX parser because that data could be literally anything, including XML special characters. Base64 encoding the data on the transmitting end and decoding it on the receiving end fixed that problem.
I am able to have my emulator to run my app with Google Map V.2 (with Google Play Service V.4). I followed steps that others suggested with some failures, however I learned from it and somehow make it work. This is how:
First of all: You must have coded your map app. correctly with all the appropriate permissions setup in your metafile XML, and have Google Play Services APK part of your app. To verify this is true, you must run your app on REAL device and know it works with its map there. Then you can proceed to process your emulator as shown below.
Create a new emulator, or use your existing emulator with specs:
Run you emulator (your target emulator must be running!)
Download the following APKs (available via dropbox per 4/2/2013) to your local directory (scan for virus!):
com.android.vending.apk, (Google Play Store, v.3.10.9)
com.google.android.gms.apk, (Google Play Service, v.2.0.12)
Install these two APK into your running (target) emulator with ADB command:
DOS/Console Prompt> adb -e install [path-to-APK-file]
NOTE: Possibly, you have had these APKs installed in your emulator during this trial-error, and need to re-install for some reason. You must uninstall them first by: adb -e uninstall (com.google.android.gms or com.android.vending)
Here, it is where things could get tricky. You think you were done, but when you open your app with Map again, but all you get is an error saying something in the form of: "Google Play services out of date. Requires 2012100 but found 2010110", and may see a button to "Update" Google Play. If this is the case, do NOT attempt to click the update button since it won't do anything. I got this error too, and I resolved it by both of these additional steps:
That's it, it works now nicely.
If you use NDBCLUSTER as storage engine, you should increase DataMemory
and IndexMemory
.
Try with this:
var result = new List<object>();
foreach (var test in model.ToList()) {
result.Add(new {Id = test.IdSoc,Nom = test.Nom});
}
If you want to add different border on different sides, may be add a subview with the specific style is a way easy to come up with.
you can find default port configuration at start your app
yourapp/scripts/start.js
scroll down and change the port to whatever you want
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 4000;
hope this may help you ;)
You should just use something like:
YourModel.update_all(
ActiveRecord::Base.send(:sanitize_sql_for_assignment, {:value => "'wow'"})
)
That would do the trick. Using the ActiveRecord::Base#send method to invoke the sanitize_sql_for_assignment makes the Ruby (at least the 1.8.7 version) skip the fact that the sanitize_sql_for_assignment is actually a protected method.
All angular services are singletons:
Docs (see Services as singletons): https://docs.angularjs.org/guide/services
Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector.
Basically the difference between the service and factory is as follows:
app.service('myService', function() {
// service is just a constructor function
// that will be called with 'new'
this.sayHello = function(name) {
return "Hi " + name + "!";
};
});
app.factory('myFactory', function() {
// factory returns an object
// you can run some code before
return {
sayHello : function(name) {
return "Hi " + name + "!";
}
}
});
Check out this presentation about $provide: http://slides.wesalvaro.com/20121113/#/
Those slides were used in one of the AngularJs meetups: http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html
First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.
To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar()
method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.
If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:
I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.
There is no ENDIF in SQL.
The statement directly followig an IF is execute only when the if expression is true.
The BEGIN ... END construct is separate from the IF. It binds multiple statements together as a block that can be treated as if they were a single statement. Hence BEGIN ... END can be used directly after an IF and thus the whole block of code in the BEGIN .... END sequence will be either executed or skipped.
In your case I suspect the "(more code)" following FROM XXXXX is where your problem is.
You have not joined TableD, merely selected the TableD FIELD (dID
) from one of the tables.
I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)
I would suggest a very simple solution.
Take the View reference variable and set view in OnCreateView. Check if view already exists in this variable, then return same view.
private View fragmentView;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (fragmentView != null) {
return fragmentView;
}
View view = inflater.inflate(R.layout.yourfragment, container, false);
fragmentView = view;
return view;
}
Timedelta objects have read-only instance attributes .days
, .seconds
, and .microseconds
.
We can take a simple example.
Consider a table named TableA
with the following values:
id firstname lastname Mark
-------------------------------------------------------------------
1 arun prasanth 40
2 ann antony 45
3 sruthy abc 41
6 new abc 47
1 arun prasanth 45
1 arun prasanth 49
2 ann antony 49
GROUP BY
The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.
In more simple words GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
We can apply GROUP BY
in our table:
select SUM(Mark)marksum,firstname from TableA
group by id,firstName
Results:
marksum firstname
----------------
94 ann
134 arun
47 new
41 sruthy
In our real table we have 7 rows and when we apply GROUP BY id
, the server group the results based on id
:
In simple words:
here
GROUP BY
normally reduces the number of rows returned by rolling them up and calculatingSum()
for each row.
PARTITION BY
Before going to PARTITION BY, let us look at the OVER
clause:
According to the MSDN definition:
OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.
PARTITION BY will not reduce the number of rows returned.
We can apply PARTITION BY in our example table:
SELECT SUM(Mark) OVER (PARTITION BY id) AS marksum, firstname FROM TableA
Result:
marksum firstname
-------------------
134 arun
134 arun
134 arun
94 ann
94 ann
41 sruthy
47 new
Look at the results - it will partition the rows and returns all rows, unlike GROUP BY.
Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:
Make sure you study this thread, as overriding a signed tag is not as easy:
git tag
man page seriously advised against a simple git tag -f B
to replace a tag name "A
"don't try to recreate a signed tag with git tag -f
(see the thread extract below)
(it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):
Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:
- in the tag object itself as a contents of 'tag' header (you can see it in output of "
git show <tag>
" and also in output of "git cat-file -p <tag>
", where<tag>
is heavyweight tag, e.g.v1.6.3
ingit.git
repository),- and also is default name of tag reference (reference in "
refs/tags/*
" namespace) pointing to a tag object.
Note that the tag reference (appropriate reference in the "refs/tags/*
" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3
', other can have in 'refs/tags/sub/v0.1.3
' for example.So when you create signed tag '
A
', you have the following situation (assuming that it points at some commit)
35805ce <--- 5b7b4ead <=== refs/tags/A
(commit) tag A
(tag)
Please also note that "
git tag -f A A
" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.If you do "
git tag -f -s A A
": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of-s
/-a
/-m
options is used to force annotated tag (creation of tag object), you will get the following situation
35805ce <--- 5b7b4ea <--- ada8ddc <=== refs/tags/A
(commit) tag A tag A
(tag) (tag)
Note also that "
git show A
" would show the whole chain down to the non-tag object...
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
This of it in terms of downloading a webpage:
Your program runs on a cellphone and is requesting the webpage http://www.google.com. If you write your program synchronously, the function you write to download the data will be running continuously until all the data is download. This means your UI will not refresh and will basically appear frozen. If you write your program using callbacks, you request the data and say "execute this function when you've finished." This allows the UI to still allow user interaction while the file is downloading. Once the webpage has finished downloading, your result function (callback) is called and you can handle the data.
Basically, it allows you to request something and continue executing while waiting for the result. Once the result comes back to you via a callback function, you can pick up the operation where it left off.
>>> '\x9c'.decode('cp1252')
u'\u0153'
>>> print '\x9c'.decode('cp1252')
œ
(In descending order of generality)
Walk: a sequence of edges where the end of one edge marks the beginning of the next edge
Trail: a walk which does not repeat any edges. All trails are walks.
Path: a walk where each vertex is traversed at most once. (paths used to refer to open walks, the definition has changed now) The property of traversing vertices at most once means that edges are also crossed at most once, hence all paths are trails.
Hamiltonian path: visits every vertex in the graph (exactly once, because it is a path)
Eulerian trail: visits every edge in the graph exactly once (because it is a trail, vertices may well be crossed more than once.)
The solution can be optimized in following way: Firstly, use a private inner class as the scope for the fields is to be the enclosing class TestPeople so as the implementation of class People won't get exposed to outer world. This can be understood in terms of creating an APIthat expects a sorted list of people Secondly, using the Lamba expression(java 8) which reduces the code, hence development effort
Hence code would be as below:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TestPeople {
public static void main(String[] args) {
ArrayList<People> peps = new ArrayList<>();// Be specific, to avoid
// classCast Exception
TestPeople test = new TestPeople();
peps.add(test.new People(123, "M", 14.25));
peps.add(test.new People(234, "M", 6.21));
peps.add(test.new People(362, "F", 9.23));
peps.add(test.new People(111, "M", 65.99));
peps.add(test.new People(535, "F", 9.23));
/*
* Collections.sort(peps);
*
* for (int i = 0; i < peps.size(); i++){
* System.out.println(peps.get(i)); }
*/
// The above code can be replaced by followin:
peps.sort((People p1, People p2) -> p1.getid() - p2.getid());
peps.forEach((p) -> System.out.println(" " + p.toString()));
}
private class People {
private int id;
@Override
public String toString() {
return "People [id=" + id + ", info=" + info + ", price=" + price + "]";
}
private String info;
private double price;
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) {
this.info = info;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
}
}
To validate Phone number using regular expression in java script.
In india phone is 10 digit and starting digits are 6,7,8 and 9.
Javascript and HTML code:
function validate()
{
var text = document.getElementById("pno").value;
var regx = /^[6-9]\d{9}$/ ;
if(regx.test(text))
alert("valid");
else
alert("invalid");
}
_x000D_
<html>
<head>
<title>JS compiler - knox97</title>
</head>
<body>
<input id="pno" placeholder="phonenumber" type="tel" maxlength="10" >
</br></br>
<button onclick="validate()" type="button">submit</button>
</body>
</html>
_x000D_
MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy
https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Returns the set of elements in the first sequence which aren't
/// in the second sequence, according to a given key selector.
/// </summary>
/// <remarks>
/// This is a set operation; if multiple elements in <paramref name="first"/> have
/// equal keys, only the first such element is returned.
/// This operator uses deferred execution and streams the results, although
/// a set of keys from <paramref name="second"/> is immediately selected and retained.
/// </remarks>
/// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="first">The sequence of potentially included elements.</param>
/// <param name="second">The sequence of elements whose keys may prevent elements in
/// <paramref name="first"/> from being returned.</param>
/// <param name="keySelector">The mapping from source element to key.</param>
/// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
/// any element in <paramref name="second"/>.</returns>
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector)
{
return ExceptBy(first, second, keySelector, null);
}
/// <summary>
/// Returns the set of elements in the first sequence which aren't
/// in the second sequence, according to a given key selector.
/// </summary>
/// <remarks>
/// This is a set operation; if multiple elements in <paramref name="first"/> have
/// equal keys, only the first such element is returned.
/// This operator uses deferred execution and streams the results, although
/// a set of keys from <paramref name="second"/> is immediately selected and retained.
/// </remarks>
/// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="first">The sequence of potentially included elements.</param>
/// <param name="second">The sequence of elements whose keys may prevent elements in
/// <paramref name="first"/> from being returned.</param>
/// <param name="keySelector">The mapping from source element to key.</param>
/// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
/// If null, the default equality comparer for <c>TSource</c> is used.</param>
/// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
/// any element in <paramref name="second"/>.</returns>
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> keyComparer)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (keySelector == null) throw new ArgumentNullException("keySelector");
return ExceptByImpl(first, second, keySelector, keyComparer);
}
private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> keyComparer)
{
var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
foreach (var element in first)
{
var key = keySelector(element);
if (keys.Contains(key))
{
continue;
}
yield return element;
keys.Add(key);
}
}
}
}
Depending on your version, use a table valued parameter in 2008, or some approach described here:
Many changes you can make very easily and visually in the table editor in SQL Server Management Studio actually require SSMS to drop the table in the background and re-create it from scratch. Even simple things like reordering the columns cannot be expressed in standard SQL DDL statement - all SSMS can do is drop and recreate the table.
This operation can be a) very time consuming on a large table, or b) might even fail for various reasons (like FK constraints and stuff). Therefore, SSMS in SQL Server 2008 introduced that new option the other answers have already identified.
It might seem counter-intuitive at first to prevent such changes - and it's certainly a nuisance on a dev server. But on a production server, this option and its default value of preventing such changes becomes a potential life-saver!
For example, if you want to make the color of "text" green, just type:
<font color='green'>text</font>
Not sure that it will be applicable solution for you. But the only way for monitoring tomcat memory settings as well as number of connections etc. that actually works for us is Lambda Probe.
It shows most of informations that we need for Tomcat tunning. We tested it with Tomcat 5.5 and 6.0 and it works fine despite beta status and date of last update in end of 2006.
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
I make a static function. Its more efficient i think.
public static String file2Base64(String filePath) {
FileInputStream fis = null;
String base64String = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024 * 100];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
return base64String;
}
Simple and easier!
This seems to solve the problem, using the [index: TYPE]
array access type, cheers.
interface ScriptNodeList extends NodeList {
[index: number]: HTMLScriptElement;
}
var script = ( <ScriptNodeList>document.getElementsByName('foo') )[0];
When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl
annotation on a create method in the ObjectFactory
class. Since you are creating the JAXBContext
on just the DocumentType
class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext
on the generated package name or ObjectFactory
class to ensure all the necessary metadata is processed.
Example solution:
JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
To select a checkbox, use the "WebElement"
class.
To operate on a drop-down list, use the "Select"
class.
Download the Print.js from http://printjs.crabbly.com/
$http({
url: "",
method: "GET",
headers: {
"Content-type": "application/pdf"
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
var pdfFile = new Blob([data], {
type: "application/pdf"
});
var pdfUrl = URL.createObjectURL(pdfFile);
//window.open(pdfUrl);
printJS(pdfUrl);
//var printwWindow = $window.open(pdfUrl);
//printwWindow.print();
}).error(function (data, status, headers, config) {
alert("Sorry, something went wrong")
});
Also you can use postgres fdw system
https://www.postgresql.org/docs/9.5/postgres-fdw.html
You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.
pycharm download & Open in UBUNTU
Download:
download pycharm linux version here : https://www.jetbrains.com/pycharm/download/#section=linux
Extract the download the downloaded tar file using : tar -xvf pycharm-Example-tar.gz
Open:
Navigate to bin directory in the extracted folder.
run : ./pycharm.sh
You can use the static
from()
method from the LayoutInflater
class:
LayoutInflater li = LayoutInflater.from(context);
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Using ls:
ls -LR
from 'man ls':
-L, --dereference
when showing file information for a symbolic link, show informa-
tion for the file the link references rather than for the link
itself
Or, using find:
find -L .
From the find manpage:
-L Follow symbolic links.
If you find you want to only follow a few symbolic links (like maybe just the toplevel ones you mentioned), you should look at the -H option, which only follows symlinks that you pass to it on the commandline.
Both Tom and Burton's answers work for me eventually, but I had a little trouble figuring out how to apply them to a ModelChoiceField
.
The only trick to it is that the choices are stored as tuples of (<model's ID>, <model's unicode repr>)
, so if you want to set the initial model selection, you pass the model's ID as the initial value, not the object itself or it's name or anything else. Then it's as simple as:
form = EmployeeForm(initial={'manager': manager_employee_id})
Alternatively the initial
argument can be ignored in place of an extra line with:
form.fields['manager'].initial = manager_employee_id
I had this same problem. A solution for updating setuptools
pip install -U setuptools
or
pip install setuptools --upgrade
In Java 8 it's simple. See example for list of integers:
String result = Arrays.asList(1,2,3).stream().map(Object::toString).reduce((t, u) -> t + "\t" + u).orElse("");
Or multiline version (which is simpler to read):
String result = Arrays.asList(1,2,3).stream()
.map(Object::toString)
.reduce((t, u) -> t + "\t" + u)
.orElse("");
String result = Arrays.asList(1,2,3).stream()
.map(Object::toString)
.collect(Collectors.joining("\t"));
For posterity, your question was how to send an http request to https://stackoverflow.com/questions
. The real answer is: you cannot with telnet, cause this is an https-only reachable url.
So, you might want to use openssl
instead of telnet
, like this for instance
$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com
This will give you the https response.
I was able to Do it using the U (Underline Tag)
u {
text-decoration: none;
position: relative;
}
u:after {
content: '';
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
<a href="" style="text-decoration:none">
<div style="text-align: right; color: Red;">
<u> Shop Now</u>
</div>
</a>
They use a combination of IP geolocation, as well as comparing the results of a scan for nearby wireless networks with a database on their side (which is built by collecting GPS coordinates alongside wifi scan data when Android phone users use their GPS)
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
#define ID_LEN 5
char **orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */
orderedIds = (char **)malloc(variableNumberOfElements * (ID_LEN + 1) * sizeof(char));
..
From plt.imshow()
official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 10000, 0, 10], aspect = 1000)
Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.
plt.imshow(data, origin = 'lower', extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')
To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1]
and y_max - y_min = y_res * data.shape[0]
, where extent = [x_min, x_max, y_min, y_max]
. By default, aspect = 1
, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower', extent = [0, 5, 0, 5])
The aspect of color pixel is x_res / y_res
. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])
) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.5)
The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.2)
Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.
I got the color range to be asymmetric simply by changing the symkey argument to FALSE
symm=F,symkey=F,symbreaks=T, scale="none"
Solved the color issue with colorRampPalette with the breaks argument to specify the range of each color, e.g.
colors = c(seq(-3,-2,length=100),seq(-2,0.5,length=100),seq(0.5,6,length=100))
my_palette <- colorRampPalette(c("red", "black", "green"))(n = 299)
Altogether
heatmap.2(as.matrix(SeqCountTable), col=my_palette,
breaks=colors, density.info="none", trace="none",
dendrogram=c("row"), symm=F,symkey=F,symbreaks=T, scale="none")
In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:
On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.
Just in addition to @David Brown´s answer, if you want to block an IP, you must first allow all then block the IPs as such:
<RequireAll>
Require all granted
Require not ip 10.0.0.0/255.0.0.0
Require not ip 172.16.0.0/12
Require not ip 192.168
</RequireAll>
First line allows all
Second line blocks from 10.0.0.0 to 10.255.255.255
Third line blocks from 172.16.0.0 to 172.31.255.255
Fourth line blocks from 192.168.0.0 to 192.168.255.255
You may use any of the notations mentioned above to suit you CIDR needs.
During my research for a similar case, I have been ending up by checking the stack trace in the subclass method to find out from where the call is coming from. There are probably smarter ways to do so, but it works out for me and it's a dynamic approach.
public void method2(){
Exception ex=new Exception();
StackTraceElement[] ste=ex.getStackTrace();
if(ste[1].getClassName().equals(this.getClass().getSuperclass().getName())){
super.method2();
}
else{
//subclass method2 code
}
}
I think the question to have a solution for the case is reasonable. There are of course ways to solve the issue with different method names or even different parameter types, like already mentioned in the thread, but in my case I dindn't like to confuse by different method names.
From the Python documentation:
And while the module doesn’t directly support parsing strings, it can easily be done:
import csv
for row in csv.reader(['one,two,three']):
print row
Just drop your string data into a singleton list.
I have same problem. I solved install this setup. (I use vs 2015 (4.6))
sep=''
in the context of a function call sets the named argument sep
to an empty string. See the print()
function; sep
is the separator used between multiple values when printing. The default is a space (sep=' '
), this function call makes sure that there is no space between Property tax: $
and the formatted tax
floating point value.
Compare the output of the following three print()
calls to see the difference
>>> print('foo', 'bar')
foo bar
>>> print('foo', 'bar', sep='')
foobar
>>> print('foo', 'bar', sep=' -> ')
foo -> bar
All that changed is the sep
argument value.
\t
in a string literal is an escape sequence for tab character, horizontal whitespace, ASCII codepoint 9.
\t
is easier to read and type than the actual tab character. See the table of recognized escape sequences for string literals.
Using a space or a \t
tab as a print separator shows the difference:
>>> print('eggs', 'ham')
eggs ham
>>> print('eggs', 'ham', sep='\t')
eggs ham
Since PowerShell can call .NET classes, you could do the following:
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion
Or as noted here on a list of files:
get-childitem * -include *.dll,*.exe | foreach-object { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion }
Or even nicer as a script: https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/
This builds on the above answer from Gordon--not all of it is my original work. What I did was add a more generic method to my static utility class.
public static int MatchingRowIndex(DataGridView dgv, string columnName, string searchValue)
{
int rowIndex = -1;
bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;
dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
if (dgv.Rows.Count > 0 && dgv.Columns.Count > 0 && dgv.Columns[columnName] != null)
{
DataGridViewRow row = dgv.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.Cells[columnName].Value.ToString().Equals(searchValue));
rowIndex = row.Index;
}
dgv.AllowUserToAddRows = tempAllowUserToAddRows;
return rowIndex;
}
Then in whatever form I want to use it, I call the method passing the DataGridView, column name and search value. For simplicity I am converting everything to strings for the search, though it would be easy enough to add overloads for specifying the data types.
private void UndeleteSectionInGrid(string sectionLetter)
{
int sectionRowIndex = UtilityMethods.MatchingRowIndex(dgvSections, "SectionLetter", sectionLetter);
dgvSections.Rows[sectionRowIndex].Cells["DeleteSection"].Value = false;
}
Fortunately there is a little bit in the docs about the splash images, which put me on the road to getting the right location for the icon images as well. So here it goes.
Where the files are placed
Once you have built your project using command-line interface "cordova build ios" you should have a complete file structure for your iOS app in the platforms/ios/
folder.
Inside that folder is a folder with the name of your app. Which in turn contains a resources/
directory where you will find the icons/
and splashscreen/
folders.
In the icons folder you will find four icon files (for 57px and 72 px, each in regular and @2x version). These are the Phonegap placeholder icons you've been seeing so far.
What to do
All you have to do is save the icon files in this folder. So that's:
YourPhonegapProject/Platforms/ios/YourAppName/Resources/icons
Same for splashscreen files.
Notes
After placing the files there, rebuild the project using cordova build ios
AND use xCode's 'Clean product' menu command. Without this, you'll still be seeing the Phonegap placeholders.
It's wisest to rename your files the iOS/Apple way (i.e. [email protected] etc) instead of editing the names in the info.plist or config.xml. At least that worked for me.
And by the way, ignore the weird path and the weird filename given for the icons in config.xml (i.e. <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />
). I just left those definitions there, and the icons showed up just fine even though my 114px icon was named [email protected]
instead of icon-57-2x.png
.
Don't use config.xml to prevent Apple's gloss effect on the icon. Instead, tick the box in xCode (click the project title in the left navigation column, select your app under the Target header, and scroll down to the icons section).
train_test_split is now in model_selection. Just type:
from sklearn.model_selection import train_test_split
it should work
You can group your specific layout under the correct folder structure as follows.
layout-land-target_version
ie
layout-land-19 // target KitKat
likewise you can create your layouts.
Hope this will help you
I was working on a nice defect last time and was wondering more about how to use properly hover property for A tag link and for IE browser. A strange thing for me was that IE was not able to capture A tag link element based on a simple A selector. So, I found out how to even force capturing A tag element and I spotted that we must use more specifc CSS selector. Here is an example below - It works perfect:
li a[href]:hover {...}
What about?
If oSheet.QueryTables.Count > 0 Then
oCmbBox.AddItem oSheet.Name
End If
Or
If oSheet.ListObjects.Count > 0 Then
'// Source type 3 = xlSrcQuery
If oSheet.ListObjects(1).SourceType = 3 Then
oCmbBox.AddItem oSheet.Name
End IF
End IF
You can simply subtract two dates. You have to cast it first, using to_date
:
select to_date('2000-01-01', 'yyyy-MM-dd')
- to_date('2000-01-02', 'yyyy-MM-dd')
datediff
from dual
;
The result is in days, to the difference of these two dates is -1
(you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.
From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.
UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>
Because both <p>
and <ol>
are element rendered as block.
The easiest way would be to package the Vagrant box and then copy (e.g. scp
or rsync
) it over to the other PC, add it and vagrant up
;-)
For detailed steps, check this out =>
Is there any way to clone a vagrant box that is already installed
On my server linux server (not true on my local dev mac), directories are ignored as long as I don't add an asterisk:
www/archives/*
I don't know why but it made me loose a couple of hours, so I wanted to share...
I just ran into this. As mentioned in this answer, using mode: "no-cors"
will give you an opaque response
, which doesn't seem to return data in the body.
opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.
In my case I was using Express
. After I installed cors for Express and configured it and removed mode: "no-cors"
, I was returned a promise. The response data will be in the promise, e.g.
fetch('http://example.com/api/node', {
// mode: 'no-cors',
method: 'GET',
headers: {
Accept: 'application/json',
},
},
).then(response => {
if (response.ok) {
response.json().then(json => {
console.log(json);
});
}
});
I had this problem and the reason was because I copied and pasted a controller into my app. I needed to change ApplicationController
to ApplicationController::Base
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}
In build.gradle below dependencies add:
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == "com.android.support") {
if (!requested.name.startsWith("multidex")) {
details.useVersion "27.+"
}
}
}
}
This worked for me, I found it on stack, addressed as the "Theme Error solution": Theme Error - how to fix?
from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
You trap selections with these data source methods.
– tableView:willSelectRowAtIndexPath:
– tableView:didSelectRowAtIndexPath:
– tableView:willDeselectRowAtIndexPath:
– tableView:didDeselectRowAtIndexPath:
In these methods, you check if the selected row is one you want to be selectable. If it is, take an action, if not, do nothing.
Unfortunately, you can't turn off selection for just one section. It's the whole table or nothing.
You can however set the table cells selectionStyle
property to UITableViewCellSelectionStyleNone
. I believe that will make the selection invisible. Combined with the above methods that should make the cells look completely inert from the user's perspective.
If you have a table in which only some of the rows are selectable it is important that the cells of the selectable rows be visually distinct from the non-selectable rows. The chevron accessory button is the default way to do this.
However you do it, you don't want your users trying to select rows and thinking the app has malfed because the row doesn't do anything.
These two classes can work together to schedule a periodic task:
import java.util.TimerTask;
import java.util.Date;
// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
Date now;
public void run() {
// Write code here that you want to execute periodically.
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create task repeating every 1 sec
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
In Prepared Statements the user is forced to enter data as parameters . If user enters some vulnerable statements like DROP TABLE or SELECT * FROM USERS then data won't be affected as these would be considered as parameters of the SQL statement
I've found that the preferred solution does not handle line breaks.
I've found this approach works in all cases:
UILabel* dummyLabel = [UILabel new];
[dummyLabel setFrame:CGRectMake(0, 0, desiredWidth, CGFLOAT_MAX)];
dummyLabel.numberOfLines = 0;
[dummyLabel setLineBreakMode:NSLineBreakByWordWrapping];
dummyLabel.attributedText = myString;
[dummyLabel sizeToFit];
CGSize requiredSize = dummyLabel.frame.size;
While working on a .Net app build with EF code first, I got this error message when trying to apply my migration where I had a Sql("UPDATE tableName SET columnName = value");
statement.
Turns out I misspelled the columnName.
The example code leads to a memory leak in Tomcat (after undeploying the webapp, the classloader still remains in memory) which will cause an outofmemory
eventually. The way to solve it is to use the sqlite-jdbc-3.7.8.jar; it's a snapshot, so it doesn't appear for maven yet.
git rev-parse
Also works for getting the current branch name using the --abbrev-ref flag like:
git rev-parse --abbrev-ref HEAD
The error suggests that the code you are using is expecting a virtual directory to be setup on IIS.
Look up the documentation and add the required virtual directory. It should be a directory that has a web.config
in it (not the root directory).
1) Check sysctl file-max
limit:
$ cat /proc/sys/fs/file-max
If the limit is lower than your desired value, open the sysctl.conf
and add this line at the end of file:
fs.file-max = 65536
Finally, apply sysctl
limits:
$ sysctl -p
2) Edit /etc/security/limits.conf
and add below the mentioned
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
These limits won't apply for root
user, if you want to change root
limits you have to do that explicitly:
root soft nofile 65535
root hard nofile 65535
...
3) Reboot system or add following line to the end of /etc/pam.d/common-session
:
session required pam_limits.so
Logout and login again.
4) Check soft limits:
$ ulimit -a
and hard limits:
$ ulimit -Ha
....
open files (-n) 65535
Reference : http://ithubinfo.blogspot.in/2013/07/how-to-increase-ulimit-open-file-and.html
'b' should be in capital letter in document.getElementById
modified code jsfiddle
function test()
{
var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
//document.body.appendChild(element);
}
varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.