I would personally use http://www.datejs.com/, really handy. Specifically, look at the time.js file: http://code.google.com/p/datejs/source/browse/trunk/src/time.js
I had a problem where I had to many columns to visually inspect on the screen so a short list comp that filters and returns the offending columns is
nan_cols = [i for i in df.columns if df[i].isnull().any()]
if that's helpful to anyone
Put code edittext xml file,
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Try something like this:
IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);
Not sure if it'll resize after being launched though, so maybe it's not what you want
"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:
float(20)/15 #1.33333333
If you want to be correct, use INFORMATION_SCHEMA.
SELECT *
FROM information_schema.tables
WHERE table_schema = 'yourdb'
AND table_name = 'testtable'
LIMIT 1;
Alternatively, you can use SHOW TABLES
SHOW TABLES LIKE 'yourtable';
If there is a row in the resultset, table exists.
When you delete innodb tables, MySQL does not free the space inside the ibdata file, that's why it keeps growing. These files hardly ever shrink.
How to shrink an existing ibdata file:
You can script this and schedule the script to run after a fixed period of time, but for the setup described above it seems that multiple tablespaces are an easier solution.
If you use the configuration option innodb_file_per_table
, you create multiple tablespaces. That is, MySQL creates separate files for each table instead of one shared file. These separate files a stored in the directory of the database, and they are deleted when you delete this database. This should remove the need to shrink/purge ibdata files in your case.
More information about multiple tablespaces:
https://dev.mysql.com/doc/refman/5.6/en/innodb-file-per-table-tablespaces.html
You can use useEffect/useLayoutEffect to achieve this:
const SomeComponent = () => {
const [count, setCount] = React.useState(0)
React.useEffect(() => {
if (count > 1) {
document.title = 'Threshold of over 1 reached.';
} else {
document.title = 'No threshold reached.';
}
}, [count]);
return (
<div>
<p>{count}</p>
<button type="button" onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
};
More about it over here.
If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:
// npm install use-state-with-callback
import useStateWithCallback from 'use-state-with-callback';
const SomeOtherComponent = () => {
const [count, setCount] = useStateWithCallback(0, count => {
if (count > 1) {
document.title = 'Threshold of over 1 reached.';
} else {
document.title = 'No threshold reached.';
}
});
return (
<div>
<p>{count}</p>
<button type="button" onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
};
ctrl + L clears the screen on Ubuntu Linux.
You're right, it's localhost\SQLEXPRESS
(just no $
) and yes, it's the same for both 2005 and 2008 express versions.
An alternative solution to changing the font size is to change the padding. When Python saves your PNG, you can change the layout using the dialogue box that opens. The spacing between the axes, padding if you like can be altered at this stage.
You can try this:-
<a href="some.htm" target="_blank">Link Text</a>
and you can try this one also:-
<a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
If nothing works Restart your PC . Restarting my computer does the trick
For PHP7 on CentOS or EC2 Linux AMI:
sudo yum install php70-gd
I think you meant to do url[i] <- paste(...
instead of url[i] = paste(...
. If so replace =
with <-
.
This should work. But I have same problems on an Android phone.
<input type="number" /> <input type="tel" />
I found out, that if I didn't include the jquerymobile-framework, the keypad showed correctly on the two types of fields.
But I havn't found a solution to solve that problem, if you really need to use jquerymobile.
UPDATE: I found out, that if the form-tag is stored out of the
<div data-role="page">
The number keypad isn't shown. This must be a bug...
The complete way would be:
bool b1;
bool? b2 = ???;
if (b2.HasValue)
b1 = b2.Value;
Or you can test for specific values using
bool b3 = (b2 == true); // b2 is true, not false or null
There is a command available for this on the SQLite command line:
.tables ?PATTERN? List names of tables matching a LIKE pattern
Which converts to the following SQL:
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1
this works for me
<select class="form-control" id="foo">
<option value="first" data-id="1">first</option>
<option value="second" data-id="2">second</option>
</select>
and the script
$('#foo').on("change",function(){
var dataid = $("#foo option:selected").attr('data-id');
alert(dataid)
});
Firstly, your example is looking quite correct and works well on my machine. You may go another way.
curl $CURLARGS $RVMHTTP > ./install.sh
All output now storing in ./install.sh
file, which you can edit and execute.
The following worked for me on Windows.
git submodule init
git submodule update
The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:
arr = []
for i in array :
if i == "two" :
arr.push(i)
print(i)
You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.
The english equivalent of what you are doing is:
You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"
The reason 'i' is equal to "three" is because three was the last thing that was defined as I
the computer did:
i = "one"
i = "two"
i = "three"
print(["two"])
Because you asked it to.
If you want the index, go here If you want the values in an array, define the array, like this:
MyArray = [(i) for i in my_list if i=="two"]
you can use SS_ISCONNECTED
macro in getsockopt()
function.
SS_ISCONNECTED
is define in socketvar.h
.
i think it is simple just add headerLeft : null
, i am using react-native cli, so this is the example :
static navigationOptions = {
headerLeft : null
};
setTimeout
returns a timer handle, which you can use to stop the timeout with clearTimeout
.
So for instance:
function setBgPosition() {
var c = 0,
timer = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c >= numbers.length) {
c = 0;
}
timer = setTimeout(run, 200);
}
timer = setTimeout(run, 200);
return stop;
function stop() {
if (timer) {
clearTimeout(timer);
timer = 0;
}
}
So you'd use that as:
var stop = setBgPosition();
// ...later, when you're ready to stop...
stop();
Note that rather than having setBgPosition
call itself again, I've just had it set c
back to 0
. Otherwise, this wouldn't work. Also note that I've used 0
as a handle value for when the timeout isn't pending; 0
isn't a valid return value from setTimeout
so it makes a handy flag.
This is also one of the (few) places I think you'd be better off with setInterval
rather than setTimeout
. setInterval
repeats. So:
function setBgPosition() {
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c >= numbers.length) {
c = 0;
}
}
return setInterval(run, 200);
}
Used like this:
var timer = setBgPosition();
// ...later, when you're ready to stop...
clearInterval(timer);
All of the above notwithstanding, I'd want to find a way to make setBgPosition
stop things itself, by detecting that some completion condition has been satisfied.
Here is a full program example of a for-each macro in C99:
#include <stdio.h>
typedef struct list_node list_node;
struct list_node {
list_node *next;
void *data;
};
#define FOR_EACH(item, list) \
for (list_node *(item) = (list); (item); (item) = (item)->next)
int
main(int argc, char *argv[])
{
list_node list[] = {
{ .next = &list[1], .data = "test 1" },
{ .next = &list[2], .data = "test 2" },
{ .next = NULL, .data = "test 3" }
};
FOR_EACH(item, list)
puts((char *) item->data);
return 0;
}
How about a one-liner list of digits...
ldigits = lambda n, l=[]: not n and l or l.insert(0,n%10) or ldigits(n/10,l)
There is a actually a setting in the VPC called "DNS Hostnames". You can modify the VPC in which the EC2 instance exists, and change this to "Yes". That should do the trick.
I ran into this issue yesterday and tried the above answer from Manny, which did not work. The VPC setting, however, did work for me.
Ultimately I added an EIP and I use that to connect.
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
On your controller
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
The lists method now returns a Collection. Upgrading To 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
Most of the time it is cause by broken database connection especially at local server, when one forget to start XAMPP or WAMPP server,
solution -1 :- Rename pub/local.xml.sample into local.xml or pub/local.xml into local.xml.sample if this is not work try solution 2
solution 2 :- go to php.ini file and increase max_execution time and fresh install magento confirm issue resolved
Below works for first tr
of the table under thead
table thead tr:first-child {
background: #f2f2f2;
}
And this works for the first tr
of thead
and tbody
both:
table thead tbody tr:first-child {
background: #f2f2f2;
}
as long as you did not commit you can type
git merge --abort
just as the command line suggested.
Use this....
string popupScript = "<script language=JavaScript>";
popupScript += "alert('Please enter valid Email Id');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);
I know this is an old Question
But in case you want to do it programmatically or the java way
For Image Backgrounds; you can use BackgroundImage class
BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));
For Paint or Fill Backgrounds; you can use BackgroundFill class
BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));
Keeps your java alive && your css dead..
Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)
Ok, this is not a very serious review, but here is what I can say:
I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:
#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis
import sys, time
stdout = sys.stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
class Iterator(object) :
def __init__(self):
print 'Rendering...'
for y in xrange(-39, 39):
stdout.write('\n')
for x in xrange(-39, 39):
if self.mandelbrot(x/40.0, y/40.0) :
stdout.write(' ')
else:
stdout.write('*')
def mandelbrot(self, x, y):
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
if zi2 + zr2 > BAILOUT:
return i
return 0
t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)
As a result:
PyChecker
is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.PyFlakes
is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.PyLint
has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).Strong points of PyLint
:
Cons of Pylint:
Corrected script (with lazy doc strings and variable names):
#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""
import time
from sys import stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
def mandelbrot(dim_1, dim_2):
"""
function doc string
"""
cr1 = dim_1 - 0.5
ci1 = dim_2
zi1 = 0.0
zr1 = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr1 * zi1
zr2 = zr1 * zr1
zi2 = zi1 * zi1
zr1 = zr2 - zi2 + cr1
zi1 = temp + temp + ci1
if zi2 + zr2 > BAILOUT:
return i
return 0
def execute() :
"""
func doc string
"""
print 'Rendering...'
for dim_1 in xrange(-39, 39):
stdout.write('\n')
for dim_2 in xrange(-39, 39):
if mandelbrot(dim_1/40.0, dim_2/40.0) :
stdout.write(' ')
else:
stdout.write('*')
START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)
Thanks to Rudiger Wolf, I discovered pep8
that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.
Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.
To give you a little idea of their output:
pep8:
./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3
Pylint:
************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C: 1: Missing docstring
C: 5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
[...] and a very long report with useful stats like :
Duplication
-----------
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
I had the same problem - i wanted to pass a parameter to another page by clicking a hyperlink and get the value to go to the next page (without using GET because the parameter is stored in the URL).
to those who don't understand why you would want to do this the answer is you dont want the user to see sensitive information or you dont want someone editing the GET.
well after scouring the internet it seemed it wasnt possible to make a normal hyperlink using the POST method.
And then i had a eureka moment!!!! why not just use CSS to make the submit button look like a normal hyperlink??? ...and put the value i want to pass in a hidden field
i tried it and it works. you can see an exaple here http://paulyouthed.com/test/css-button-that-looks-like-hyperlink.php
the basic code for the form is:
<form enctype="multipart/form-data" action="page-to-pass-to.php" method="post">
<input type="hidden" name="post-variable-name" value="value-you-want-pass"/>
<input type="submit" name="whatever" value="text-to-display" id="hyperlink-style-button"/>
</form>
the basic css is:
#hyperlink-style-button{
background:none;
border:0;
color:#666;
text-decoration:underline;
}
#hyperlink-style-button:hover{
background:none;
border:0;
color:#666;
text-decoration:none;
cursor:pointer;
cursor:hand;
}
Update: 8-20-2015
Please note the instructions have changed since this question was asked 2 yrs ago.
So on Newer versions of Android and Chrome for Android. You need to use this.
https://developers.google.com/web/tools/setup/remote-debugging/remote-debugging?hl=en
Original Answer:
I have the S3 and it works fine. I have found that a common mistake is not enabling USB Debugging in Chrome mobile. Not only do you have to enable USB debugging on the device itself under developer options but you have to go to the Chrome Browser on your phone and enable it in the settings there too.
Try this with the SDK
Enable port forwarding on your computer by doing the following command below
C:\adb forward tcp:9222 localabstract:chrome_devtools_remote
Go to http://localhost:9222
in Chrome on your Computer
TroubleShooting:
If you get command not found
when trying to run ADB
, make sure Platform-Tools is in your path or just use the whole path to your SDK and run it
C:\path-to-SDK\platform-tools\adb forward tcp:9222 localabstract:chrome_devtools_remote
If you get "device not found
", then run adb kill-server
and then try again.
SynchronousQueue
( Taken from another question )SynchronousQueue
is more of a handoff, whereas the LinkedBlockingQueue
just allows a single element. The difference being that the put()
call to a SynchronousQueue
will not return until there is a corresponding take()
call, but with a LinkedBlockingQueue
of size 1, the put()
call (to an empty queue) will return immediately. It's essentially the BlockingQueue
implementation for when you don't really want a queue (you don't want to maintain any pending data).
LinkedBlockingQueue
(LinkedList
Implementation but Not Exactly JDK Implementation of LinkedList
It uses static inner class Node to maintain Links between elements )Constructor for LinkedBlockingQueue
public LinkedBlockingQueue(int capacity)
{
if (capacity < = 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node< E >(null); // Maintains a underlying linkedlist. ( Use when size is not known )
}
Node class Used to Maintain Links
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
3 . ArrayBlockingQueue ( Array Implementation )
Constructor for ArrayBlockingQueue
public ArrayBlockingQueue(int capacity, boolean fair)
{
if (capacity < = 0)
throw new IllegalArgumentException();
this.items = new Object[capacity]; // Maintains a underlying array
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
IMHO Biggest Difference between ArrayBlockingQueue
and LinkedBlockingQueue
is clear from constructor one has underlying data structure Array and other linkedList.
ArrayBlockingQueue
uses single-lock double condition algorithm and LinkedBlockingQueue
is variant of the "two lock queue" algorithm and it has 2 locks 2 conditions ( takeLock , putLock)
use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,
this is a code:
input type="submit" name="continue" value="submit" onClick="**return** checkform();"
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>
What I'm currently doing Dec 2012 (combines most of these answers):
oldPath="vendor/example"
git config -f .git/config --remove-section "submodule.${oldPath}"
git config -f .gitmodules --remove-section "submodule.${oldPath}"
git rm --cached "${oldPath}"
rm -rf "${oldPath}" ## remove src (optional)
rm -rf ".git/modules/${oldPath}" ## cleanup gitdir (optional housekeeping)
git add .gitmodules
git commit -m "Removed ${oldPath}"
but select-String doesn't seem to have this option.
Correct. PowerShell is not a clone of *nix shells' toolset.
However it is not hard to build something like it yourself:
$regexes = Get-Content RegexFile.txt |
Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }
$fileList | Get-Content | Where-Object {
foreach ($r in $regexes) {
if ($r.IsMatch($_)) {
$true
break
}
}
$false
}
You can use the Python REPL to simulate a timeout while receiving data (i.e. after a connection has been established successfully). Nothing but a standard Python installation is needed.
Python 2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.bind(('localhost', 9000))
>>> s.listen(0)
>>> (clientsocket, address) = s.accept()
Now it waits for an incoming connection. Connect whatever you want to test to localhost:9000
. When you do, Python will accept the connection and accept()
will return it. Unless you send any data through the clientsocket
, the caller's socket should time out during the next recv()
.
The other already explained to you that the syntax that you observe is called "constructor initializer list". This syntax lets you to custom-initialize base subobjects and member subobjects of the class (as opposed to allowing them to default-initialize or to remain uninitialized).
I just want to note that the syntax that, as you said, "looks like a constructor call", is not necessarily a constructor call. In C++ language the ()
syntax is just one standard form of initialization syntax. It is interpreted differently for different types. For class types with user-defined constructor it means one thing (it is indeed a constructor call), for class types without user-defined constructor it means another thing (so called value initialization ) for empty ()
) and for non-class types it again means something different (since non-class types have no constructors).
In your case the data member has type int
. int
is not a class type, so it has no constructor. For type int
this syntax means simply "initialize bar
with the value of num
" and that's it. It is done just like that, directly, no constructors involved, since, once again, int
is not a class type of therefore it can't have any constructors.
Create Proc[usp_mquestions]
(
@title nvarchar(500), --0
@tags nvarchar(max), --1
@category nvarchar(200), --2
@ispoll char(1), --3
@descriptions nvarchar(max), --4
)
AS
BEGIN TRY
BEGIN
DECLARE @message varchar(1000);
DECLARE @tempid bigint;
IF((SELECT count(id) from [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN
if @id=0
begin
select @tempid =id from [xyz] where id=@id;
if @tempid is null
BEGIN
INSERT INTO xyz
(entrydate,updatedate)
VALUES
(GETDATE(),GETDATE())
SET @tempid=@@IDENTITY;
END
END
ELSE
BEGIN
set @tempid=@id
END
if @tempid>0
BEGIN
-- Updation of table begin--
UPDATE tab_questions
set title=@title, --0
tags=@tags, --1
category=@category, --2
ispoll=@ispoll, --3
descriptions=@descriptions, --4
status=@status, --5
WHERE id=@tempid ; --9 ;
IF @id=0
BEGIN
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END
ELSE
BEGIN
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)
END
END
ELSE
BEGIN
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END
END
END
END TRY
BEGIN CATCH
SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;
Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:
$(document).ready({
$('a.TOClink').click(function(){
showTOC();
});
});
function showTOC() {
$('#example').dialog({modal:true});
}
A more concise example which accomplishes the desired effect using the jQuery UI dialog is:
<div id="terms" style="display:none;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<a id="showTerms" href="#">Show Terms & Conditions</a>
<script type="text/javascript">
$(document).ready(function(){
$('#showTerms').click(function(){
$('#terms').dialog({modal:true});
});
});
</script>
The compiler replaces null comparisons with a call to HasValue
, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
FOR WITHIN TEMPLATES
This is how I usually get current logged in user and their id in my templates.
<p>Your Username is : {{user}} </p>
<p>Your User Id is : {{user.id}} </p>
It sounds like you are doing everything exactly as the client credential section of the Subversion book suggests. The only thing I can think of is that the server isn't asking for the username and password because is getting it from somewhere else.
SELECT
*
FROM
[SERVER2NAME].[THEDB].[THEOWNER].[THETABLE]
You can also look at using Linked Servers. Linked servers can be other types of data sources too such as DB2 platforms. This is one method for trying to access DB2 from a SQL Server TSQL or Sproc call...
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code here
return false;
}
return super.onKeyDown(keyCode, event);
}
This is very simple.
Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..
Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.
Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.
Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.
CSS3 allows this sort of thing and it looks like this:
body {
background-image: url(images/bgtop.png), url(images/bg.png);
background-repeat: repeat-x, repeat;
}
The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:
<body>
<div id="bgTopDiv">
content here
</div>
</body>
body{
background-image: url(images/bg.png);
}
#bgTopDiv{
background-image: url(images/bgTop.png);
background-repeat: repeat-x;
}
I found this by adapting some tutos. Thanks to google, and to all of you ;)
def findall(L, test):
i=0
indices = []
while(True):
try:
# next value in list passing the test
nextvalue = filter(test, L[i:])[0]
# add index of this value in the index list,
# by searching the value in L[i:]
indices.append(L.index(nextvalue, i))
# iterate i, that is the next index from where to search
i=indices[-1]+1
#when there is no further "good value", filter returns [],
# hence there is an out of range exeption
except IndexError:
return indices
A very simple use:
a = [0,0,2,1]
ind = findall(a, lambda x:x>0))
[2, 3]
P.S. scuse my english
From the package matplotlib.dates as shown in this example the date format can be applied to the axis label and ticks for plot.
Below I have given an example for labeling axis ticks for multiplots
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
df = pd.read_csv('US_temp.csv')
plt.plot(df['Date'],df_f['MINT'],label='Min Temp.')
plt.plot(df['Date'],df_f['MAXT'],label='Max Temp.')
plt.legend()
####### Use the below functions #######
dtFmt = mdates.DateFormatter('%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.show()
As simple as that
I had a huge problems with auto layout. We have two containers inside table cell. Second container is resized depending on Item description (0 - 1000 chars), and row should be resized based on them.
The missing ingredient was bottom constraint for description.
I've changed bottom constraint of dynamic element from = 0 to >= 0.
Here's a short and sweet JavaScript function to fetch the session ID:
function session_id() {
return /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
}
Or if you prefer a variable, here's a simple one-liner:
var session_id = /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
Should match the session ID cookie for PHP, JSP, .NET, and I suppose various other server-side processors as well.
To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.
find . -mtime -1 -ls
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
Create a command file with your commands
ie: commands.txt
open www.domainhere.com
user useridhere
passwordhere
put test.txt
bye
Then run the FTP client from the command line: ftp -s:commands.txt
Note: This will work for the Windows FTP client.
Edit: Should have had a linebreak after the user name before the password.
.remove()
is deprecated. instead we can use deleteMany
DateTime.deleteMany({}, callback)
.
i had the same issue and it solved by removing drawable-v24 with (24) in front of images in drawable folder and replacing them with ordinary drawables.
The following is taken from http://pandas.pydata.org/pandas-docs/dev/indexing.html. There are a few more examples... you have to scroll down a little
In [816]: df1
0 2 4 6
0 0.569605 0.875906 -2.211372 0.974466
2 -2.006747 -0.410001 -0.078638 0.545952
4 -1.219217 -1.226825 0.769804 -1.281247
6 -0.727707 -0.121306 -0.097883 0.695775
8 0.341734 0.959726 -1.110336 -0.619976
10 0.149748 -0.732339 0.687738 0.176444
Select via integer slicing
In [817]: df1.iloc[:3]
0 2 4 6
0 0.569605 0.875906 -2.211372 0.974466
2 -2.006747 -0.410001 -0.078638 0.545952
4 -1.219217 -1.226825 0.769804 -1.281247
In [818]: df1.iloc[1:5,2:4]
4 6
2 -0.078638 0.545952
4 0.769804 -1.281247
6 -0.097883 0.695775
8 -1.110336 -0.619976
Select via integer list
In [819]: df1.iloc[[1,3,5],[1,3]]
2 6
2 -0.410001 0.545952
6 -0.121306 0.695775
10 -0.732339 0.176444
In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.
$url='the/url/you/want/to/go';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
this works for me fine.
Update for Swift 3:
// Create the AlertController and add its actions like button in ActionSheet
let actionSheetController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .actionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default) { action -> Void in
print("Save")
}
actionSheetController.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default) { action -> Void in
print("Delete")
}
actionSheetController.addAction(deleteActionButton)
self.present(actionSheetController, animated: true, completion: nil)
Fixed it with -no-pie
option in linker stage:
g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...
C99 quotes
This answer aims to quote and explain the relevant parts of the C99 N1256 standard draft.
Definition of declarator
The term declarator will come up a lot, so let's understand it.
From the language grammar, we find that the following underline characters are declarators:
int f(int x, int y);
^^^^^^^^^^^^^^^
int f(int x, int y) { return x + y; }
^^^^^^^^^^^^^^^
int f();
^^^
int f(x, y) int x; int y; { return x + y; }
^^^^^^^
Declarators are part of both function declarations and definitions.
There are 2 types of declarators:
Parameter type list
Declarations look like:
int f(int x, int y);
Definitions look like:
int f(int x, int y) { return x + y; }
It is called parameter type list because we must give the type of each parameter.
Identifier list
Definitions look like:
int f(x, y)
int x;
int y;
{ return x + y; }
Declarations look like:
int g();
We cannot declare a function with a non-empty identifier list:
int g(x, y);
because 6.7.5.3 "Function declarators (including prototypes)" says:
3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.
It is called identifier list because we only give the identifiers x
and y
on f(x, y)
, types come after.
This is an older method, and shouldn't be used anymore. 6.11.6 Function declarators says:
1 The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.
and the Introduction explains what is an obsolescent feature:
Certain features are obsolescent, which means that they may be considered for withdrawal in future revisions of this International Standard. They are retained because of their widespread use, but their use in new implementations (for implementation features) or new programs (for language [6.11] or library features [7.26]) is discouraged
f() vs f(void) for declarations
When you write just:
void f();
it is necessarily an identifier list declaration, because 6.7.5 "Declarators" says defines the grammar as:
direct-declarator:
[...]
direct-declarator ( parameter-type-list )
direct-declarator ( identifier-list_opt )
so only the identifier-list version can be empty because it is optional (_opt
).
direct-declarator
is the only grammar node that defines the parenthesis (...)
part of the declarator.
So how do we disambiguate and use the better parameter type list without parameters? 6.7.5.3 Function declarators (including prototypes) says:
10 The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.
So:
void f(void);
is the way.
This is a magic syntax explicitly allowed, since we cannot use a void
type argument in any other way:
void f(void v);
void f(int i, void);
void f(void, int);
What can happen if I use an f() declaration?
Maybe the code will compile just fine: 6.7.5.3 Function declarators (including prototypes):
14 The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.
So you can get away with:
void f();
void f(int x) {}
Other times, UB can creep up (and if you are lucky the compiler will tell you), and you will have a hard time figuring out why:
void f();
void f(float x) {}
See: Why does an empty declaration work for definitions with int arguments but not for float arguments?
f() and f(void) for definitions
f() {}
vs
f(void) {}
are similar, but not identical.
6.7.5.3 Function declarators (including prototypes) says:
14 An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.
which looks similar to the description of f(void)
.
But still... it seems that:
int f() { return 0; }
int main(void) { f(1); }
is conforming undefined behavior, while:
int f(void) { return 0; }
int main(void) { f(1); }
is non conforming as discussed at: Why does gcc allow arguments to be passed to a function defined to be with no arguments?
TODO understand exactly why. Has to do with being a prototype or not. Define prototype.
In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.
As other answers have said, the string concatenation operator in Lua is two dots.
Your simple example would be written like this:
filename = "checkbook"
filename = filename .. ".tmp"
However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the data from the source strings to it. That makes successive concatenations to a single string have very poor performance.
The Lua idiom for this case is something like this:
function listvalues(s)
local t = { }
for k,v in ipairs(s) do
t[#t+1] = tostring(v)
end
return table.concat(t,"\n")
end
By collecting the strings to be concatenated in an array t
, the standard library routine table.concat
can be used to concatenate them all up (along with a separator string between each pair) without unnecessary string copying.
Update: I just noticed that I originally wrote the code snippet above using pairs()
instead of ipairs()
.
As originally written, the function listvalues()
would indeed produce every value from the table passed in, but not in a stable or predictable order. On the other hand, it would include values who's keys were not positive integers in the span of 1
to #s
. That is what pairs()
does: it produces every single (key,value) pair stored in the table.
In most cases where you would be using something like listvaluas()
you would be interested in preserving their order. So a call written as listvalues{13, 42, 17, 4}
would produce a string containing those value in that order. However, pairs()
won't do that, it will itemize them in some order that depends on the underlying implementation of the table data structure. It is known that the order not only depends on the keys, but also on the order in which the keys were inserted and other keys removed.
Of course ipairs()
isn't a perfect answer either. It only enumerates those values of the table that form a "sequence". That is, those values who's keys form an unbroken block spanning from 1 to some upper bound, which is (usually) also the value returned by the #
operator. (In many cases, the function ipairs()
itself is better replaced by a simpler for
loop that just counts from 1
to #s
. This is the recommended practice in Lua 5.2 and in LuaJIT where the simpler for
loop can be more efficiently implemented than the ipairs()
iterator.)
If pairs()
really is the right approach, then it is usually the case that you want to print both the key and the value. This reduces the concerns about order by making the data self-describing. Of course, since any Lua type (except nil
and the floating point NaN
) can be used as a key (and NaN
can also be stored as a value) finding a string representation is left as an exercise for the student. And don't forget about trees and more complex structures of tables.
Update (9/1/15): The OP has made this question a bit of a moving target. It’s been updated again. So, I feel responsible to update my reply.
Yes, this is possible.
You can solve this by updating Child’s onClick
to be this.props.onClick.bind(null, this)
:
var Child = React.createClass({
render: function () {
return <a onClick={this.props.onClick.bind(null, this)}>Click me</a>;
}
});
The event handler in your Parent can then access the component and event like so:
onClick: function (component, event) {
// console.log(component, event);
},
Parent already knows Child’s props
.
This isn’t clear in the provided example because no props are actually being provided. This sample code might better support the question being asked:
var Child = React.createClass({
render: function () {
return <a onClick={this.props.onClick}> {this.props.text} </a>;
}
});
var Parent = React.createClass({
getInitialState: function () {
return { text: "Click here" };
},
onClick: function (event) {
// event.component.props ?why is this not available?
},
render: function() {
return <Child onClick={this.onClick} text={this.state.text} />;
}
});
It becomes much clearer in this example that you already know what the props of Child are.
If it’s truly about using a Child’s props, you can avoid any hookup with Child altogether.
JSX has a spread attributes API I often use on components like Child. It takes all the props
and applies them to a component. Child would look like this:
var Child = React.createClass({
render: function () {
return <a {...this.props}> {this.props.text} </a>;
}
});
Allowing you to use the values directly in the Parent:
var Parent = React.createClass({
getInitialState: function () {
return { text: "Click here" };
},
onClick: function (text) {
alert(text);
},
render: function() {
return <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />;
}
});
And there's no additional configuration required as you hookup additional Child components
var Parent = React.createClass({
getInitialState: function () {
return {
text: "Click here",
text2: "No, Click here",
};
},
onClick: function (text) {
alert(text);
},
render: function() {
return <div>
<Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />
<Child onClick={this.onClick.bind(null, this.state.text2)} text={this.state.text2} />
</div>;
}
});
But I suspect that’s not your actual use case. So let’s dig further…
The generic nature of the provided example is a hard to talk about. I’ve created a component that demonstrations a practical use for the question above, implemented in a very Reacty way:
DTServiceCalculator working example
DTServiceCalculator repo
This component is a simple service calculator. You provide it with a list of services (with names and prices) and it will calculate a total the selected prices.
ServiceItem
is the child-component in this example. It doesn’t have many opinions about the outside world. It requires a few props, one of which is a function to be called when clicked.
<div onClick={this.props.handleClick.bind(this.props.index)} />
It does nothing but to call the provided handleClick
callback with the provided index
[source].
DTServicesCalculator
is the parent-component is this example. It’s also a child. Let’s look.
DTServiceCalculator
creates a list of child-component (ServiceItem
s) and provides them with props [source]. It’s the parent-component of ServiceItem
but it`s the child-component of the component passing it the list. It doesn't own the data. So it again delegates handling of the component to its parent-component source
<ServiceItem chosen={chosen} index={i} key={id} price={price} name={name} onSelect={this.props.handleServiceItem} />
handleServiceItem
captures the index, passed from the child, and provides it to its parent [source]
handleServiceClick (index) {
this.props.onSelect(index);
}
The concept of “Ownership” is an important one in React. I recommend reading more about it here.
In the example I’ve shown, I keep delegating handling of an event up the component tree until we get to the component that owns the state.
When we finally get there, we handle the state selection/deselection like so [source]:
handleSelect (index) {
let services = […this.state.services];
services[index].chosen = (services[index].chosen) ? false : true;
this.setState({ services: services });
}
Try keeping your outer-most components as opaque as possible. Strive to make sure that they have very few preferences about how a parent-component might choose to implement them.
Keep aware of who owns the data you are manipulating. In most cases, you will need to delegate event handling up the tree to the component that owns that state.
Aside: The Flux pattern is a good way to reduce this type of necessary hookup in apps.
I get this post is old but there have been changes to how select2 works now and the answer to this question is extremely simple.
To set the values in a multi select2 is as follows
$('#Books_Illustrations').val([1,2,3]).change();
There is no need to specify .select2
in jquery anymore, simply .val
Also there will be times you will not want to fire the change
event because you might have some other code that will execute which is what will happen if you use the method above so to get around that you can change the value without firing the change
event like so
$('#Books_Illustrations').select2([1,2,3], null, false);
When you working with JsonObject request you need to pass the parameters right after you pass the link in the initialization , take a look on this code :
HashMap<String, String> params = new HashMap<>();
params.put("user", "something" );
params.put("some_params", "something" );
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "request_URL", new JSONObject(params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Some code
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//handle errors
}
});
}
This is a basic example with comments. The upload
function is what you are looking for:
// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');
// This will upload the file after having read it
const upload = (file) => {
fetch('http://www.example.net', { // Your POST endpoint
method: 'POST',
headers: {
// Content-Type may need to be completely **omitted**
// or you may need something
"Content-Type": "You will perhaps need to define a content-type here"
},
body: file // This is your file object
}).then(
response => response.json() // if the response is a JSON object
).then(
success => console.log(success) // Handle the success response object
).catch(
error => console.log(error) // Handle the error response object
);
};
// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);
// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);
You can use this Autoit script to handle the login popup:
WinWaitActive("Authentication Required","","10")
If WinExists("Authentication Required") Then
Send("username{TAB}")
Send("Password{Enter}")
EndIf'
Mates,
I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this
try{
foo();
}
catch (exception $e)
{
echo "$e->getMessage()";
}
function foo(){
echo "blah blah blah";
}
so php was throwing me error "call to undefined function ".
This kinda seem classic programming error but may help someone in need of clue.
Look here for windows-specific way of getting full list of running processes with their IDs. It would be something like
from win32com.client import GetObject
def get_proclist():
WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')
return [process.Properties_('ProcessID').Value for process in processes]
You can then verify pid you get against this list. I have no idea about performance cost, so you'd better check this if you're going to do pid verification often.
For *NIx, just use mluebke's solution.
There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.
Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:
void remove_element(array_type *array, int index, int array_length)
{
int i;
for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}
Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:
remove_element(array, index, array_length); /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
/* No memory available */
exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;
realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.
Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.
This is the initial database of the data source when you connect.
Edited for clarity:
If you have multiple databases in your SQL Server instance and you don't want to use the default database, you need some way to specify which one you are going to use.
Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.
Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.
If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error
object given to the catch block has a stack
property that shows where the exception happened.
Same thing with gcc version 4.8.1 (GCC)
and libstdc++.so.6.0.18
. Had to copy it here /usr/lib/x86_64-linux-gnu
on my ubuntu box.
The problem is the OS can’t find Pip. Pip helps you install packages MODIFIED SOME GREAT ANSWERS TO BE BETTER
cd C:\Users\Username\AppData\Local\Programs\Python\Python37-32
In this directory, search pip with python -m pip then install package
python -m pip install ipywidgets
-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.
GO TO scripts from CMD. This is where Pip stays :)
cd C:\Users\User name\AppData\Local\Programs\Python\Python37-32\Scripts>
Then
pip install anypackage
No, you shouldn't call it explicitly because it would be called twice. Once for the manual call and another time when the scope in which the object is declared ends.
Eg.
{
Class c;
c.~Class();
}
If you really need to perform the same operations you should have a separate method.
There is a specific situation in which you may want to call a destructor on a dynamically allocated object with a placement new
but it doesn't sound something you will ever need.
Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html
It's just a matter of using curl
to trigger a Jenkins job using the git hooks provided by git.
The command
curl http://localhost:8080/job/someJob/build?delay=0sec
can run a Jenkins job, where someJob
is the name of the Jenkins job.
Search for the hooks
folder in your hidden .git folder. Rename the post-commit.sample
file to post-commit
. Open it with Notepad, remove the : Nothing
line and paste the above command into it.
That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.
SQL Developer seems to only output the DBMS_OUTPUT text when you have explicitly turned on the DBMS_OUTPUT window pane.
Go to (Menu) VIEW -> Dbms_output to invoke the pane.
Click on the Green Plus sign to enable output for your connection and then run the code.
EDIT: Don't forget to set the buffer size according to the amount of output you are expecting.
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
You can use the setText()
method. Example:
import android.widget.Button;
Button p1_button = (Button)findViewById(R.id.Player1);
p1_button.setText("Some text");
Also, just as a point of reference, Button extends TextView, hence why you can use setText()
just like with an ordinary TextView.
I do it this way:
The html:
<head>
<style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>
The xCss.php:
<? // place here your vars
$fntBtn = 'bold 14px Arial'
$colBorder = '#556677' ;
$colBG0 = '#dddddd' ;
$colBG1 = '#44dddd' ;
$colBtn = '#aadddd' ;
// here goes your css after the php-close tag:
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; }
A move from WebForms to MVC requires a complete sea-change in logic and brain processes. You're no longer interacting with the 'form' both server-side and client-side (and in fact even with WebForms you weren't interacting client-side). You've probably just mixed up a bit of thinking there, in that with WebForms and RUNAT="SERVER"
you were merely interacting with the building of the Web page.
MVC is somewhat similar in that you have server-side code in constructing the model (the data you need to build what your user will see), but once you have built the HTML you need to appreciate that the link between the server and the user no longer exists. They have a page of HTML, that's it.
So the HTML you are building is read-only. You pass the model through to the Razor page, which will build HTML appropriate to that model.
If you want to have a hidden element which sets true or false depending on whether this is the first view or not you need a bool in your model, and set it to True in the Action if it's in response to a follow up. This could be done by having different actions depending on whether the request is [HttpGet] or [HttpPost] (if that's appropriate for how you set up your form: a GET request for the first visit and a POST request if submitting a form).
Alternatively the model could be set to True when it's created (which will be the first time you visit the page), but after you check the value as being True or False (since a bool defaults to False when it's instantiated). Then using:
@Html.HiddenFor(x => x.HiddenPostBack)
in your form, which will put a hidden True. When the form is posted back to your server the model will now have that value set to True.
It's hard to give much more advice than that as your question isn't specific as to why you want to do this. It's perhaps vital that you read a good book on moving to MVC from WebForms, such as Steve Sanderson's Pro ASP.NET MVC.
The following also works:
cd "${0%/*}"
The syntax is thoroughly described in this StackOverflow answer.
You don't need initialization lists for that:
std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);
here the link to webreports version 12 https://www.nuget.org/packages/Microsoft.ReportViewer.WebForms.v12/12.0.0?_src=template
after the package installed
on your toolbox browse the dll reference it to bin then that's it run the visual studio
You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/
vs https/
, www.
vs no www.
, etc).
For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms
)
Note that path prefix is optional.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="www.docs.google.com" />
<data android:host="docs.google.com" />
<data android:pathPrefix="/forms" />
</intent-filter>
If we get the value as int
and we set it to String
, the error occurs. PFB my solution,
Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));
In laravel 7, to set current time use following:
$table->timestamp('column_name')->useCurrent();
The code points used in icon font tricks are usually Private Use code points, which means that they have no generally defined meaning and should not be used in open information interchange, only by private agreement between interested parties. However, Private Use code points can be represented as any other Unicode value, e.g. in CSS using a notation like \f066
, as others have answered. You can even enter the code point as such, if your document is UTF-8 encoded and you know how to type an arbitrary Unicode value by its number in your authoring environment (but of course it would normally be displayed using a symbol for an unknown character).
However, this is not the normal way of using icon fonts. Normally you use a CSS file provided with the font and use constructs like <span class="icon-resize-small">foo</span>
. The CSS code will then take care of inserting the symbol at the start of the element, and you don’t need to know the code point number.
It's far from perfect, but it does the job.
data = data.replace(',"',',\n"')
you can improve it, add indenting and so on, but if you just want to be able to read a cleaner json, this is the way to go.
Raymond Chen has a few ideas:
https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573
Quoted here in full because MSDN archives tend to be somewhat unreliable:
The easy way is to use the
%CD%
pseudo-variable. It expands to the current working directory.
set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory
(Of course, directory save/restore could more easily have been done with
pushd
/popd
, but that's not the point here.)The
%CD%
trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.
set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args
(I like to use
%_%
as my scratch environment variable.)Type
SET /?
to see the other pseudo-variables provided by the command processor.
Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):
http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741
This covers the use of %~dp0:
If you want to know where the batch file lives:
%~dp0
%0
is the name of the batch file.~dp
gives you the drive and path of the specified argument.
On Windows you do not link with a .dll
file directly – you must use the accompanying .lib
file instead. To do that go to Project -> Properties -> Configuration Properties -> Linker -> Additional Dependencies
and add path to your .lib as a next line.
You also must make sure that the .dll
file is either in the directory contained by the %PATH%
environment variable or that its copy is in Output Directory
(by default, this is Debug\Release
under your project's folder).
If you don't have access to the .lib
file, one alternative is to load the .dll
manually during runtime using WINAPI functions such as LoadLibrary and GetProcAddress.
I think Dan and Nicola have suitable corrected code, however you may not be clear on why the original code didn't work.
What has been called here a "ternary operator" is called a conditional operator in ECMA-262 section 11.12. It has the form:
LogicalORExpression ? AssignmentExpression : AssignmentExpression
The LogicalORExpression is evaluated and the returned value converted to Boolean (just like an expression in an if condition). If it evaluates to true, then the first AssignmentExpression is evaluated and the returned value returned, otherwise the second is evaluated and returned.
The error in the original code is the extra semi-colons that change the attempted conditional operator into a series of statements with syntax errors.
You can have one alternative of using placeholders as:
@Query("Select c from Registration c where c.place LIKE %?1%")
List<Registration> findPlaceContainingKeywordAnywhere(String place);
If you working with in-memory data (read "collections of POCO") you may also stack your expressions together using PredicateBuilder like so:
// initial "false" condition just to start "OR" clause with
var predicate = PredicateBuilder.False<YourDataClass>();
if (condition1)
{
predicate = predicate.Or(d => d.SomeStringProperty == "Tom");
}
if (condition2)
{
predicate = predicate.Or(d => d.SomeStringProperty == "Alex");
}
if (condition3)
{
predicate = predicate.And(d => d.SomeIntProperty >= 4);
}
return originalCollection.Where<YourDataClass>(predicate.Compile());
The full source of mentioned PredicateBuilder
is bellow (but you could also check the original page with a few more examples):
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T> () { return f => true; }
public static Expression<Func<T, bool>> False<T> () { return f => false; }
public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
}
}
Note: I've tested this approach with Portable Class Library project and have to use .Compile()
to make it work:
Where(predicate .Compile() );
While Dictionary is implemented as a hash table, SortedDictionary is implemented as a Red-Black Tree.
If you don't take advantage of the order in your algorithm and only need to sort the data before output, using SortedDictionary would have negative impact on performance.
You can "sort" the dictionary like this:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// algorithm
return new SortedDictionary<string, int>(dictionary);
If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:
public object this[int i] => this.InnerList[i];
This error has occurred when i was importing a project from Github. This happens as the project was of older version. Just try to delete these methods below from your root gradle.
android { compileSdkVersion 19 buildToolsVersion "19.1" }
then try again.
I hope it works.
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
I found the answer here: Is it possible to pass query parameters via Django's {% url %} template tag?
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
[there is nothing else to improve but I'm getting a stupid error when I fix the code ticks]
Tablets supports tvdpi and for that scaling factor is 1.33 times dimensions of medium dpi
ldpi | mdpi | tvdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
0.75 | 1 | 1.33 | 1.5 | 2 | 3 | 4
This means that if you generate a 400x400 image for xxxhdpi devices, you should generate the same resource in 300x300 for xxhdpi, 200x200 for xhdpi, 133x133 for tvdpi, 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices
This problem appeared for me when I was creating folders in the filesystem (not in my solution) and moved some projects around.
Turns out that the package paths are relative from the csproj files. So I had to change the "HintPath" of my references:
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
To:
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
Notice the double "..\" in 'HintPath'.
I also had to change my error conditions, for example I had to change:
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
To:
<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
Again, notice the double "..\".
SELECT
MyParts.*,MyPriceDate.Price,MyPriceDate.PriceDate
FROM MyParts
INNER JOIN (SELECT Partid, MAX(PriceDate) AS MaxPriceDate FROM MyPrice GROUP BY Partid) dt ON MyParts.Partid = dt.Partid
INNER JOIN MyPrice ON dt.Partid = MyPrice.Partid AND MyPrice.PriceDate=dt.MaxPriceDate
You can do this faster using a nearly optimal trial division sieve in one (long) line like this:
Enumerable.Range(0, Math.Floor(2.52*Math.Sqrt(num)/Math.Log(num))).Aggregate(
Enumerable.Range(2, num-1).ToList(),
(result, index) => {
var bp = result[index]; var sqr = bp * bp;
result.RemoveAll(i => i >= sqr && i % bp == 0);
return result;
}
);
The approximation formula for number of primes used here is p(x) < 1.26 x / ln(x)
. We only need to test by primes not greater than x = sqrt(num)
.
Note that the sieve of Eratosthenes has much better run time complexity than trial division (should run much faster for bigger num
values, when properly implemented).
Even better:
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Taken from: https://docs.python.org/3/howto/sorting.html
To use the parent of an element use parentElement
:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
map[key] = value
is provided for easier syntax. It is easier to read and write.
The reason for which you need to have default constructor is that map[key]
is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[]
.
There's much simpler solution today — pem. This tool makes life much easier.
For example, to generate or renew your push notification certificate just enter:
fastlane pem
and it's done in under a minute. In case you need a sandbox certificate, enter:
fastlane pem --development
And that's pretty it.
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
The general format, from the @link section of the javadoc documentation, is:
Method in the same class:
/** See also {@link #myMethod(String)}. */
void foo() { ... }
Method in a different class, either in the same package or imported:
/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }
Method in a different package and not imported:
/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }
Label linked to method, in plain text rather than code font:
/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }
A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz()
. But these labels can be fragile during refactoring -- see "Labels" below.
/**
* A convenience method, equivalent to
* {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
* @return baz
*/
public Baz fooBarBaz()
Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.
Therefore, provide a label only if you want different text than the default.
For example, you might link from human language to code:
/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }
Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.
If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:
int bar( Collection<Integer> receiver ) { ... }
/** See also {@link #bar(Collection)}. */
void foo() { ... }
I am using in the way and it is working for me.
public static void main(String[] args) {
new CarpoolDBAppTest();
}
public CarpoolDBAppTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Student stud = (Student) context.getBean("yourBeanId");
}
Here Student is my classm you will get the class matching yourBeanId.
Now work on that object with whatever operation you want to do.
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
I had the same problem.please do the following it may help you: By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.
To Change the LVT:
Click OK to save it.
yes you can, just set the NODE_PATH env variable :
export NODE_PATH='yourdir'/node_modules
According to the doc :
If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)
Additionally, node will search in the following locations:
1: $HOME/.node_modules
2: $HOME/.node_libraries
3: $PREFIX/lib/node
Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.
These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.
i got some problems with dynamic refresh of my listview.
Call notifyDataSetChanged() on your Adapter.
Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.
notifyDataSetChanged() did not work properly in my case[ I called the notifyDataSetChanged from another class]. Just in the case i edited the ListView in the running Activity (Thread). That video thanks to Christopher gave the final hint.
In my second class i used
Runnable run = new Runnable(){
public void run(){
contactsActivity.update();
}
};
contactsActivity.runOnUiThread(run);
to acces the update() from my Activity. This update includes
myAdapter.notifyDataSetChanged();
to tell the Adapter to refresh the view. Worked fine as far as I can say.
I think it helps to think of the "else" as the word OTHERWISE.
so you would read it like this:
if (something is true)
{
// do stuff
}
otherwise if (some other thing is true)
{
// do some stuff
}
otherwise
{
// do some other stuff :)
}
HTML:
<textarea rows="10" cols="20" id="text"></textarea>
CSS:
#text
{
overflow-y:scroll;
}
mv
in unix-ish systems, move
in dos/windows.
e.g.
C:\> move c:\users\you\somefile.txt c:\temp\newlocation.txt
and
$ mv /home/you/somefile.txt /tmp/newlocation.txt
just give and text style whatever you want like :D HTML:
<a href="javascript:;" class="fa fa-trash" style="color:#d9534f;">
<span style="color:black;">Text Name</span>
</a>
You can use resolve
:
angular.module('app',[])
.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl : 'app/views/login.html',
controller : 'YourController',
controllerAs : 'Your',
resolve: {
factory : checkLoginRedirect
}
})
}
And, the function of the resolve:
function checkLoginRedirect($location){
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
if ($location.path() == "/"){
$location.path('dash');
}
return true;
}else{
// No user is signed in.
$location.path('/');
return false;
}
}
Firebase also has a method that helps you install an observer, I advise installing it inside a .run
:
.run(function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('User is signed in.');
} else {
console.log('No user is signed in.');
}
});
}
I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.
As others have stated, you can create and submit a form to download via a POST request. However, you don't have to do this manually.
One really simple library for doing exactly this is jquery.redirect. It provides an API similar to the standard jQuery.post
method:
$.redirect(url, [values, [method, [target]]])
I think --include
is used to include a subset of files that are otherwise excluded by --exclude
, rather than including only those files.
In other words: you have to think about include meaning don't exclude.
Try instead:
rsync -zarv --include "*/" --exclude="*" --include="*.sh" "$from" "$to"
For rsync version 3.0.6 or higher, the order needs to be modified as follows (see comments):
rsync -zarv --include="*/" --include="*.sh" --exclude="*" "$from" "$to"
Adding the -m
flag will avoid creating empty directory structures in the destination. Tested in version 3.1.2.
So if we only want *.sh files we have to exclude all files --exclude="*"
, include all directories --include="*/"
and include all *.sh files --include="*.sh"
.
You can find some good examples in the section Include/Exclude Pattern Rules of the man page
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
scp -r C:/site user@server_ip:path
path
is the place, where site
will be copied into the remote server
EDIT: As I said in my comment, try pscp
, as you want to use scp
using PuTTY
.
The other option is WinSCP
Alternatively you could update brew
by installing it again. (Think I did this as El Capitan changed something)
Note: this is a heavy handed approach that will remove all applications installed via brew!
Try to install brew a fresh and it will tell how to uninstall.
At original time of writing to uninstall:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Edit: As of 2020 to uninstall:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
After you tried Clean and Rebuild without success, check your res
folder for corrupted files.
In my case a corrupted .png
file caused all the trouble.
A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes
if (c == '\n')
While many of the other answers provide good examples of why you might want to catch an rethrow an exception, no one seems to have mentioned a 'finally' scenario.
An example of this is where you have a method in which you set the cursor (for example to a wait cursor), the method has several exit points (e.g. if () return;) and you want to ensure the cursor is reset at the end of the method.
To do this you can wrap all of the code in a try/catch/finally. In the finally set the cursor back to the right cursor. So that you don't bury any valid exceptions, rethrow it in the catch.
try
{
Cursor.Current = Cursors.WaitCursor;
// Test something
if (testResult) return;
// Do something else
}
catch
{
throw;
}
finally
{
Cursor.Current = Cursors.Default;
}
declare @counter as int
set @counter = 0
declare @date as varchar(50)
set @date = cast(1+@counter as varchar)+'/01/2013'
while(@counter < 12)
begin
select cast(1+@counter as varchar)+'/01/2013' as date
set @counter = @counter + 1
end
First create the database and table, manually adding the columns. In which column to be primary key. You should right click this column and set primary key and set the seed value of the primary key.
1.save your file name as hey.py with the below given hello world script
#! /usr/bin/python
print('Hello, world!')
2.open the terminal in that directory
$ python hey.py
or if you are using python3 then
$ python3 hey.py
If you have a rooted device you can use kill
command
Connect to your device with adb:
adb shell
Once the session is established, you have to escalade privileges:
su
Then
ps
will list running processes. Note down the PID of the process you want to terminate. Then get rid of it
kill PID
HERE A VERY IMPORTANT ANSWER:
You just change your API URL String (in your method) from https to http.. This could also be the cause:
client.resource("http://192.168.0.100:8023/jaxrs/tester/tester");
instead of
client.resource("https://192.168.0.100:8023/jaxrs/tester/tester");
In the case you have different sample sizes, it may be difficult to compare the distributions with a single y-axis. For example:
import numpy as np
import matplotlib.pyplot as plt
#makes the data
y1 = np.random.normal(-2, 2, 1000)
y2 = np.random.normal(2, 2, 5000)
colors = ['b','g']
#plots the histogram
fig, ax1 = plt.subplots()
ax1.hist([y1,y2],color=colors)
ax1.set_xlim(-10,10)
ax1.set_ylabel("Count")
plt.tight_layout()
plt.show()
In this case, you can plot your two data sets on different axes. To do so, you can get your histogram data using matplotlib, clear the axis, and then re-plot it on two separate axes (shifting the bin edges so that they don't overlap):
#sets up the axis and gets histogram data
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.hist([y1, y2], color=colors)
n, bins, patches = ax1.hist([y1,y2])
ax1.cla() #clear the axis
#plots the histogram data
width = (bins[1] - bins[0]) * 0.4
bins_shifted = bins + width
ax1.bar(bins[:-1], n[0], width, align='edge', color=colors[0])
ax2.bar(bins_shifted[:-1], n[1], width, align='edge', color=colors[1])
#finishes the plot
ax1.set_ylabel("Count", color=colors[0])
ax2.set_ylabel("Count", color=colors[1])
ax1.tick_params('y', colors=colors[0])
ax2.tick_params('y', colors=colors[1])
plt.tight_layout()
plt.show()
An alternative way to rename files using the renamer npm package.
below is an example of renaming files extensions
renamer -d --path-element ext --find ts --replace js *
This works fine for me.
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++)
{
resourceId[i] = fields[i].getInt(drawableResources);
/* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
imageview.setImageResource(resourceId[any]);
}
This works:
sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"
Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)
Just keep in mind that:
obj= "foo"
is correct; obj="foo"
is not.PowerShell has aliases for several common commands like echo
. Type the following in PowerShell:
Get-Alias echo
to get a response:
CommandType Name Version Source
----------- ---- ------- ------
Alias echo -> Write-Output
Even Get-Alias has an alias gal -> Get-Alias
. You could write gal echo
to get the alias for echo
.
gal echo
Other aliases are listed here: https://docs.microsoft.com/en-us/powershell/scripting/learn/using-familiar-command-names?view=powershell-6
cat dir mount rm cd echo move rmdir chdir erase popd sleep clear h ps sort cls history pushd tee copy kill pwd type del lp r write diff ls ren
I tried this and it works perfectly
@Entity
public class Shipwreck {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
@Basic(optional = false)
@SequenceGenerator(name = "seq", sequenceName = "shipwreck_seq", allocationSize = 1)
Long id;
....
CREATE SEQUENCE public.shipwreck_seq
INCREMENT 1
START 110
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 1;
Note: if you were on Branch1
, you will with Git 2.0 (Q2 2014) be able to type:
git checkout Branch2
git rebase -
See commit 4f40740 by Brian Gesiak modocache
:
rebase
: allow "-
" short-hand for the previous branchTeach rebase the same shorthand as
checkout
andmerge
to name the branch torebase
the current branch on; that is, that "-
" means "the branch we were previously on".
This fixed node.js not running on port 80 under Windows 10 as well, I was getting a listen eacces
error. Start > Services, find "World Wide Web Publish Service" and disable it, exactly as paaacman described.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
framemain.setSize((int)width,(int)height);
framemain.setResizable(true);
framemain.setExtendedState(JFrame.MAXIMIZED_BOTH);
public static void main(String s[])
{
int firstArray[] = {2, 14, 6, 82, 22};
int secondArray[] = {3, 16, 12, 14, 48, 96};
int number = getCommonMinimumNumber(firstArray, secondArray);
System.out.println("The number is " + number);
}
public static int getCommonMinimumNumber(int firstSeries[], int secondSeries[])
{
Integer result =0;
if ( firstSeries.length !=0 && secondSeries.length !=0 )
{
series(firstSeries);
series(secondSeries);
one : for (int i = 0 ; i < firstSeries.length; i++)
{
for (int j = 0; j < secondSeries.length; j++)
if ( firstSeries[i] ==secondSeries[j])
{
result =firstSeries[i];
break one;
}
else
result = -999;
}
}
else if ( firstSeries == Null || secondSeries == null)
result =-999;
else
result = -999;
return result;
}
public static int[] series(int number[])
{
int temp;
boolean fixed = false;
while(fixed == false)
{
fixed = true;
for ( int i =0 ; i < number.length-1; i++)
{
if ( number[i] > number[i+1])
{
temp = number[i+1];
number[i+1] = number[i];
number[i] = temp;
fixed = false;
}
}
}
/*for ( int i =0 ;i< number.length;i++)
System.out.print(number[i]+",");*/
return number;
}
If you are using pm2, you can use it with autorestart
set to false
:
$ pm2 ecosystem
This will generate a sample ecosystem.config.js
:
module.exports = {
apps: [
{
script: './scripts/companies.js',
autorestart: false,
},
{
script: './scripts/domains.js',
autorestart: false,
},
{
script: './scripts/technologies.js',
autorestart: false,
},
],
}
$ pm2 start ecosystem.config.js
Here is how I solved this on ubuntu 18:
$ sudo docker ps -a
For each container do:
$ sudo docker stop container_ID
$ sudo docker rm container_ID
0 */6 * * *
crontab every 6 hours is a commonly used cron schedule.
The pointsize command scales the size of points, but does not affect the size of dots.
In other words, plot ... with points ps 2
will generate points of twice the normal size, but for plot ... with dots ps 2
the "ps 2
" part is ignored.
You could use circular points (pt 7
), which look just like dots.
Have you try changing your project name in package.json
and execute command git init
to reinitialize the existing Git, instead?
Your existing Git history will still exist.
From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is
DELETE FROM MainTable
WHERE PrimaryKey = ???
You database engine will take care of deleting the corresponding referencing records.
This fixed it for me:
brew upgrade node
you can use simply write the code in a .bat
format extension ,the code of the batch file :
c:/ copy /b Image1.jpg + Archive.rar Image2.jpg
use this c# code :
Process.Start("file_name.bat")
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
I am calling the json on login button click
@IBAction func loginClicked(sender : AnyObject) {
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
println("json2 :\(json2)")
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Success: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
return params
}
// You can add your own sets of parameter here.
When you get a UnicodeEncodeError
, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)
To avoid that, you must use explicit decoding.
If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.
def robust_decode(bs):
'''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
cr = None
try:
cr = bs.decode('utf8')
except UnicodeDecodeError:
cr = bs.decode('latin1')
return cr
If you do not know original encoding and do not care for non ascii character, you can set the optional errors
parameter of the decode
method to replace
. Any offending byte will be replaced (from the standard library documentation):
Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.
bs.decode(errors='replace')
:set runtimepath?
This lists the path of all plugins loaded when a file is opened with Vim.
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
There's no reason for not using database for login implementation, the very least you can do is to download and install SQLite if your hosting company does not provide you with enough DB.
A much simpler solution:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
and later in the code:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.
Shortest way to get all dictionary/object values:
Object.keys(dict).map(k => dict[k]);
You can also use printf to pipe the input to your script.
var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh
Try importing the Celery task in a Python Shell - Celery might silently be failing to register your tasks because of a bad import statement.
I had an ImportError
exception in my tasks.py file that was causing Celery to not register the tasks in the module. All other module tasks were registered correctly.
This error wasn't evident until I tried importing the Celery task within a Python Shell. I fixed the bad import statement and then the tasks were successfully registered.
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
@{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button').on("click", function(){
$.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.target').load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints
is your Action
with [HttpPost]
attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
I recommend adding the following line after the export to PDF:
ThisWorkbook.Sheets("Sheet1").Select
(where eg. Sheet1
is the single sheet you want to be active afterwards)
Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)
Already tested by me, it works fine
For i =0 To ListBox2.items.count - 1
ListBox2.Items.removeAt(0)
Next
**A full example of POM file**.
Command to Build All **Jrxml** to **Jasper File** in maven
If you used eclipse then right click on the project and Run as maven Build and add goals antrun:run@compile-jasper-reports
compile-jasper-reports is the id you gave in the pom file.
**<id>compile-jasper-reports</id>**
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.jasper</groupId>
<artifactId>testJasper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>TestJasper</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.3.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>compile-jasper-reports</id>
<goals>
<goal>run</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<target>
<echo message="Start compile of jasper reports" />
<mkdir dir="${project.build.directory}/classes/reports"/>
<echo message="${basedir}/src/main/resources/jasper/jasperreports" />
<taskdef name="jrc" classname="net.sf.jasperreports.ant.JRAntCompileTask"
classpathref="maven.compile.classpath" />
<jrc srcdir="${basedir}/src/main/resources/jasper/jasperreports" destdir="${basedir}/src/main/resources/jasper/jasperclassfile"
xmlvalidation="true">
<classpath refid="maven.compile.classpath"/>
<include name="**/*.jrxml" />
</jrc>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
private ArrayList ShuffleArrayList(ArrayList source)
{
ArrayList sortedList = new ArrayList();
Random generator = new Random();
while (source.Count > 0)
{
int position = generator.Next(source.Count);
sortedList.Add(source[position]);
source.RemoveAt(position);
}
return sortedList;
}
If you are targeting Windows XP (v140_xp
), try installing Windows XP Support for C++.
Starting with Visual Studio 2012, the default toolset (v110) dropped support for Windows XP. As a result, a Windows.h
error can occur if your project is targeting Windows XP with the default C++ packages.
Check which Windows SDK version is specified in your project's Platform Toolset. (Project ? Properties ? Configuration Properties ? General
). If your Toolset ends in _xp
, you'll need to install XP support.
Open the Visual Studio Installer and click Modify for your version of Visual Studio. Open the Individual Components tab and scroll down to Compilers, build tools, and runtimes. Near the bottom, check Windows XP support for C++ and click Modify to begin installing.
I prefer inline-block, although float is also useful. Table-cell isn't rendered correctly by old IEs (neither does inline-block, but there's the zoom: 1; *display: inline
hack that I use frequently). If you have children that have a smaller height than their parent, floats will bring them to the top, whereas inline-block will screw up sometimes.
Most of the time, the browser will interpret everything correctly, unless, of course, it's IE. You always have to check to make sure that IE doesn't suck-- for example, the table-cell concept.
In all reality, yes, it boils down to personal preference.
One technique you could use to get rid of white space would be to set a font-size
of 0 to the parent, then give the font-size
back to the children, although that's a hassle, and gross.
For the Python module import to work, you must have "src" in your path, not "gen_py/lib".
When processing an import like import gen_py.lib
, it looks for a module gen_py
, then looks for a submodule lib
.
As the module gen_py
won't be in "../gen_py/lib" (it'll be in ".."), the path you added will do nothing to help the import process.
Depending on where you're running it from, try adding the relative path to the "src" folder. Perhaps it's sys.path.append('..')
. You might also have success running the script while inside the src folder directly, via relative paths like python main/MyServer.py
In an empty directory:
git init
git remote add [REMOTE_NAME] [GIT_URL]
git fetch REMOTE_NAME
git checkout REMOTE_NAME/BRANCH -- path/to/directory
I was facing the same issue. I realised that I was using the Wrong provider class in persistence.xml
For Hibernate it should be
<provider>org.hibernate.ejb.HibernatePersistence</provider>
And for EclipseLink it should be
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
It's not a matter of pixels count, it's a matter of actual size (in mm or inches) of characters on the screen, which depends on pixels density. Hence "min-width:" and "max-width:" are useless. A full explanation of this issue is here: what exactly is device pixel ratio?
"@media" queries take into account the pixels count and the device pixel ratio, resulting in a "virtual resolution" which is what you have to actually take into account while designing your page: if your font is 10px fixed-width and the "virtual horizontal resolution" is 300 px, 30 characters will be needed to fill a line.
Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&
, >
, <
, '
, "
) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter  
in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.
This is my working code. Thanks to Paulo for the links. You create a custom error handler and call the trigger_error
function with the correct $errno
exception, even if it's not an error. Make sure you can write to the log file directory without administrator access.
<?php
$logfile_dir = "C:\workspace\logs\\"; // or "/var/log/" for Linux
$logfile = $logfile_dir . "php_" . date("y-m-d") . ".log";
$logfile_delete_days = 30;
function error_handler($errno, $errstr, $errfile, $errline)
{
global $logfile_dir, $logfile, $logfile_delete_days;
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting, so let it fall
// through to the standard PHP error handler
return false;
}
$filename = basename($errfile);
switch ($errno) {
case E_USER_ERROR:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "ERROR >> message = [$errno] $errstr\n", FILE_APPEND | LOCK_EX);
exit(1);
break;
case E_USER_WARNING:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "WARNING >> message = $errstr\n", FILE_APPEND | LOCK_EX);
break;
case E_USER_NOTICE:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "NOTICE >> message = $errstr\n", FILE_APPEND | LOCK_EX);
break;
default:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "UNKNOWN >> message = $errstr\n", FILE_APPEND | LOCK_EX);
break;
}
// delete any files older than 30 days
$files = glob($logfile_dir . "*");
$now = time();
foreach ($files as $file)
if (is_file($file))
if ($now - filemtime($file) >= 60 * 60 * 24 * $logfile_delete_days)
unlink($file);
return true; // Don't execute PHP internal error handler
}
set_error_handler("error_handler");
trigger_error("testing 1,2,3", E_USER_NOTICE);
?>
The date time you're passing is not a iso local date time format.
Change to
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
and pass date string in the format '2011-12-03T10:15:30'.
But if you still want to pass your custom format, use just have to specify the right formatter.
Change to
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
I think your problem is the @DateTimeFormat has no effect at all. As the jackson is doing the deseralization and it doesnt know anything about spring annotation and I dont see spring scanning this annotation in the deserialization context.
Alternatively, you can try setting the formatter while registering the java time module.
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
Here is the test case with the deseralizer which works fine. May be try to get rid of that DateTimeFormat annotation altogether.
@RunWith(JUnit4.class)
public class JacksonLocalDateTimeTest {
private ObjectMapper objectMapper;
@Before
public void init() {
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(module)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
@Test
public void test() throws IOException {
final String json = "{ \"date\": \"2016-11-08 12:00\" }";
final JsonType instance = objectMapper.readValue(json, JsonType.class);
assertEquals(LocalDateTime.parse("2016-11-08 12:00",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") ), instance.getDate());
}
}
class JsonType {
private LocalDateTime date;
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
}
I have used this command to troubleshoot client certificate negotiation:
openssl s_client -connect www.test.com:443 -prexit
The output will probably contain "Acceptable client certificate CA names" and a list of CA certificates from the server, or possibly "No client certificate CA names sent", if the server doesn't always require client certificates.
btnTest_Click(null, null);
Provided that the method isn't using either of these parameters (it's very common not to.)
To be honest though this is icky. If you have code that needs to be called you should follow the following convention:
protected void btnTest_Click(object sender, EventArgs e)
{
SomeSub();
}
protected void SomeOtherFunctionThatNeedsToCallTheCode()
{
SomeSub();
}
protected void SomeSub()
{
// ...
}
For anyone Googling this, one suggestion is to remove all the input-group
class instances. Worked for me in a similar situation. Original code:
<form>_x000D_
<div class="bs-callout">_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="form-group">_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" name="time" placeholder="Time">_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<div class="form-group">_x000D_
<div class="input-group">_x000D_
<select name="dtarea" class="form-control">_x000D_
<option value="1">Option value 1</option>_x000D_
</select>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="input-group">_x000D_
<input type="text" name="reason" class="form-control" placeholder="Reason">_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
New code:
<form>_x000D_
<div class="bs-callout">_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="form-group">_x000D_
<input type="text" class="form-control" name="time" placeholder="Time">_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<div class="form-group">_x000D_
<select name="dtarea" class="form-control">_x000D_
<option value="1">Option value 1</option>_x000D_
</select>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<input type="text" name="reason" class="form-control" placeholder="Reason">_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
Whenever I set debug="off" in my web.config and run my mvc4 application i would end up with ...
<script src="/bundles/jquery?v=<some long string>"></script>
in my html code and a JavaScript error
Expected ';'
There were 2 ways to get rid of the javascript error
BundleTable.EnableOptimizations = false
in BundleConfig.cs OR
Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])
1> Int(3.4)
$R1: Int = 3
I was trying something similar to ensure the -ggdb
flag was present.
Call make in a clean directory and grep the flag you are looking for. Looking for debug
rather than ggdb
I would just write.
make VERBOSE=1 | grep debug
The -ggdb
flag was obscure enough that only the compile commands popped up.
%s
indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s
converts a specified value to a string using the str()
function. Compare this with the %r
conversion type that uses the repr()
function for value conversion.
Take a look at the docs for string formatting.
Pymongo 3.9+
update()
is now deprecated and you should use replace_one()
, update_one()
, or update_many()
instead.
In my case I used update_many()
and it solved my issue:
db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)
From documents
update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=False, collation=None, session=None) filter: A query that matches the documents to update. update: The modifications to apply. upsert (optional): If True, perform an insert if no documents match the filter. bypass_document_validation (optional): If True, allows the write to opt-out of document level validation. Default is False. collation (optional): An instance of Collation. This option is only supported on MongoDB 3.4 and above. array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+. session (optional): a ClientSession.
If you need it only locally for local development, I've created utility exactly for this task - https://github.com/pie6k/easy-https
import { createHttpsDevServer } from 'easy-https';
async function start() {
const server = await createHttpsDevServer(
async (req, res) => {
res.statusCode = 200;
res.write('ok');
res.end();
},
{
domain: 'my-app.dev',
port: 3000,
subdomains: ['test'], // will add support for test.my-app.dev
openBrowser: true,
},
);
}
start();
It:
Well, to do it with eloquent you would do:
Blog:all();
From within your Model you do:
return DB::table('posts')->get();