You've only got a forward declaration for student
in the header file; you need to place the struct declaration in the header file, not the .cpp. The method definitions will be in the .cpp (assuming you have any).
Those extensions aren't really new, they are old. :-)
When C++ was new, some people wanted to have a .c++ extension for the source files, but that didn't work on most file systems. So they tried something close to that, like .cxx, or .cpp instead.
Others thought about the language name, and "incrementing" .c to get .cc or even .C in some cases. Didn't catch on that much.
Some believed that if the source is .cpp, the headers ought to be .hpp to match. Moderately successful.
Responding to MadKeithV's answer,
This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times, and also the amount of recompilation needed when something in the implementation changes.
Another reason is that a header gives a unique id to each class.
So if we have something like
class A {..};
class B : public A {...};
class C {
include A.cpp;
include B.cpp;
.....
};
We will have errors, when we try to build the project, since A is part of B, with headers we would avoid this kind of headache...
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
Check if you have anything like those stdio.h file and other header files under INCLUDE folder and LIB folder. LIB contains some files. In my case, I had the same issue but both of these folder were blank.. good to know. Steps:
This window will have values for INCLUDE and LIB directories. The by default value for these two boxes in the popup window are: Drive leter where you installed TC... i.e. C:\ or D:\ or whatever followed by the path for INCLUDE and LIB folder. So, in my case,
INCLUDE box was set to: "C:\TC\INCLUDE" and LIB directory value box was set to: "C:\TC\LIB" (without quotes). Steps to resolve:
Press ALT + C.
Sources telling you to use apstring.h are materials for the Advanced Placement course in computer science. It describes a string class that you'll use through the course, and some of the exam questions may refer to it and expect you to be moderately familiar with it. Unless you're enrolled in that class or studying to take that exam, ignore those sources.
Sources telling you to use string.h are either not really talking about C++, or are severely outdated. You should probably ignore them, too. That header is for the C functions for manipulating null-terminated arrays of characters, also known as C-style strings.
In C++, you should use the string header. Write #include <string>
at the top of your file. When you declare a variable, the type is string
, and it's in the std
namespace, so its full name is std::string
. You can avoid having to write the namespace portion of that name all the time by following the example of lots of introductory texts and saying using namespace std
at the top of the C++ source files (but generally not at the top of any header files you might write).
Your FMAT.h requires a definition of std::string in order to complete the definition of class FMAT. In FMAT.cpp, you've done this by #include <string>
before #include "FMAT.h"
. You haven't done that in your main file.
Your attempt to forward declare string
was incorrect on two levels. First you need a fully qualified name, std::string
. Second this works only for pointers and references, not for variables of the declared type; a forward declaration doesn't give the compiler enough information about what to embed in the class you're defining.
A popular Linux library which has similar functionality would be ncurses.
Here's a two-liner:
CPPFLAGS = -MMD
-include $(OBJS:.c=.d)
This works with the default make recipe, as long as you have a list of all your object files in OBJS
.
If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.
$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
__off_t __pos;
__off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;
If you look at the complete output you can even see the exact header file location and line number where it was defined:
# 132 "/usr/include/bits/types.h" 2 3 4
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
...
# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;
#include <filename>
is used when you want to use the header file of the C/C++ system or compiler libraries. These libraries can be stdio.h, string.h, math.h, etc.
#include "path-to-file/filename"
is used when you want to use your own custom header file which is in your project folder or somewhere else.
For more information about preprocessors and header. Read C - Preprocessors.
A/code.cpp
#include <B/file.hpp>
A/a/code2.cpp
#include <B/file.hpp>
Compile using:
g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp
Edit:
You can use environment variables to change the path g++ looks for header files. From man page:
Some additional environments variables affect the behavior of the preprocessor.
CPATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH
Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.
CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.
The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.
In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.
There are many ways you can change an environment variable. On bash prompt you can do this:
$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp
You can of course add this in your Makefile etc.
BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.
You could use an arbitrary count of arrays and map on the same index new objects.
var array1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],_x000D_
array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }],_x000D_
result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
The -I
directive does the job:
gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c
You can use the react-moment package
-> https://www.npmjs.com/package/react-moment
Put in your file the next line:
import moment from "moment";
date_create: moment().format("DD-MM-YYYY hh:mm:ss")
The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.
Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:
main.c:
#include "Enum.h"
CreateEnum(
EnumerationName,
ENUMValue1,
ENUMValue2,
ENUMValue3);
int main(void)
{
int i;
EnumerationName EnumInstance = ENUMValue1;
/* Prints "ENUMValue1" */
PrintEnumValue(EnumerationName, EnumInstance);
/* Prints:
* ENUMValue1
* ENUMValue2
* ENUMValue3
*/
for (i=0;i<3;i++)
{
PrintEnumValue(EnumerationName, i);
}
return 0;
}
Enum.h:
#include <stdio.h>
#include <string.h>
#ifdef NDEBUG
#define CreateEnum(name,...) \
typedef enum \
{ \
__VA_ARGS__ \
} name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
typedef enum \
{ \
__VA_ARGS__ \
} name; \
const char Lookup##name[] = \
#__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif
Enum.c
#include "Enum.h"
#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
char *lookup_copy;
int lookup_length;
char *pch;
lookup_length = strlen(lookup);
lookup_copy = malloc((1+lookup_length)*sizeof(char));
strcpy(lookup_copy, lookup);
pch = strtok(lookup_copy," ,");
while (pch != NULL)
{
if (value == 0)
{
printf("%s\n",pch);
break;
}
else
{
pch = strtok(NULL, " ,.-");
value--;
}
}
free(lookup_copy);
}
#endif
Disclaimer: don't do this.
$(document).ready(function() {
$(body).submit(function () {
var btn = $(this).find("input[type=submit]:focus");
if($(btn).prop("id") == "YourButtonID")
$(btn).attr("disabled", "true");
});
}
I've already commented it but I still think is a valid option, just test if in your environment is better one solution or the other. In my particular case, using source.ForEach(p => dest.Add(p))
performs better than the classic AddRange
but I've not investigated why at the low level.
You can see an example code here: https://gist.github.com/mcliment/4690433
So the option would be:
var allProducts = new List<Product>(productCollection1.Count +
productCollection2.Count +
productCollection3.Count);
productCollection1.ForEach(p => allProducts.Add(p));
productCollection2.ForEach(p => allProducts.Add(p));
productCollection3.ForEach(p => allProducts.Add(p));
Test it to see if it works for you.
Disclaimer: I'm not advocating for this solution, I find Concat
the most clear one. I just stated -in my discussion with Jon- that in my machine this case performs better than AddRange
, but he says, with far more knowledge than I, that this does not make sense. There's the gist if you want to compare.
For users of GitHub, this worked for me:
git reset --hard <full_hash_of_commit_to_reset_to>
git push --force
This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.
All everyone else needs to do is the git reset
command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.
In Celery 3+
http://docs.celeryproject.org/en/3.1/faq.html#how-do-i-purge-all-waiting-tasks
CLI
Purge named queue:
celery -A proj amqp queue.purge <queue name>
Purge configured queue
celery -A proj purge
I’ve purged messages, but there are still messages left in the queue? Answer: Tasks are acknowledged (removed from the queue) as soon as they are actually executed. After the worker has received a task, it will take some time until it is actually executed, especially if there are a lot of tasks already waiting for execution. Messages that are not acknowledged are held on to by the worker until it closes the connection to the broker (AMQP server). When that connection is closed (e.g. because the worker was stopped) the tasks will be re-sent by the broker to the next available worker (or the same worker when it has been restarted), so to properly purge the queue of waiting tasks you have to stop all the workers, and then purge the tasks using celery.control.purge().
So to purge the entire queue workers must be stopped.
split(delimiter)
by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit)
with limit
set to negative value like
String[] split = data.split("\\|", -1);
Little more details:
split(regex)
internally returns result of split(regex, 0)
and in documentation of this method you can find (emphasis mine)
The
limit
parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.If the limit
n
is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.If
n
is non-positive then the pattern will be applied as many times as possible and the array can have any length.If
n
is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Exception:
It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything)
since we can't split ""
farther we will get as result [""]
array.
It happens because split didn't happen here, so ""
despite being empty and trailing represents original string, not empty string which was created by splitting process.
<form action="" method="post" name="register_form" id="register_form" enctype="multipart/form-data">
<div class="text-input">
<label>Gender: </label>
<input class="form-control" type="radio" name="gender" id="male" value="male" />
<label for="male">Male</label>
<input class="form-control" type="radio" name="gender" id="female" value="female" />
<label for="female">Female</label>
</div>
<div class="text-input" align="center">
<input type="submit" name="register" value="Submit" onclick="return radioValidation();" />
</div>
</form>
<script type="text/javascript">
function radioValidation(){
var gender = document.getElementsByName('gender');
var genValue = false;
for(var i=0; i<gender.length;i++){
if(gender[i].checked == true){
genValue = true;
}
}
if(!genValue){
alert("Please Choose the gender");
return false;
}
}
</script>
Source: http://chandreshrana.blogspot.in/2016/11/radio-button-validation-in-javascript.html
My way is to use yappi (https://github.com/sumerc/yappi). It's especially useful combined with an RPC server where (even just for debugging) you register method to start, stop and print profiling information, e.g. in this way:
@staticmethod
def startProfiler():
yappi.start()
@staticmethod
def stopProfiler():
yappi.stop()
@staticmethod
def printProfiler():
stats = yappi.get_stats(yappi.SORTTYPE_TTOT, yappi.SORTORDER_DESC, 20)
statPrint = '\n'
namesArr = [len(str(stat[0])) for stat in stats.func_stats]
log.debug("namesArr %s", str(namesArr))
maxNameLen = max(namesArr)
log.debug("maxNameLen: %s", maxNameLen)
for stat in stats.func_stats:
nameAppendSpaces = [' ' for i in range(maxNameLen - len(stat[0]))]
log.debug('nameAppendSpaces: %s', nameAppendSpaces)
blankSpace = ''
for space in nameAppendSpaces:
blankSpace += space
log.debug("adding spaces: %s", len(nameAppendSpaces))
statPrint = statPrint + str(stat[0]) + blankSpace + " " + str(stat[1]).ljust(8) + "\t" + str(
round(stat[2], 2)).ljust(8 - len(str(stat[2]))) + "\t" + str(round(stat[3], 2)) + "\n"
log.log(1000, "\nname" + ''.ljust(maxNameLen - 4) + " ncall \tttot \ttsub")
log.log(1000, statPrint)
Then when your program work you can start profiler at any time by calling the startProfiler
RPC method and dump profiling information to a log file by calling printProfiler
(or modify the rpc method to return it to the caller) and get such output:
2014-02-19 16:32:24,128-|SVR-MAIN |-(Thread-3 )-Level 1000:
name ncall ttot tsub
2014-02-19 16:32:24,128-|SVR-MAIN |-(Thread-3 )-Level 1000:
C:\Python27\lib\sched.py.run:80 22 0.11 0.05
M:\02_documents\_repos\09_aheadRepos\apps\ahdModbusSrv\pyAheadRpcSrv\xmlRpc.py.iterFnc:293 22 0.11 0.0
M:\02_documents\_repos\09_aheadRepos\apps\ahdModbusSrv\serverMain.py.makeIteration:515 22 0.11 0.0
M:\02_documents\_repos\09_aheadRepos\apps\ahdModbusSrv\pyAheadRpcSrv\PicklingXMLRPC.py._dispatch:66 1 0.0 0.0
C:\Python27\lib\BaseHTTPServer.py.date_time_string:464 1 0.0 0.0
c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\_psmswindows.py._get_raw_meminfo:243 4 0.0 0.0
C:\Python27\lib\SimpleXMLRPCServer.py.decode_request_content:537 1 0.0 0.0
c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\_psmswindows.py.get_system_cpu_times:148 4 0.0 0.0
<string>.__new__:8 220 0.0 0.0
C:\Python27\lib\socket.py.close:276 4 0.0 0.0
C:\Python27\lib\threading.py.__init__:558 1 0.0 0.0
<string>.__new__:8 4 0.0 0.0
C:\Python27\lib\threading.py.notify:372 1 0.0 0.0
C:\Python27\lib\rfc822.py.getheader:285 4 0.0 0.0
C:\Python27\lib\BaseHTTPServer.py.handle_one_request:301 1 0.0 0.0
C:\Python27\lib\xmlrpclib.py.end:816 3 0.0 0.0
C:\Python27\lib\SimpleXMLRPCServer.py.do_POST:467 1 0.0 0.0
C:\Python27\lib\SimpleXMLRPCServer.py.is_rpc_path_valid:460 1 0.0 0.0
C:\Python27\lib\SocketServer.py.close_request:475 1 0.0 0.0
c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\__init__.py.cpu_times:1066 4 0.0 0.0
It may not be very useful for short scripts but helps to optimize server-type processes especially given the printProfiler
method can be called multiple times over time to profile and compare e.g. different program usage scenarios.
In newer versions of yappi, the following code will work:
@staticmethod
def printProfile():
yappi.get_func_stats().print_all()
$(document)[0].styleSheets[styleSheetIndex].insertRule(rule, lineIndex);
styleSheetIndex
is the index value that corresponds to which order you loaded the file in the <head>
(e.g. 0 is the first file, 1 is the next, etc. if there is only one CSS file, use 0).
rule
is a text string CSS rule. Like this: "body { display:none; }"
.
lineIndex
is the line number in that file. To get the last line number, use $(document)[0].styleSheets[styleSheetIndex].cssRules.length
. Just console.log
that styleSheet object, it's got some interesting properties/methods.
Because CSS is a "cascade", whatever rule you're trying to insert for that selector you can just append to the bottom of the CSS file and it will overwrite anything that was styled at page load.
In some browsers, after manipulating the CSS file, you have to force CSS to "redraw" by calling some pointless method in DOM JS like document.offsetHeight
(it's abstracted up as a DOM property, not method, so don't use "()") -- simply adding that after your CSSOM manipulation forces the page to redraw in older browsers.
So here's an example:
var stylesheet = $(document)[0].styleSheets[0];
stylesheet.insertRule('body { display:none; }', stylesheet.cssRules.length);
I have a similar experience and I believe that it might be the browser that is cutting the session short. I also set the maxIdleTimeout, but the session is dropped regardless. To me, it looks like it is the client (the browser) that is timing out the session and then hangs up.
Don't know how to work around it.
The accepted answer shows the reason for the deprecation but misses to name the alternative:
CellType getCellTypeEnum()
where the CellType
is the enum decribing the type of the cell.
The plan is to rename getCellTypeEnum()
back to getCellType()
in POI 4.0.
PLEASE NOTE: THE ANSWER BELOW IS HORRIBLY OUTDATED, AND MIGHT NOT BE ENTIRELY CORRECT ANYMORE.
You can program in C/C++ using the Android NDK. You'll have to wrap your c++ codebase in a static library and load that through a Java wrapper & JNI.
The standard NDK does not support RTTI and a lot of the functionality of standard c++ is also not available such as std::string, etc. To solve this you can recompile the NDK. Dmitry Moskalchuk supplies a modified version of the NDK that supports this at http://www.crystax.net/android/ndk-r3.php. This modified version works on all Android phones that run on an ARM processor.
Depending on the kind of application you should decide to use Java or C/C++. I'd use C/C++ for anything that requires above average computational power and games -- Java for the rest.
Just pick one language and write the majority of your application in that language; JNI calls can decrease your performance by a lot. Java isn't that hard though -- if you know how to program in C/C++. The advantage of Java is that the application can run on any device running Android, where as NDK applications depend on the architecture it was compiled for.
First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,
import myClass
or you can import the entire class and entire functions from the file. For example,
from myClass import
Finally, you need to create an instance of the class from the original file and call the instance objects.
Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay
. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.
The key excerpt to look at is:
# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)
learning_rate = tf.train.exponential_decay(
0.01, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
train_size, # Decay step.
0.95, # Decay rate.
staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
0.9).minimize(loss,
global_step=batch)
Note the global_step=batch
parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.
If you want to be able to call the func
with or without the parameter you can create a second func
of the same name which calls the other.
func test(firstThing: Int?) {
if firstThing != nil {
print(firstThing!)
}
print("done")
}
func test() {
test(firstThing: nil)
}
now you can call a function named test
without or without the parameter.
// both work
test()
test(firstThing: 5)
var oldDateObj = new Date();_x000D_
var newDateObj = new Date();_x000D_
newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));_x000D_
console.log(newDateObj);
_x000D_
Just create hide and show methods yourself for all elements, as follows
Element.prototype.hide = function() {
this.style.display = 'none';
}
Element.prototype.show = function() {
this.style.display = '';
}
After this you can use the methods with the usual element identifiers like in these examples:
document.getElementByTagName('div')[3].hide();
document.getElementById('thing').show();
or:
<img src="removeME.png" onclick="this.hide()">
If we also want to handle white spaces and unwanted tabs-
Check and Try the below script (Unit Tested)-
--Declaring
DECLARE @Tbl TABLE(col_1 VARCHAR(100));
--Test Samples
INSERT INTO @Tbl (col_1)
VALUES
(' EY y
Salem')
, (' EY P ort Chennai ')
, (' EY Old Park ')
, (' EY ')
, (' EY ')
,(''),(null),('d
f');
SELECT col_1 AS INPUT,
LTRIM(RTRIM(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(col_1,CHAR(10),' ')
,CHAR(11),' ')
,CHAR(12),' ')
,CHAR(13),' ')
,CHAR(14),' ')
,CHAR(160),' ')
,CHAR(13)+CHAR(10),' ')
,CHAR(9),' ')
,' ',CHAR(17)+CHAR(18))
,CHAR(18)+CHAR(17),'')
,CHAR(17)+CHAR(18),' ')
)) AS [OUTPUT]
FROM @Tbl;
I know this is extremely old, but I understand that this error type is a common mistake for beginners to make since most beginners will call their functions upon their header element being loaded. Seeing as this solution is not addressed at all in this thread, I'll add it. It is very likely that this javascript function was placed before the actual html was loaded. Remember, if you immediately call your javascript before the document is ready then elements requiring an element from the document might find an undefined value.
I came across this error due to the improper closing of the statement,
@using (Html.BeginForm("DeleteSelected", "Employee", FormMethod.Post))
{
} //This curly bracket needed to be closed at the end.
In Index.cshtml view file.I didn't close the statement at the end of the program. instead, I ended up closing improperly and ran into this error.
I was sure there isn't a need of checking Controller ActionMethod code because I have returned the Controller method properly to the View. So It has to be the view that's not responding and met with similar Error.
DELETE Table1
FROM Table1
INNER JOIN Table2 ON Table1.ID = Table2.ID
Please note!!! You must use the following format when instantiating PHPMailer!
$mail = new PHPMailer(true);
If you don't exceptions are ignored and the only thing you'll get is an echo from the routine! I know this is well after this was created but hopefully it will help someone.
There is also one nice thing some people might not know about:
echo $(( a < b ? a : b ))
This code will print the smallest number out of a
and b
please do read observer pattern
listener interface
public interface OnEventListener {
void onEvent(EventResult er);
// or void onEvent(); as per your need
}
then in your class say Event
class
public class Event {
private OnEventListener mOnEventListener;
public void setOnEventListener(OnEventListener listener) {
mOnEventListener = listener;
}
public void doEvent() {
/*
* code code code
*/
// and in the end
if (mOnEventListener != null)
mOnEventListener.onEvent(eventResult); // event result object :)
}
}
in your driver class MyTestDriver
public class MyTestDriver {
public static void main(String[] args) {
Event e = new Event();
e.setOnEventListener(new OnEventListener() {
public void onEvent(EventResult er) {
// do your work.
}
});
e.doEvent();
}
}
The simple solution: Add the following to the very top of the php file you are requesting the data from.
header("Access-Control-Allow-Origin: *");
I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
<layer-list>
<item>
<shape android:shape="oval">
<solid android:color="#08000000"/>
<padding
android:bottom="3px"
android:left="3px"
android:right="3px"
android:top="3px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#09000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#10000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#11000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#12000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#13000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#14000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#15000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#16000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#17000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
</layer-list>
</item>
<item>
<shape android:shape="oval">
<solid android:color="?attr/colorPrimary"/>
</shape>
</item>
</layer-list>
In place of ?attr/colorPrimary
you can choose any color. Here's a screenshot of the result:
Click app/manifests/AndroidManifest.xml
You see android:icon="@mipmap/your image name"
Also change android:roundicon="@mipmap/your image name"
Example:
android:icon="@mipmap/image"
that's all
You can do this by comparing each field using the NULL-safe equals operator <=>
and then negating the result using NOT
.
The complete trigger would become:
DROP TRIGGER IF EXISTS `my_trigger_name`;
DELIMITER $$
CREATE TRIGGER `my_trigger_name` AFTER UPDATE ON `my_table_name` FOR EACH ROW
BEGIN
/*Add any fields you want to compare here*/
IF !(OLD.a <=> NEW.a AND OLD.b <=> NEW.b) THEN
INSERT INTO `my_other_table` (
`a`,
`b`
) VALUES (
NEW.`a`,
NEW.`b`
);
END IF;
END;$$
DELIMITER ;
(Based on a different answer of mine.)
They are used for different purposes and in fact have different operator precedences. The &&
and ||
operators are intended for Boolean conditions, whereas and
and or
are intended for control flow.
For example, the following is a Boolean condition:
if ($foo == $bar && $baz != $quxx) {
This differs from control flow:
doSomething() or die();
In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL
:
NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
base64String]];
return [NSData dataWithContentsOfURL:URL];
The question is quite old, but what about:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ( a | default({})).get('nested', {}).get('var','bar') }}"
It looks less cumbersome to me...
If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:
function getData(id, opt){
var data = voodooMagic(id, opt.parameters);
if (opt.callback!=undefined)
opt.callback.call(data);
return data;
}
getData(5, {parameters: "1,2,3", callback:
function(){for (i=0;i<=1;i--)alert("FAIL!");}
});
You can slice along the columns of a DataFrame
by referring to the names of each column in a list, like so:
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
data_ab = data[list('ab')]
data_cde = data[list('cde')]
Make sure you specify pass header=None
and add usecols=[3,6]
for the 4th and 7th columns.
This might help:
$("dropdownmenuname").click(function(e){
e.stopPropagation();
})
In MAC OS, just rebooted the computer and it worked after the reboot.
As @Tommy suggested, you should use update-alternatives
.
It assigns values to every software of a family, so that it defines the order in which the applications will be called.
It is used to maintain different versions of the same software on a system. In your case, you will be able to use several declinations of gcc
, and one will be favoured.
To figure out the current priorities of gcc, type in the command pointed out by @tripleee's comment:
update-alternatives --query gcc
Now, note the priority attributed to gcc-4.4
because you'll need to give a higher one to gcc-3.3
.
To set your alternatives, you should have something like this (assuming your gcc
installation is located at /usr/bin/gcc-3.3
, and gcc-4.4
's priority is less than 50):
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-3.3 50
--edit--
Finally, you can also use the interactive interface of update-alternatives
to easily switch between versions. Type update-alternatives --config gcc
to be asked to choose the gcc version you want to use among those installed.
--edit 2 --
Now, to fix the CXX environment variable systemwide, you need to put the line indicated by @DipSwitch's in your .bashrc
file (this will apply the change only for your user, which is safer in my opinion):
echo 'export CXX=/usr/bin/gcc-3.3' >> ~/.bashrc
If you can modify the client, then have it print out the remote reference and you will see what port it's using. E.g.
ServerApi server = (ServerApi) registry.lookup(ServerApi.RMI_NAME);
System.out.println("Got server handle " + server);
will produce something like:
Got server handle Proxy[ServerApi,RemoteObjectInvocationHandler[UnicastRef [liveRef: [endpoint:172.17.3.190:9001,objID:[-7c63fea8:...
where you can see the port is 9001. If the remote class is not specifying the port, then it will change across reboots. If you want to use a fixed port then you need to make sure the remote class constructor does something like:
super(rmiPort)
This is because the StreamReader
closes the underlying stream automatically when being disposed of. The using
statement does this automatically.
However, the StreamWriter
you're using is still trying to work on the stream (also, the using
statement for the writer is now trying to dispose of the StreamWriter
, which is then trying to close the stream).
The best way to fix this is: don't use using
and don't dispose of the StreamReader
and StreamWriter
. See this question.
using (var ms = new MemoryStream())
{
var sw = new StreamWriter(ms);
var sr = new StreamReader(ms);
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
Console.WriteLine(sr.ReadToEnd());
}
If you feel bad about sw
and sr
being garbage-collected without being disposed of in your code (as recommended), you could do something like that:
StreamWriter sw = null;
StreamReader sr = null;
try
{
using (var ms = new MemoryStream())
{
sw = new StreamWriter(ms);
sr = new StreamReader(ms);
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
Console.WriteLine(sr.ReadToEnd());
}
}
finally
{
if (sw != null) sw.Dispose();
if (sr != null) sr.Dispose();
}
DataFrame['Col_name'].replace("None", np.nan, inplace=True)
A minor simplification on the example by @naresh. Should deal with permission issues and offer some clarification.
$data = '<base64_encoded_string>';
$data = base64_decode($data);
$img = imagecreatefromstring($data);
header('Content-Type: image/png');
$file = '<path_to_home_or_user_directory>/decoded_images/test.png';
imagepng($img, $file);
imagedestroy($img);
Use StreamReader
and direct it to detect the encoding for you:
using (var reader = new System.IO.StreamReader(path, true))
{
var currentEncoding = reader.CurrentEncoding;
}
And use Code Page Identifiers https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx in order to switch logic depending on it.
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
Better for all background: url('../images/bg-menu-dropdown-top.png') left 20px top no-repeat !important;
Try to wrap wsdlLocation in wsdlUrls
<wsdlUrls>
<wsdlLocation>http://url</wsdlLocation>
</wsdlUrls>
Looking at the screen from the top, you get x and z axis.
Looking at the screen from the side, you get y and z axis.
Calculate the focal lengths of the top and side views, using trigonometry, which is the distance between the eye and the middle of the screen, which is determined by the field of view of the screen. This makes the shape of two right triangles back to back.
hw = screen_width / 2
hh = screen_height / 2
fl_top = hw / tan(?/2)
fl_side = hh / tan(?/2)
Then take the average focal length.
fl_average = (fl_top + fl_side) / 2
Now calculate the new x and new y with basic arithmetic, since the larger right triangle made from the 3d point and the eye point is congruent with the smaller triangle made by the 2d point and the eye point.
x' = (x * fl_top) / (z + fl_top)
y' = (y * fl_top) / (z + fl_top)
Or you can simply set
x' = x / (z + 1)
and
y' = y / (z + 1)
Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:
<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>
If you will invoke the script with source
, you can use return <x>
where <x>
will be the script exit status (use a non-zero value for error or false). But if you invoke an executable script (i.e., directly with its filename), the return statement will result in a complain (error message "return: can only `return' from a function or sourced script").
If exit <x>
is used instead, when the script is invoked with source
, it will result in exiting the shell that started the script, but an executable script will just terminate, as expected.
To handle either case in the same script, you can use
return <x> 2> /dev/null || exit <x>
This will handle whichever invocation may be suitable. That is assuming you will use this statement at the script's top level. I would advise against directly exiting the script from within a function.
Note: <x>
is supposed to be just a number.
In MYSQL server version: 5.0.27 i tried this and it worked fine for me check in your version
ALTER TABLE carmake
MODIFY `country` ENUM('Japan', 'USA', 'England', 'Australia', 'Germany', 'France', 'Italy', 'Spain', 'Czech Republic', 'China', 'South Korea', 'India', 'Sweden', 'Malaysia');
You have done it correctly. The pull request will automatically update. The process is:
The pull request will automatically add the new commits at the bottom of the pull request discussion (ie, it's already there, scroll down!)
This is an old question, but here's another way to do it.
You can modify the R code itself instead of the chunk options, by wrapping the source
call in suppressPackageStartupMessages()
, suppressMessages()
, and/or suppressWarnings()
. E.g:
```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```
You can also put those functions around your library()
calls inside the "source.R"
script.
$msg="You Enter Wrong Username OR Password"; $responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";
Check php.ini for auto session id.
If you enable it, you will have PHPSESSID in your cookies.
Without jQuery-UI accordion, one can simply do this:
<div class="section">
<div class="section-title">
Section 1
</div>
<div class="section-content">
Section 1 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
</div>
</div>
<div class="section">
<div class="section-title">
Section 2
</div>
<div class="section-content">
Section 2 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
</div>
</div>
And js
$( ".section-title" ).click(function() {
$(this).parent().find( ".section-content" ).slideToggle();
});
.selectmenu{_x000D_
_x000D_
-webkit-appearance: none; /*Removes default chrome and safari style*/_x000D_
-moz-appearance: none; /* Removes Default Firefox style*/_x000D_
background: #0088cc ;_x000D_
width: 200px; /*Width of select dropdown to give space for arrow image*/_x000D_
text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
text-overflow: ""; /*Removes default arrow from firefox*/ /*My custom style for fonts*/_x000D_
color: #FFF;_x000D_
border-radius: 2px;_x000D_
padding: 5px;_x000D_
border:0 !important;_x000D_
box-shadow: inset 0 0 5px rgba(000,000,000, 0.5);_x000D_
}_x000D_
.hideoption { display:none; visibility:hidden; height:0; font-size:0; }
_x000D_
Try this html_x000D_
_x000D_
<select class="selectmenu">_x000D_
<option selected disabled class="hideoption">Select language</option>_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
<option>Option 3</option>_x000D_
<option>Option 4</option>_x000D_
<option>Option 5</option>_x000D_
</select>
_x000D_
file_get_contents()
utilizes the fopen()
wrappers, therefore it is restricted from accessing URLs through the allow_url_fopen
option within php.ini.
You will either need to alter your php.ini to turn this option on or use an alternative method, namely cURL - by far the most popular and, to be honest, standard way to accomplish what you are trying to do.
This function does what you want, and performs a lot faster than the option suggested in the accepted answer :
var repeat = function(str, count) {
var array = [];
for(var i = 0; i <= count;)
array[i++] = str;
return array.join('');
}
You use it like this :
var repeatedCharacter = repeat("a", 10);
To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.
In modern browsers, you can now also do this :
var repeatedCharacter = "a".repeat(10) };
This option is even faster. However, unfortunately it doesn't work in any version of Internet explorer.
The numbers in the table specify the first browser version that fully supports the method :
If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.
SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;
if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }
As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!
DELETE
FROM m_productprice B
USING m_product C
WHERE B.m_product_id = C.m_product_id AND
C.upc = '7094' AND
B.m_pricelist_version_id='1000020';
or
DELETE
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND
m_product_id IN (SELECT m_product_id
FROM m_product
WHERE upc = '7094');
These steps are enough to solve most of the problems related to Gradle build in any way. These steps helped me solve this problem too.
Registering DLL for Fundsite
Outdated or missing comdlg32.ocx runtime library can be the problem of causing this error. Make sure comdlg32.ocx file is not corrupted otherwise Download the File comdlg32.ocx (~60 Kb Zip).
Download the file and extract the comdlg32.ocx to your the Windows\System32 folder or Windows\SysWOW64. In my case i started with Windows\System32 but it didn’t work at my end, so I again saved in Windows\SysWOW64.
Type following command from Start, Run dialog:“c:\windows>System32\regsvr32 Comdlg32.ocx “ or “c:\windows>SysWOW64\regsvr32 Comdlg32.ocx ”
Now Comdlg.ocx File is register and next step is to register the DLL
Copy the Fundsite.Text.Encoding. dll into .Net Framework folder for 64bit on below path C:\Windows\Microsoft.NET\Framework64\v2.0.50727
Then on command prompt and go to directory C:\Windows\Microsoft.NET\Framework64\v2.0.50727 and then run the following command as shown below.
This will register the dll successfully.
C:\Windows\Microsoft.net\framework64\v2.0.50727>regasm "Dll Name".dll
Remove the position: absolute; attribute in the style
You should take to consideration that $array1 + $array2 != $array2 + $array1
$array1 = array(
'11' => 'x1',
'22' => 'x1'
);
$array2 = array(
'22' => 'x2',
'33' => 'x2'
);
with $array1 + $array2
$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
and with $array2 + $array1
$array2 + $array1 = array(
'11' => 'x1',
'22' => 'x2',
'33' => 'x2'
);
Here is how I do it in Angular 7.3
// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {
form.reset();
Object.keys(form.controls).forEach(key => {
form.get(key).setErrors(null) ;
});
}
There was no need to call form.clearValidators()
Just install apt-get install php5-mysqlnd Restart Apache service apache2 restart
In this line:
for name, email, lastname in unpaidMembers.items():
unpaidMembers.items()
must have only two values per iteration.
Here is a small example to illustrate the problem:
This will work:
for alpha, beta, delta in [("first", "second", "third")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
This will fail, and is what your code does:
for alpha, beta, delta in [("first", "second")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
In this last example, what value in the list is assigned to delta
? Nothing, There aren't enough values, and that is the problem.
You can do this :
<table id="table_header">
<tr>
<td contenteditable="true">a</td>
<td contenteditable="true">b</td>
<td contenteditable="true">c</td>
</tr>
</table>
There are synchronous action creators and then there are asynchronous action creators.
A synchronous action creator is one that when we call it, it immediately returns an Action object with all the relevant data attached to that object and its ready to be processed by our reducers.
Asynchronous action creators is one in which it will require a little bit of time before it is ready to eventually dispatch an action.
By definition, anytime you have an action creator that makes a network request, it is always going to qualify as an async action creator.
If you want to have asynchronous action creators inside of a Redux application you have to install something called a middleware that is going to allow you to deal with those asynchronous action creators.
You can verify this in the error message that tells us use custom middleware for async actions.
So what is a middleware and why do we need it for async flow in Redux?
In the context of redux middleware such as redux-thunk, a middleware helps us deal with asynchronous action creators as that is something that Redux cannot handle out of the box.
With a middleware integrated into the Redux cycle, we are still calling action creators, that is going to return an action that will be dispatched but now when we dispatch an action, rather than sending it directly off to all of our reducers, we are going to say that an action will be sent through all the different middleware inside the application.
Inside of a single Redux app, we can have as many or as few middleware as we want. For the most part, in the projects we work on we will have one or two middleware hooked up to our Redux store.
A middleware is a plain JavaScript function that will be called with every single action that we dispatch. Inside of that function a middleware has the opportunity to stop an action from being dispatched to any of the reducers, it can modify an action or just mess around with an action in any way you which for example, we could create a middleware that console logs every action you dispatch just for your viewing pleasure.
There are a tremendous number of open source middleware you can install as dependencies into your project.
You are not limited to only making use of open source middleware or installing them as dependencies. You can write your own custom middleware and use it inside of your Redux store.
One of the more popular uses of middleware (and getting to your answer) is for dealing with asynchronous action creators, probably the most popular middleware out there is redux-thunk and it is about helping you deal with asynchronous action creators.
There are many other types of middleware that also help you in dealing with asynchronous action creators.
If the goal is to build an API that allow you to access your models in JSON format I recommend you to use the django-restframework
that is an enormously popular package within the Django community to achieve this type of tasks.
It include useful features such as Pagination, Defining Serializers, Nested models/relations and more. Even if you only want to do minor Javascript tasks and Ajax calls I would still suggest you to build a proper API using the Django Rest Framework instead of manually defining the JSON response.
I was trying to run selenium on Jenkins with Mocha framework using wdio. So following are the steps to solve this issue:-
Install google chrome
sudo apt-get update
sudo apt-get install google-chrome-stable
Install chrome-driver
wget http://chromedriver.storage.googleapis.com/2.23/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
Run following commands to start selenium web server
nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"
After this start you tests with wdio command
wdio wdio.conf.js
Vojta described the "Angular way", but if you really need to make this work, @urbanek recently posted a workaround using ng-init:
<input type="text" ng-model="rootFolders" ng-init="rootFolders='Bob'" value="Bob">
https://groups.google.com/d/msg/angular/Hn3eztNHFXw/wk3HyOl9fhcJ
Installing a newer release of IDEA Community (2018.3 instead of 2017.x) was solved my issue with same error but java version:11. Reimport hadn't worked for me. But it worth a try.
1) Go to Windows->Preferences->General->Keys
2) Select the command
"Generate Getters and Setters"
3) In the Binding
, press the shortcut to like to use (like Alt+Shift+G)
4) Click apply and you are good to go
Yes the second syntax is fine.
Have you tried using the SPF wizard? https://www.spfwizard.net/
It can quickly generate basic and complex SPF records.
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
Does <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" >
help?
Browser will take care of keeping aspect ratio intact.
i.e max-width
kicks in when image width is greater than height and its height will be calculated proportionally. Similarly max-height
will be in effect when height is greater than width.
You don't need any jQuery or javascript for this.
Supported by ie7+ and other browsers (http://caniuse.com/minmaxwh).
Just a note
The following arrays:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };
Will be compiled to:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };
I'll explain it in a simple way.
Generics defined at Class level are completely separate from the generics defined at the (static) method level.
class Greet<T> {
public static <T> void sayHello(T obj) {
System.out.println("Hello " + obj);
}
}
When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.
class Greet<T> {
public static <E> void sayHello(E obj) {
System.out.println("Hello " + obj);
}
}
Why the static method needs to have its own generics separate from those of the Class?
This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.
So, whenever you are calling the static method,
Greet.sayHello("Bob");
Greet.sayHello(123);
JVM interprets it as the following.
Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);
Both giving the same outputs.
Hello Bob
Hello 123
how about in vuejs how is it applicable?
function onClick() {_x000D_
var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
pdf.canvas.height = 72 * 11;_x000D_
pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
pdf.fromHTML(document.body);_x000D_
_x000D_
pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
I'm using a support widget Toolbar v7. So, in order to be able to delete or hide the Title we need to write this.
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//Remove¡ing title bar
getSupportActionBar().setDisplayShowTitleEnabled(false);
You can use the Windows API function ShellExecute
to do so:
Option Explicit
Private Declare Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal Operation As String, _
ByVal Filename As String, _
Optional ByVal Parameters As String, _
Optional ByVal Directory As String, _
Optional ByVal WindowStyle As Long = vbMinimizedFocus _
) As Long
Public Sub OpenUrl()
Dim lSuccess As Long
lSuccess = ShellExecute(0, "Open", "www.google.com")
End Sub
Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute
would execute any command with the user's permissions, also a format c:
would be executed if the user is an administrator.
You're close. You can strip the whitespace by using the replace
method like this:
$answer.replace(' ','')
There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
As gratitude to the timely help I got from here - a minor update to above.
$query = "UPDATE `db`.`table` SET `fieldname`= str_to_date( fieldname, '%d/%m/%Y')";
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
Do it in simple. According to documentation https://developer.android.com/training/data-storage/files
String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
picFile = new File(ProfileActivity.this.getCacheDir(),imageName);
and delete it after usage
picFile.delete()
findByInventoryIdIn(List<Long> inventoryIdList)
should do the trick.
The HTTP request parameter format would be like so:
Yes ?id=1,2,3
No ?id=1&id=2&id=3
The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn
is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn
and IsNotIn
.
You probably don't actually want to change your default Python.
Your distro installed a standard system Python in /usr/bin
, and may have scripts that depend on this being present, and selected by #! /usr/bin/env python
. You can usually get away with running Python 2.6 scripts in 2.7, but do you want to risk it?
On top of that, monkeying with /usr/bin
can break your package manager's ability to manage packages. And changing the order of directories in your PATH
will affect a lot of other things besides Python. (In fact, it's more common to have /usr/local/bin
ahead of /usr/bin
, and it may be what you actually want—but if you have it the other way around, presumably there's a good reason for that.)
But you don't need to change your default Python to get the system to run 2.7 when you type python
.
First, you can set up a shell alias:
alias python=/usr/local/bin/python2.7
Type that at a prompt, or put it in your ~/.bashrc
if you want the change to be persistent, and now when you type python
it runs your chosen 2.7, but when some program on your system tries to run a script with /usr/bin/env python
it runs the standard 2.6.
Alternatively, just create a virtual environment out of your 2.7 (or separate venvs for different projects), and do your work inside the venv.
The AT command would do that but that's what the Scheduled Tasks gui is for. Enter "help at" in a cmd window for details.
There may be another reason when your application will not update when you either change/add/remove shareId in AndroidManifiest.
"android:sharedUserId"
Please check that also.
To prevent would recommend to use sharedUserId in your application despite in your current requirement you need or now.
These are identical for printf
but different for scanf
. For printf
, both %d
and %i
designate a signed decimal integer. For scanf
, %d
and %i
also means a signed integer but %i
inteprets the input as a hexadecimal number if preceded by 0x
and octal if preceded by 0
and otherwise interprets the input as decimal.
I use Portecle, and it works like a charm.
PIE
makes Internet Explorer 6-9
capable of rendering several of the most useful CSS3
decoration features
................................................................................
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
//Class Name
public class ClassName {
//Make it runnable
public static void main(String args[]) throws MalformedURLException{
//Get the URL
URL img = this.getClass().getResource("src/Name.gif");
//Make it to a Icon
Icon icon = new ImageIcon(img);
//Make a new JLabel that shows "icon"
JLabel Gif = new JLabel(icon);
//Make a new Window
JFrame main = new JFrame("gif");
//adds the JLabel to the Window
main.getContentPane().add(Gif);
//Shows where and how big the Window is
main.setBounds(x, y, H, W);
//set the Default Close Operation to Exit everything on Close
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Open the Window
main.setVisible(true);
}
}
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
Serializable
transient
You write, "I know literally it's list of numbers and list of lists where all list contains only a number" but that's a bit of an unhelpful way to think about it.
The best way to think about NumPy arrays is that they consist of two parts, a data buffer which is just a block of raw elements, and a view which describes how to interpret the data buffer.
For example, if we create an array of 12 integers:
>>> a = numpy.arange(12)
>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
Then a
consists of a data buffer, arranged something like this:
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
and a view which describes how to interpret the data:
>>> a.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> a.dtype
dtype('int64')
>>> a.itemsize
8
>>> a.strides
(8,)
>>> a.shape
(12,)
Here the shape (12,)
means the array is indexed by a single index which runs from 0 to 11. Conceptually, if we label this single index i
, the array a
looks like this:
i= 0 1 2 3 4 5 6 7 8 9 10 11
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
If we reshape an array, this doesn't change the data buffer. Instead, it creates a new view that describes a different way to interpret the data. So after:
>>> b = a.reshape((3, 4))
the array b
has the same data buffer as a
, but now it is indexed by two indices which run from 0 to 2 and 0 to 3 respectively. If we label the two indices i
and j
, the array b
looks like this:
i= 0 0 0 0 1 1 1 1 2 2 2 2
j= 0 1 2 3 0 1 2 3 0 1 2 3
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
which means that:
>>> b[2,1]
9
You can see that the second index changes quickly and the first index changes slowly. If you prefer this to be the other way round, you can specify the order
parameter:
>>> c = a.reshape((3, 4), order='F')
which results in an array indexed like this:
i= 0 1 2 0 1 2 0 1 2 0 1 2
j= 0 0 0 1 1 1 2 2 2 3 3 3
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
which means that:
>>> c[2,1]
5
It should now be clear what it means for an array to have a shape with one or more dimensions of size 1. After:
>>> d = a.reshape((12, 1))
the array d
is indexed by two indices, the first of which runs from 0 to 11, and the second index is always 0:
i= 0 1 2 3 4 5 6 7 8 9 10 11
j= 0 0 0 0 0 0 0 0 0 0 0 0
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
and so:
>>> d[10,0]
10
A dimension of length 1 is "free" (in some sense), so there's nothing stopping you from going to town:
>>> e = a.reshape((1, 2, 1, 6, 1))
giving an array indexed like this:
i= 0 0 0 0 0 0 0 0 0 0 0 0
j= 0 0 0 0 0 0 1 1 1 1 1 1
k= 0 0 0 0 0 0 0 0 0 0 0 0
l= 0 1 2 3 4 5 0 1 2 3 4 5
m= 0 0 0 0 0 0 0 0 0 0 0 0
+-----------------------------------------------------------+
¦ 0 ¦ 1 ¦ 2 ¦ 3 ¦ 4 ¦ 5 ¦ 6 ¦ 7 ¦ 8 ¦ 9 ¦ 10 ¦ 11 ¦
+-----------------------------------------------------------+
and so:
>>> e[0,1,0,0,0]
6
See the NumPy internals documentation for more details about how arrays are implemented.
Since numpy.reshape
just creates a new view, you shouldn't be scared about using it whenever necessary. It's the right tool to use when you want to index an array in a different way.
However, in a long computation it's usually possible to arrange to construct arrays with the "right" shape in the first place, and so minimize the number of reshapes and transposes. But without seeing the actual context that led to the need for a reshape, it's hard to say what should be changed.
The example in your question is:
numpy.dot(M[:,0], numpy.ones((1, R)))
but this is not realistic. First, this expression:
M[:,0].sum()
computes the result more simply. Second, is there really something special about column 0? Perhaps what you actually need is:
M.sum(axis=0)
You can use this OnLoad or during fetch infos from DB
In HTML Add following code:
<div id="divLoading">
<p id="loading">
<img src="~/images/spinner.gif">
</p>
In CSS add following Code:
#divLoading {
margin: 0px;
display: none;
padding: 0px;
position: absolute;
right: 0px;
top: 0px;
width: 100%;
height: 100%;
background-color: rgb(255, 255, 255);
z-index: 30001;
opacity: 0.8;}
#loading {
position: absolute;
color: White;
top: 50%;
left: 45%;}
if you want to show and hide from JS:
document.getElementById('divLoading').style.display = 'none'; //Not Visible
document.getElementById('divLoading').style.display = 'block';//Visible
Preamble: I'm using NET 2.0;
The solution posted by Yiannis Leoussis is acceptable but I had some problem with it.
First, the static AppSettingsSection AppSettings = (AppSettingsSection)myDllConfig.GetSection("appSettings");
returns null. I had to change it to static AppSettingSection = myDllConfig.AppSettings;
Then the return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
doesn't have a catch for Exceptions. So I've changed it
try
{
return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
}
catch (Exception ex)
{
return default(T);
}
This works very well but if you have a different dll you have to rewrite every time the code for every assembly. So, this is my version for an Class to instantiate every time you need.
public class Settings
{
private AppSettingsSection _appSettings;
private NumberFormatInfo _nfi;
public Settings(Assembly currentAssembly)
{
UriBuilder uri = new UriBuilder(currentAssembly.CodeBase);
string configPath = Uri.UnescapeDataString(uri.Path);
Configuration myDllConfig = ConfigurationManager.OpenExeConfiguration(configPath);
_appSettings = myDllConfig.AppSettings;
_nfi = new NumberFormatInfo()
{
NumberGroupSeparator = "",
CurrencyDecimalSeparator = "."
};
}
public T Setting<T>(string name)
{
try
{
return (T)Convert.ChangeType(_appSettings.Settings[name].Value, typeof(T), _nfi);
}
catch (Exception ex)
{
return default(T);
}
}
}
For a config:
<add key="Enabled" value="true" />
<add key="ExportPath" value="c:\" />
<add key="Seconds" value="25" />
<add key="Ratio" value="0.14" />
Use it as:
Settings _setting = new Settings(Assembly.GetExecutingAssembly());
somebooleanvar = _settings.Setting<bool>("Enabled");
somestringlvar = _settings.Setting<string>("ExportPath");
someintvar = _settings.Setting<int>("Seconds");
somedoublevar = _settings.Setting<double>("Ratio");
Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Here's some code:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yy");
Date date = format1.parse("05/01/1999");
System.out.println(format2.format(date));
Output:
01-May-99
Jenkins Pipeline also provides the current build number as the property number
of the currentBuild
. It can be read as currentBuild.number
.
For example:
// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"
Other properties of currentBuild
are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.
You need to reduce an NP-Complete problem to the problem you have. If the reduction can be done in polynomial time then you have proven that your problem is NP-complete, if the problem is already in NP, because:
It is not easier than the NP-complete problem, since it can be reduced to it in polynomial time which makes the problem NP-Hard.
See the end of http://www.ics.uci.edu/~eppstein/161/960312.html for more.
In any programming language, be careful when using Nulls. The example above shows another issue. If you use a type of Nullable, that means that the variables instantiated from that type can hold the value System.DBNull.Value; not that it has changed the interpretation of setting the value to default using "= Nothing" or that the Object of the value can now support a null reference. Just a warning... happy coding!
You could create a separate class containing a value type. An object created from such a class would be a reference type, which could be assigned Nothing. An example:
Public Class DateTimeNullable
Private _value As DateTime
'properties
Public Property Value() As DateTime
Get
Return _value
End Get
Set(ByVal value As DateTime)
_value = value
End Set
End Property
'constructors
Public Sub New()
Value = DateTime.MinValue
End Sub
Public Sub New(ByVal dt As DateTime)
Value = dt
End Sub
'overridables
Public Overrides Function ToString() As String
Return Value.ToString()
End Function
End Class
'in Main():
Dim dtn As DateTimeNullable = Nothing
Dim strTest1 As String = "Falied"
Dim strTest2 As String = "Failed"
If dtn Is Nothing Then strTest1 = "Succeeded"
dtn = New DateTimeNullable(DateTime.Now)
If dtn Is Nothing Then strTest2 = "Succeeded"
Console.WriteLine("test1: " & strTest1)
Console.WriteLine("test2: " & strTest2)
Console.WriteLine(".ToString() = " & dtn.ToString())
Console.WriteLine(".Value.ToString() = " & dtn.Value.ToString())
Console.ReadKey()
' Output:
'test1: Succeeded()
'test2: Failed()
'.ToString() = 4/10/2012 11:28:10 AM
'.Value.ToString() = 4/10/2012 11:28:10 AM
Then you could pick and choose overridables to make it do what you need. Lot of work - but if you really need it, you can do it.
You've answered the question with this statement:
Cron calls this
.sh
every 2 minutes
Cron does not run in a terminal, so why would you expect one to be set?
The most common reason for getting this error message is because the script attempts to source the user's .profile
which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:
#!/bin/bash -p
Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.
If this is the entirety of the script, then the TERM
error is coming from something other than the plain content of the script.
if you have this kind of problem with ispconfig3 and got an error like this
open_basedir restriction in effect. File(/var/www/clients/client7/web15) is not within the allowed path(s):.........
To solve it (in my case) , just set PHP to SuPHP in the Website's panel of ispconfig3
Hope it helps someone :)
For dynamic SQL use:
'IN(' ||array_to_string(some_array, ',')||')'
DO LANGUAGE PLPGSQL $$
DECLARE
some_array bigint[];
sql_statement text;
BEGIN
SELECT array[1, 2] INTO some_array;
RAISE NOTICE '%', some_array;
sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
RAISE NOTICE '%', sql_statement;
END;
$$;
Result:
NOTICE: {1,2}
NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)
$filename= time()."pdf";
//$filelocation = "C://xampp/htdocs/Nilesh/Projects/mkGroup/admin/PDF";
$filelocation = "/pdf uplaod path/";
$fileNL = $filelocation."/".$filename;
$pdf->Output($fileNL,'F');
$pdf->Output($filename, 'S');
This deletes only files from ABC (sub-directories are untouched):
Arrays.stream(new File("C:/test/ABC/").listFiles()).forEach(File::delete);
This deletes only files from ABC (and sub-directories):
Files.walk(Paths.get("C:/test/ABC/"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(File::delete);
^ This version requires handling the IOException
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
As of December 2017, there have been some updates, e.g. the usage of android.hardware.Camera
is deprecated now. While the newer android.hardware.camera2
comes with handy things like a CameraManager
.
I personally like this example a lot, which makes use of this current API and works like a charm: https://github.com/googlesamples/android-Camera2Video
It also includes asking the user for the required permissions at start and features video preview before starting the video recording.
(In addition, I find the code really beautiful (and this is very rare for me ^^), but that's just my subjective opinion.)
If you can live with 01 for January instead of 1, then try...
d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")
You can check the docs for other formatting directives.
To remove specific key and element from hashmap use
hashmap.remove(key)
full source code is like
import java.util.HashMap;
public class RemoveMapping {
public static void main(String a[]){
HashMap hashMap = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : "+hashMap);
hashMap.remove(3);
System.out.println("Changed HashMap : "+hashMap);
}
}
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
I could do this (demo):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type="file" id="f" data-max-size="32154" />
<input type="submit" />
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][data-max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].size;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
</html>
For those who searches for an answer without parsing and loosing milliseconds,
given dt_obj
is a datetime:
python3 only, elegant
int(dt_obj.timestamp() * 1000)
both python2 and python3 compatible:
import time
int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)
I'm using GNU Make from the GnuWin32 project, see http://gnuwin32.sourceforge.net/ but there haven't been any updates for a while now, so I'm not sure on this project's status.
It's not good for several reasons:
eval
The simplest thing would be to add a name
attribute to your <a>
element, then you could do:
document.myelement.onclick = function() {
window.popup('/map/', 300, 300, 'map');
return false;
};
although modern best practise would be to use an id
instead of a name, and use addEventListener()
instead of using onclick
since that allows you to bind multiple functions to a single event.
I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.
But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js
).
var config = {
// TODO: Add common Configuration
module: {},
};
var fooConfig = Object.assign({}, config, {
name: "a",
entry: "./a/app",
output: {
path: "./a",
filename: "bundle.js"
},
});
var barConfig = Object.assign({}, config,{
name: "b",
entry: "./b/app",
output: {
path: "./b",
filename: "bundle.js"
},
});
// Return Array of Configurations
module.exports = [
fooConfig, barConfig,
];
If you have common configuration among them, you could use the extend library or Object.assign
in ES6 or {...}
spread operator in ES7.
simplified to one function:
function removeWhiteSpace($text)
{
$text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
$text = preg_replace('/([\s])\1+/', ' ', $text);
$text = trim($text);
return $text;
}
based on Danuel O'Neal answer.
Explain only shows how the optimizer thinks the query will execute.
To show the real plan, you will need to run the sql once. Then use the same session run the following:
@yoursql
select * from table(dbms_xplan.display_cursor())
This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".
Function Concat(myRange As Range, Optional myDelimiter As String) As String
Dim r As Range
Application.Volatile
For Each r In myRange
If Len(r.Text) Then
Concat = Concat & IIf(Concat <> "", myDelimiter, "") & r.Text
End If
Next
End Function
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
What I was looking for is a way to fetch the data
so I used this $data = $this->db->get('table_name')->result_array();
and then fetched my data just as you operate on array objects.
$data[0]['field_name']
No need to worry about type casting or anything just straight to the point.
So it worked for me.
This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.
Here is a good post on permanent generation.
I like the descriptions given for each space in Oracle's guide on JConsole:
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.
- Eden Space (heap): The pool from which memory is initially allocated for most objects.
- Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
- Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
- Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
- Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.
Remove the :iml file found in java and test folders inside the project and invalidate and restart .
It will ask can I remove the projects . Put Yes. The error will goes off.
I developed my own SQL Server 2016+ JSON parser a while ago. I use this in all my projects - very good performance. I hope it can help someone else too.
Full code of the function:
ALTER FUNCTION [dbo].[SmartParseJSON] (@json NVARCHAR(MAX))
RETURNS @Parsed TABLE (Parent NVARCHAR(MAX),Path NVARCHAR(MAX),Level INT,Param NVARCHAR(4000),Type NVARCHAR(255),Value NVARCHAR(MAX),GenericPath NVARCHAR(MAX))
AS
BEGIN
-- Author: Vitaly Borisov
-- Create date: 2018-03-23
;WITH crData AS (
SELECT CAST(NULL AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
,j.[Key] AS [Param],j.Value,j.Type
,j.[Key] AS [Path],0 AS [Level]
,j.[Key] AS [GenericPath]
FROM OPENJSON(@json) j
UNION ALL
SELECT CAST(d.Path AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
,j.[Key] AS [Param],j.Value,j.Type
,d.Path + CASE d.Type WHEN 5 THEN '.' WHEN 4 THEN '[' ELSE '' END + j.[Key] + CASE d.Type WHEN 4 THEN ']' ELSE '' END AS [Path]
,d.Level+1
,d.GenericPath + CASE d.Type WHEN 5 THEN '.' + j.[Key] ELSE '' END AS [GenericPath]
FROM crData d
CROSS APPLY OPENJSON(d.Value) j
WHERE ISJSON(d.Value) = 1
)
INSERT INTO @Parsed(Parent, Path, Level, Param, Type, Value, GenericPath)
SELECT d.Parent,d.Path,d.Level,d.Param
,CASE d.Type
WHEN 1 THEN CASE WHEN TRY_CONVERT(UNIQUEIDENTIFIER,d.Value) IS NOT NULL THEN 'UNIQUEIDENTIFIER' ELSE 'NVARCHAR(MAX)' END
WHEN 2 THEN 'INT'
WHEN 3 THEN 'BIT'
WHEN 4 THEN 'Array'
WHEN 5 THEN 'Object'
ELSE 'NVARCHAR(MAX)'
END AS [Type]
,CASE
WHEN d.Type = 3 AND d.Value = 'true' THEN '1'
WHEN d.Type = 3 AND d.Value = 'false' THEN '0'
ELSE d.Value
END AS [Value]
,d.GenericPath
FROM crData d
OPTION(MAXRECURSION 1000) /*Limit to 1000 levels deep*/
;
RETURN;
END
GO
Example of use:
DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath
FROM dbo.SmartParseJSON(@json) j;
Example of multilevel use:
DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
DROP TABLE IF EXISTS #ParsedData;
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath
INTO #ParsedData
FROM dbo.SmartParseJSON(@json) j;
SELECT COALESCE(p2.GenericPath,p.GenericPath) AS [GenericPath]
,COALESCE(p2.Param,p.Param) AS [Param]
,COALESCE(p2.Value,p.Value) AS [Value]
FROM #ParsedData p
LEFT JOIN #ParsedData p1 ON p1.Parent = p.Path AND p1.Level = 1
LEFT JOIN #ParsedData p2 ON p2.Parent = p1.Path AND p2.Level = 2
WHERE p.Level = 0
;
DROP TABLE IF EXISTS #ParsedData;
There are three issues here that need to be fixed:
First is that you are expecting synchronous behavior while using stdout asynchronously. All of the calls in your run_cmd
function are asynchronous, so it will spawn the child process and return immediately regardless of whether some, all, or none of the data has been read off of stdout. As such, when you run
console.log(foo.stdout);
you get whatever happens to be stored in foo.stdout at the moment, and there's no guarantee what that will be because your child process might still be running.
Second is that stdout is a readable stream, so 1) the data event can be called multiple times, and 2) the callback is given a buffer, not a string. Easy to remedy; just change
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, data){me.stdout=data;}
);
into
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, buffer){me.stdout+=buffer.toString();}
);
so that we convert our buffer into a string and append that string to our stdout variable.
Third is that you can only know you've received all output when you get the 'end' event, which means we need another listener and callback:
function run_cmd(cmd, args, cb, end) {
// ...
child.stdout.on('end', end);
}
So, your final result is this:
function run_cmd(cmd, args, cb, end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
child.stdout.on('data', function (buffer) { cb(me, buffer) });
child.stdout.on('end', end);
}
// Run C:\Windows\System32\netstat.exe -an
var foo = new run_cmd(
'netstat.exe', ['-an'],
function (me, buffer) { me.stdout += buffer.toString() },
function () { console.log(foo.stdout) }
);
Linq With Or Condition by using Lambda expression you can do as below
DataTable dtEmp = new DataTable();
dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));
dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);
var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
== 1 || emp.Field<int>("EmpID") == 2);
foreach (DataRow row in res2)
{
Label2.Text += "Emplyee ID: " + row[0] + " & Emplyee Name: " + row[1] + ", ";
}
You can try strtotime() and date() functions for output in minimum code and using standard way.
echo date('Y', strtotime('2068-06-15'));
For me, the offending xml files were missing the header line...
<?xml version="1.0" encoding="utf-8"?>
Adding that fixed it.
The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark"
and the property in code is FirstName
then use the Select method as follows
List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();
you can do like this in your typescript code
onNavigate(){
var location="https://google.com",
}
In your html code add an anchor tag and pass that variable(location)
<a href="{{location}}" target="_blank">Redirect Location</a>
Suppose you have url like this www.google.com
without http
and you are not getting redirected to the given url then add http://
to the location
like this
var location = 'http://'+ www.google.com
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
Pragma directives specify operating system or machine specific (x86 or x64 etc) compiler options. There are several options available. Details can be found in https://msdn.microsoft.com/en-us/library/d9x1s805.aspx
#pragma comment( comment-type [,"commentstring"] )
has this format.
Refer https://msdn.microsoft.com/en-us/library/7f0aews7.aspx for details about different comment-type.
#pragma comment(lib, "kernel32")
#pragma comment(lib, "user32")
The above lines of code includes the library names (or path) that need to be searched by the linker. These details are included as part of the library-search record in the object file.
So, in this case kernel.lib
and user32.lib
are searched by the linker and included in the final executable.
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
The is
operator in Python probably doesn't do what you expect. Instead of this:
if numpy.array_equal(tmp,universe_array) is True:
break
I would write it like this:
if numpy.array_equal(tmp,universe_array):
break
The is
operator tests object identity, which is something quite different from equality.
This is not possible in Lombok. Although it would be a really nice feature, it requires resolution to find the constructors of the super class. The super class is only known by name the moment Lombok gets invoked. Using the import statements and the classpath to find the actual class is not trivial. And during compilation you cannot just use reflection to get a list of constructors.
It is not entirely impossible but the results using resolution in val
and @ExtensionMethod
have taught us that is it hard and error-prone.
Disclosure: I am a Lombok developer.
I have used this wrapper (Recommended) written by google developers. Its super easy to use.
https://github.com/googlesamples/easypermissions
Function dealing with checking and ask for permission if required
public void locationAndContactsTask() {
String[] perms = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CONTACTS };
if (EasyPermissions.hasPermissions(this, perms)) {
// Have permissions, do the thing!
Toast.makeText(this, "TODO: Location and Contacts things", Toast.LENGTH_LONG).show();
} else {
// Ask for both permissions
EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
RC_LOCATION_CONTACTS_PERM, perms);
}
}
Happy coding :)
I was running into this error message because of <></>
being returned for some items in the array when instead null
needs to be returned.
In a private project a wrote this filter
angular.module('myApp')
.filter('isEmpty', function () {
var bar;
return function (obj) {
for (bar in obj) {
if (obj.hasOwnProperty(bar)) {
return false;
}
}
return true;
};
});
usage:
<p ng-hide="items | isEmpty">Some Content</p>
testing:
describe('Filter: isEmpty', function () {
// load the filter's module
beforeEach(module('myApp'));
// initialize a new instance of the filter before each test
var isEmpty;
beforeEach(inject(function ($filter) {
isEmpty = $filter('isEmpty');
}));
it('should return the input prefixed with "isEmpty filter:"', function () {
expect(isEmpty({})).toBe(true);
expect(isEmpty({foo: "bar"})).toBe(false);
});
});
regards.
Here is a little utility class that I created:
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Convenience utility to create a FilenameFilter, based on a list of extensions
*/
public class FileExtensionFilter implements FilenameFilter {
private Set<String> exts = new HashSet<String>();
/**
* @param extensions
* a list of allowed extensions, without the dot, e.g.
* <code>"xml","html","rss"</code>
*/
public FileExtensionFilter(String... extensions) {
for (String ext : extensions) {
exts.add("." + ext.toLowerCase().trim());
}
}
public boolean accept(File dir, String name) {
final Iterator<String> extList = exts.iterator();
while (extList.hasNext()) {
if (name.toLowerCase().endsWith(extList.next())) {
return true;
}
}
return false;
}
}
Usage:
String[] files = new File("myfile").list(new FileExtensionFilter("pdf", "zip"));
Reading an html page with urllib is fairly simple to do. Since you want to read it as a single string I will show you.
Import urllib.request:
#!/usr/bin/python3.5
import urllib.request
Prepare our request
request = urllib.request.Request('http://www.w3schools.com')
Always use a "try/except" when requesting a web page as things can easily go wrong. urlopen() requests the page.
try:
response = urllib.request.urlopen(request)
except:
print("something wrong")
Type is a great function that will tell us what 'type' a variable is. Here, response is a http.response object.
print(type(response))
The read function for our response object will store the html as bytes to our variable. Again type() will verify this.
htmlBytes = response.read()
print(type(htmlBytes))
Now we use the decode function for our bytes variable to get a single string.
htmlStr = htmlBytes.decode("utf8")
print(type(htmlStr))
If you do want to split up this string into separate lines, you can do so with the split() function. In this form we can easily iterate through to print out the entire page or do any other processing.
htmlSplit = htmlStr.split('\n')
print(type(htmlSplit))
for line in htmlSplit:
print(line)
Hopefully this provides a little more detailed of an answer. Python documentation and tutorials are great, I would use that as a reference because it will answer most questions you might have.
That's right, if you're on a mac(unix) you won't see .git in finder(the file browser). You can follow the directions above to delete and there are git commands that allow you to delete files as well(they are sometimes difficult to work with and learn, for example: on making a 'git rm -r ' command you might be prompted with a .git/ not found. Here is the git command specs:
usage: git rm [options] [--] ...
-n, --dry-run dry run
-q, --quiet do not list removed files
--cached only remove from the index
-f, --force override the up-to-date check
-r allow recursive removal
--ignore-unmatch exit with a zero status even if nothing matched
When I had to do this, deleting the objects and refs didn't matter. After I deleted the other files in the .git, I initialized a git repo with 'git init' and it created an empty repo.
Make the following changes in your Registry and it should work:
1.) .NET Framework strong cryptography registry keys
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
2.) Secure Channel (Schannel) TLS 1.2 registry keys
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
This is because according to CSS 2.1, the effect of position: relative
on table elements is undefined. Illustrative of this, position: relative
has the desired effect on Chrome 13, but not on Firefox 4. Your solution here is to add a div
around your content and put the position: relative
on that div
instead of the td
. The following illustrates the results you get with the position: relative
(1) on a div
good), (2) on a td
(no good), and finally (3) on a div
inside a td
(good again).
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="position:relative;">_x000D_
<span style="position:absolute; left:150px;">_x000D_
Absolute span_x000D_
</span>_x000D_
Relative div_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I have successfully used as shown below in Jenkinsfile:
steps {
script {
def reportPath = "${WORKSPACE}/target/report"
...
}
}
You can use jQuery's .text()
function.
For example:
From the jQuery documentation regarding the .text()
function:
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.
Previous Versions of the jQuery Documentation worded it this way (emphasis added):
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <).
LocalDateTime
is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime
doesn't have such information. That's why the error occured.
If you want time-zone information, you should use ZonedDateTime
.
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"
for latest Jquery. Simply:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
Coalesce will fold nulls into a default:
COALESCE (fieldName, '') <> ''
My solution based on Mahdi Hijazi answer, but without any custom views:
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:id="@+id/scrollVertical"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<WateverViewYouWant/>
</ScrollView>
</HorizontalScrollView>
final HorizontalScrollView hScroll = (HorizontalScrollView) value.findViewById(R.id.scrollHorizontal);
final ScrollView vScroll = (ScrollView) value.findViewById(R.id.scrollVertical);
vScroll.setOnTouchListener(new View.OnTouchListener() { //inner scroll listener
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
hScroll.setOnTouchListener(new View.OnTouchListener() { //outer scroll listener
private float mx, my, curX, curY;
private boolean started = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
curX = event.getX();
curY = event.getY();
int dx = (int) (mx - curX);
int dy = (int) (my - curY);
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (started) {
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
} else {
started = true;
}
mx = curX;
my = curY;
break;
case MotionEvent.ACTION_UP:
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
started = false;
break;
}
return true;
}
});
You can change the order of the scrollviews. Just change their order in layout and in the code. And obviously instead of WateverViewYouWant you put the layout/views you want to scroll both directions.
Simply use ImageButton View and set image for it:`
<ImageButton
android:id="@+id/searchImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:src="@android:drawable/ic_menu_search" />
The floor() method doesn't work for negative numbers. This works every time:
$num = 5.7;
$whole = (int) $num; // 5
$frac = $num - $whole; // .7
...also works for negatives (same code, different number):
$num = -5.7;
$whole = (int) $num; // -5
$frac = $num - $whole; // -.7
The connection string is not in AppSettings.
What you're looking for is in:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...
Can I just ask to compare based on the year and month?
You can. Here's a simple example using the AdventureWorks sample database...
DECLARE @Year INT
DECLARE @Month INT
SET @Year = 2002
SET @Month = 6
SELECT
[pch].*
FROM
[Production].[ProductCostHistory] pch
WHERE
YEAR([pch].[ModifiedDate]) = @Year
AND MONTH([pch].[ModifiedDate]) = @Month
I have not run into this problem personally, but try checking the following settings (File
-> Settings
or Alt+F7
):
Project Settings [name]
Inspections
- ensure that Android
and Android Lint
is checked, or alternately just set it back to default using the dropdown box at the top.
IDE Settings
Editor
-> Code Completion
- ensure the Autopopup code completion
is checked (and check the rest of the settings based on your preference.
I got same error. This is how it worked for me:
Worked perfectly!
I solved the same error with the Path.Combine(MapPath()) to get the physical file path instead of the http:/// www one.
There's a JS QrCode scanner, that works on mobile sites with a camera:
https://github.com/LazarSoft/jsqrcode
I have worked with it for one of my project and it works pretty good !
As suggested by A Star, I always use something along the lines of:
DATE(NOW()) - INTERVAL 1 MONTH
Similarly you can do:
NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY
and so on. Much easier than typing DATE_ADD
or DATE_SUB
all the time :)!
I ran into this issue and resolved it by removing the width styling I had used on the SVG:
.svg-div img {
width: 200px; /* removed this */
height: auto;
}
This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).
To avoid it, the browser check the Same-origin policy
Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:
Deleting the workspace and cache was not sufficient for me. I had to also restart the "Visual Studio Team Foundation Build Service Host" service.
Other posters gave some examples for situations in which you'd use daemon threads. My recommendation, however, is never to use them.
It's not because they're not useful, but because there are some bad side effects you can experience if you use them. Daemon threads can still execute after the Python runtime starts tearing down things in the main thread, causing some pretty bizarre exceptions.
More info here:
https://joeshaw.org/python-daemon-threads-considered-harmful/
https://mail.python.org/pipermail/python-list/2005-February/343697.html
Strictly speaking you never need them, it just makes implementation easier in some cases.
You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();
Building on alko's answer that almost worked for me, except for the filtering step (where I get: ValueError: cannot reindex from a duplicate axis
), here is the final solution I used:
# join the dataframes
united_data = pd.concat([data1, data2, data3, ...])
# group the data by the whole row to find duplicates
united_data_grouped = united_data.groupby(list(united_data.columns))
# detect the row indices of unique rows
uniq_data_idx = [x[0] for x in united_data_grouped.indices.values() if len(x) == 1]
# extract those unique values
uniq_data = united_data.iloc[uniq_data_idx]
You can have multiple <context:property-placeholder />
elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.
There are nice libraries which will handle everything and reduce your pain. For using it, just add two dependencies in gradle:
implementation 'com.intuit.ssp:ssp-android:1.0.5'
implementation 'com.intuit.sdp:sdp-android:1.0.5'
After that, use dimens
like this:
android:layout_marginTop="@dimen/_80sdp"
If you are using Jackson, then you can use the @JsonProperty
annotation to customize the name of a given JSON property.
Therefore, you just have to annotate the entity fields with the @JsonProperty
annotation and provide a custom JSON property name, like this:
@Entity
public class City {
@Id
@JsonProperty("value")
private Long id;
@JsonProperty("label")
private String name;
//Getters and setters omitted for brevity
}
JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty
annotation:
@Entity
public class City {
@Id
@JsonbProperty("value")
private Long id;
@JsonbProperty("label")
private String name;
//Getters and setters omitted for brevity
}
I had a similar problem. The fontsquirel demo page was working in FF but not my own page even though all files were coming from the same domain!
It turned out that I was linking my stylesheet with an absolute URL (http://example.com/style.css) so FF thought it was coming from a different domain. Changing my stylesheet link href to /style.css instead fixed things for me.
Use regular expression to achieve this task. Please refer the below code.
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your content: ");
String data = reader.readLine();
boolean b1 = Pattern.matches("^\\d+$", data);
boolean b2 = Pattern.matches("[0-9a-zA-Z([+-]?\\d*\\.+\\d*)]*", data);
boolean b3 = Pattern.matches("^([+-]?\\d*\\.+\\d*)$", data);
if(b1) {
System.out.println("It is integer.");
} else if(b2) {
System.out.println("It is String. ");
} else if(b3) {
System.out.println("It is Float. ");
}
} catch (IOException ex) {
Logger.getLogger(TypeOF.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can use the isin
method on the date
column like so
df[df["date"].isin(pd.date_range(start_date, end_date))]
Note: This only works with dates (as the question asks) and not timestamps.
Example:
import numpy as np
import pandas as pd
# Make a DataFrame with dates and random numbers
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
# Select the rows between two dates
in_range_df = df[df["date"].isin(pd.date_range("2017-01-15", "2017-01-20"))]
print(in_range_df) # print result
which gives
0 1 2 date
14 0.960974 0.144271 0.839593 2017-01-15
15 0.814376 0.723757 0.047840 2017-01-16
16 0.911854 0.123130 0.120995 2017-01-17
17 0.505804 0.416935 0.928514 2017-01-18
18 0.204869 0.708258 0.170792 2017-01-19
19 0.014389 0.214510 0.045201 2017-01-20
My case was to print horizontal (landscape) summary section - so:
}).then((canvas) => {
const img = canvas.toDataURL('image/jpg');
new jsPDF({
orientation: 'l', // landscape
unit: 'pt', // points, pixels won't work properly
format: [canvas.width, canvas.height] // set needed dimensions for any element
});
pdf.addImage(img, 'JPEG', 0, 0, canvas.width, canvas.height);
pdf.save('your-filename.pdf');
});
insert a new column and put a series in 1,2,3,4, etc. Then create another new column and use the command =if(int(a1/7)=(a1/7),1,0) you should get a 1 in every 7th row, filter the column on the 1
To trim any set of characters from the beginning and end of a string, you can do the following code where @TrimPattern defines the characters to be trimmed. In this example, Space, tab, LF and CR characters are being trimmed:
Declare @Test nvarchar(50) = Concat (' ', char(9), char(13), char(10), ' ', 'TEST', ' ', char(9), char(10), char(13),' ', 'Test', ' ', char(9), ' ', char(9), char(13), ' ')
DECLARE @TrimPattern nvarchar(max) = '%[^ ' + char(9) + char(13) + char(10) +']%'
SELECT SUBSTRING(@Test, PATINDEX(@TrimPattern, @Test), LEN(@Test) - PATINDEX(@TrimPattern, @Test) - PATINDEX(@TrimPattern, LTRIM(REVERSE(@Test))) + 2)
Adding the @ElementCollection
to the List field solved this issue:
@Column
@ElementCollection(targetClass=Integer.class)
private List<Integer> countries;
You can try this. its working for me 'name' is a property in arr.
repeat="item in (tagWordOptions | filter:{ name: $select.search } ) track by $index
Add an identity column (PeopleID) and then use a correlated subquery to return the first value for each value.
SELECT *
FROM People p
WHERE PeopleID = (
SELECT MIN(PeopleID)
FROM People
WHERE IDNo = p.IDNo
)
Something like this maybe?
$("input:radio[name=theme]").click(function() {
...
});
When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Based on Alpar solution, using only templates with anidated ng-repeat. Works with both full and partially empty rows:
<div data-ng-app="" data-ng-init="products='soda','beer','water','milk','wine']" class="container">
<div ng-repeat="product in products" ng-if="$index % 3 == 0" class="row">
<div class="col-xs-4"
ng-repeat="product in products.slice($index, ($index+3 > products.length ?
products.length : $index+3))"> {{product}}</div>
</div>
</div>
You need to escape the backslash \
:
println yourString.replace("\\", "/")
this should serve the purpose
android:textAlignment="textStart"
I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called rows
that will give you the number of rows.
So, if you have a named data range called Data
that has 7 rows, then =ROWS(Data)
will show 7 in that cell.
I know this is somewhat of an old topic, but in case anyone reads this in the future...
I uninstalled xampp, deleted everything under the c:\xampp folder, then reinstalled xampp as administrator and it worked like a charm.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
It looks like the github.com
host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts
. Jenkins runs on most distros as the user jenkins
and hence has its own .ssh
directory to store the list of public keys and known_hosts
.
The easiest solution I can think of to fix this problem is:
# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash
cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL
# Allow adding the SSH host key to your known_hosts
# Exit from su
exit
The disabled
attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled
) and check for that attribute when you handle the click event.
In general, I always recommend this official video from Go to get a quick overview on the matter:
http://www.youtube.com/watch?v=XCsL89YtqCs
It's easier to be shown than to be told.
@jwfearn paraphrased the important part of the video:
export GOPATH="${HOME}/gocode"; export PATH="${PATH}:${GOPATH}/bin"; mkdir -p "${GOPATH}"
jquery.js: when you have to dive into jquery's source code jquery.min.js: compressed version for saving bandwidth
There is one more option for saving more bandwidth then the compressed version which is using something like Google CDN provided: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
I solved it by global searching the missing directory in the project. then delete any files containing that keyword. it can clean successfully after I remove all the build
and .externalNativeBuild
directories manually.
I tried above all and end-up with few changes which I would like to share. Here's the code which works for me (find the attached screenshot):
<div class="input-group">
<input type="text" class="form-control" placeholder="Search text">
<span class="input-group-btn" style="width:0;">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div>
If you want to see it working, just use below code in you editor:
<html>
<head>
<link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
</head>
<body>
<div class="container body-content">
<div class="form-horizontal">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search text">
<span class="input-group-btn" style="width:0;">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div>
</div>
</div>
</body>
</html>
Hope this helps.
If you really, really want to use strlen(), then
cout << strlen(str.c_str()) << endl;
else the use of .length() is more in keeping with C++.
Here you can find a complete guide for MySQL case statements in SQL.
CASE
WHEN some_condition THEN return_some_value
ELSE return_some_other_value
END
After weeks of research. I came up with the following code. I believe this is the bare minimum needed to make a secure connection with SSL to a web server.
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#define APIKEY "YOUR_API_KEY"
#define HOST "YOUR_WEB_SERVER_URI"
#define PORT "443"
int main() {
//
// Initialize the variables
//
BIO* bio;
SSL* ssl;
SSL_CTX* ctx;
//
// Registers the SSL/TLS ciphers and digests.
//
// Basically start the security layer.
//
SSL_library_init();
//
// Creates a new SSL_CTX object as a framework to establish TLS/SSL
// or DTLS enabled connections
//
ctx = SSL_CTX_new(SSLv23_client_method());
//
// -> Error check
//
if (ctx == NULL)
{
printf("Ctx is null\n");
}
//
// Creates a new BIO chain consisting of an SSL BIO
//
bio = BIO_new_ssl_connect(ctx);
//
// Use the variable from the beginning of the file to create a
// string that contains the URL to the site that you want to connect
// to while also specifying the port.
//
BIO_set_conn_hostname(bio, HOST ":" PORT);
//
// Attempts to connect the supplied BIO
//
if(BIO_do_connect(bio) <= 0)
{
printf("Failed connection\n");
return 1;
}
else
{
printf("Connected\n");
}
//
// The bare minimum to make a HTTP request.
//
char* write_buf = "POST / HTTP/1.1\r\n"
"Host: " HOST "\r\n"
"Authorization: Basic " APIKEY "\r\n"
"Connection: close\r\n"
"\r\n";
//
// Attempts to write len bytes from buf to BIO
//
if(BIO_write(bio, write_buf, strlen(write_buf)) <= 0)
{
//
// Handle failed writes here
//
if(!BIO_should_retry(bio))
{
// Not worth implementing, but worth knowing.
}
//
// -> Let us know about the failed writes
//
printf("Failed write\n");
}
//
// Variables used to read the response from the server
//
int size;
char buf[1024];
//
// Read the response message
//
for(;;)
{
//
// Get chunks of the response 1023 at the time.
//
size = BIO_read(bio, buf, 1023);
//
// If no more data, then exit the loop
//
if(size <= 0)
{
break;
}
//
// Terminate the string with a 0, to let know C when the string
// ends.
//
buf[size] = 0;
//
// -> Print out the response
//
printf("%s", buf);
}
//
// Clean after ourselves
//
BIO_free_all(bio);
SSL_CTX_free(ctx);
return 0;
}
The code above will explain in details how to establish a TLS connection with a remote server.
Important note: this code doesn't check if the public key was signed by a valid authority. Meaning I don't use root certificates for validation. Don't forget to implement this check otherwise you won't know if you are connecting the right website
When it comes to the request itself. It is nothing more then writing the HTTP request by hand.
You can also find under this link an explanation how to instal openSSL in your system, and how to compile the code so it uses the secure library.
The server name should be same as the first/last name which you give while create a certificate