I'm putting a breakpoint at the last return 0 of the program. It works fine.
Stopwatch is designed for this purpose and is one of the best way to measure execution time in .NET.
var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTimes to measure execution time in .NET.
Saves time to develop
Makes life easier by providing features like Integrated debugging, intellisense.
There are lot many, but will recommend to use one, they are more than obvious.
The difference is unlikely to matter:
As other posters have mentioned, this is a premature optimization. Concentrate on algorithm design, and only come back to this if profiling shows it to be a performance problem.
That said... I suspect method 1 will be faster. There is some---admittedly small---overhead to parse the sprintf format-string. And strcat is more likely "inline-able".
Piping to another process (Although this WON'T accomplish what you said you are trying to do):
command1 | command2
This will send the output of command1 as the input of command2
-exec
on a find
(this will do what you are wanting to do -- but is specific to find
)
find . -name '*.foo' -exec cat {} \;
(Everything between find
and -exec
are the find predicates you were already using. {}
will substitute the particular file you found into the command (cat {}
in this case); the \;
is to end the -exec
command.)
send output of one process as command line arguments to another process
command2 `command1`
for example:
cat `find . -name '*.foo' -print`
(Note these are BACK-QUOTES not regular quotes (under the tilde ~ on my keyboard).)
This will send the output of command1
into command2
as command line arguments. Note that file names containing spaces (newlines, etc) will be broken into separate arguments, though.
You can implement a system that handles the type checks automatically, using a wrapper in your function.
With this approach, you can build a complete
declarative type check system
that will manage for you the type checks . If you are interested in taking a more in depth look at this concept, check the Functyped library
The following implementation illustrates the main idea, in a simplistic, but operative way :
/*_x000D_
* checkType() : Test the type of the value. If succeds return true, _x000D_
* if fails, throw an Error_x000D_
*/_x000D_
function checkType(value,type, i){_x000D_
// perform the appropiate test to the passed _x000D_
// value according to the provided type_x000D_
switch(type){_x000D_
case Boolean : _x000D_
if(typeof value === 'boolean') return true;_x000D_
break;_x000D_
case String : _x000D_
if(typeof value === 'string') return true;_x000D_
break;_x000D_
case Number : _x000D_
if(typeof value === 'number') return true;_x000D_
break;_x000D_
default :_x000D_
throw new Error(`TypeError : Unknown type provided in argument ${i+1}`);_x000D_
}_x000D_
// test didn't succeed , throw error_x000D_
throw new Error(`TypeError : Expecting a ${type.name} in argument ${i+1}`);_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
* typedFunction() : Constructor that returns a wrapper_x000D_
* to handle each function call, performing automatic _x000D_
* arguments type checking_x000D_
*/_x000D_
function typedFunction( parameterTypes, func ){_x000D_
// types definitions and function parameters _x000D_
// count must match_x000D_
if(parameterTypes.length !== func.length) throw new Error(`Function has ${func.length} arguments, but type definition has ${parameterTypes.length}`);_x000D_
// return the wrapper..._x000D_
return function(...args){_x000D_
// provided arguments count must match types_x000D_
// definitions count_x000D_
if(parameterTypes.length !== args.length) throw new Error(`Function expects ${func.length} arguments, instead ${args.length} found.`);_x000D_
// iterate each argument value, and perform a_x000D_
// type check against it, using the type definitions_x000D_
// provided in the construction stage_x000D_
for(let i=0; i<args.length;i++) checkType( args[i], parameterTypes[i] , i)_x000D_
// if no error has been thrown, type check succeed_x000D_
// execute function!_x000D_
return func(...args);_x000D_
}_x000D_
}_x000D_
_x000D_
// Play time! _x000D_
// Declare a function that expects 2 Numbers_x000D_
let myFunc = typedFunction( [ Number, Number ], (a,b)=>{_x000D_
return a+b;_x000D_
});_x000D_
_x000D_
// call the function, with an invalid second argument_x000D_
myFunc(123, '456')_x000D_
// ERROR! Uncaught Error: TypeError : Expecting a Number in argument 2
_x000D_
You may use Socket for this like
String host = "www.yourhost.com";
Socket socket = new Socket(host, 80);
String request = "GET / HTTP/1.0\r\n\r\n";
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();
InputStream is = socket.getInputStream();
int ch;
while( (ch=is.read())!= -1)
System.out.print((char)ch);
socket.close();
The solutions above are superior, especially if using Java, and encountering more numbers with more than 10 digits such as the international code prefix or additional extension numbers. This solution is basic (I'm a beginner in the regex world) and designed with US Phone numbers in mind and is only useful for strings with just 10 numbers with perhaps some formatting characters, or perhaps no formatting characters at all (just 10 numbers). As such I would recomend this solution only for semi-automatic applications. I Personally prefer to store numbers as just 10 numbers without formatting characters, but also want to be able to convert or clean phone numbers to the standard format normal people and apps/phones will recognize instantly at will.
I came across this post looking for something I could use with a text cleaner app that has PCRE Regex capabilities (but no java functions). I will post this here for people who could use a simple pure Regex solution that could work in a variety of text editors, cleaners, expanders, or even some clipboard managers. I personally use Sublime and TextSoap. This solution was made for Text Soap as it lives in the menu bar and provides a drop-down menu where you can trigger text manipulation actions on what is selected by the cursor or what's in the clipboard.
My approach is essentially two substitution/search and replace regexes. Each substitution search and replace involves two regexes, one for search and one for replace.
Substitution/ Search & Replace #1
First Substitution/ Search Regex: \D
First Substitution/ Replace Regex: "" (nothing, not even a space)
Substitution/ Search & Replace #2
$1
, a capture group for the second set of three numbers $2
, and the last capture group for the last set of four numbers $3
. The regex for the substitute portion of the operation inserts US phone number formatting in between the captured group of digits.Second Substitution/ Search Regex: (\d{3})(\d{3})(\d{4})
Second Substitution/ Replace Regex: \($1\) $2\-$3
The backslash \
escapes the special characters (
, )
,
(<-whitespace), and -
since we are inserting them between our captured numbers in capture groups $1
, $2
, & $3
for US phone number formatting purposes.
In TextSoap I created a custom cleaner that includes the two substitution operation actions, so in practice it feels identical to executing a script. I'm sure this solution could be improved but I expect complexity to go up quite a bit. An improved version of this solution is welcomed as a learning experience if anyone wants to add to this.
Use another constant instead of Calendar.HOUR
, use Calendar.HOUR_OF_DAY
.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR
uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY
uses 0-23.
To quote the Javadocs:
public static final int HOUR
Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
and
public static final int HOUR_OF_DAY
Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):
public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}
Output:
$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00
There are several ways to create a favicon. The best way for you depends on various factors:
If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.
Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.
As you suggest, you can create a favicon.ico
file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).
Then, declare it in your HTML code:
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.
About your suggestion of placing the favicon.ico
file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).
In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico
file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.
You can achieve a good compatibility with:
favicon.ico
, see above.Declare them with
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">
This is not the full story, but it's good enough in most cases.
I got through the same error when I went on to the admin panel.
You ought to run this instead-: python manage.py migrate --run-syncdb
.
Don't forget to include migrate, I ran:
python manage.py make migrations
and then
python manage.py migrate
Still when the error persisted I tried it with the above suggested command.
You can simply assign null
to the reference. (This will work for any type of array, not just ints
)
int[] arr = new int[]{1, 2, 3, 4};
arr = null;
This will 'clear out' the array. You can also assign a new array to that reference if you like:
int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};
If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.
Another example:
float[] arr = ;// some array that you want to clear
arr = new float[arr.length];
This will create a new float[]
initialized to the default value for float.
Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):
https://stackoverflow.com/a/42000085
<span class="something" datacustomattribute="">
Hello
</span>
.something::before {
content: attr(datascustomattribute);
position: absolute;
}
Note that the datacustomattribute
must start with data
and be all lowercase to satisfy React.
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
RMI is based on Proxy.
Should be possible to cite one for most of the 23 patterns in GoF:
I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.
"In java, we have been taught about public/private/protected variables"
"Why is that not required in python?"
For the same reason, it's not required in Java.
You're free to use -- or not use private
and protected
.
As a Python and Java programmer, I've found that private
and protected
are very, very important design concepts. But as a practical matter, in tens of thousands of lines of Java and Python, I've never actually used private
or protected
.
Why not?
Here's my question "protected from whom?"
Other programmers on my team? They have the source. What does protected mean when they can change it?
Other programmers on other teams? They work for the same company. They can -- with a phone call -- get the source.
Clients? It's work-for-hire programming (generally). The clients (generally) own the code.
So, who -- precisely -- am I protecting it from?
If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO
Upstream System:
<select name=upstream id=upstream>
<option value="SYBASE">SYBASE ASE
<option value="SYBASE_IQ">SYBASE_IQ
<option value="SQLSERVER">SQLSERVER
</select>
<script>
var obj=document.getElementById("upstream");
for (var i=0;i<obj.length;i++){if(obj.options[i].value==="SYBASE_IQ")obj.selectedIndex=i;}
</script>
In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.
Start by defining a generic function pointer type:
typedef int (__stdcall* func_ptr_t)();
What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:
func_ptr_t func_ptr [DLL_FUNCTIONS_N];
In this array we can store the actual function pointers that point into the DLL memory space.
Next problem is that GetProcAddress
expects the function names as strings. So create a similar array consisting of the function names in the DLL:
const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] =
{
"dll_add",
"dll_subtract",
"dll_do_stuff",
...
};
Now we can easily call GetProcAddress() in a loop and store each function inside that array:
for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);
if(func_ptr[i] == NULL)
{
// error handling, most likely you have to terminate the program here
}
}
If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:
typedef struct
{
int (__stdcall* dll_add_ptr)(int, int);
int (__stdcall* dll_subtract_ptr)(int, int);
void (__stdcall* dll_do_stuff_ptr)(something);
...
} functions_struct;
And finally, to connect these to the array from before, create a union:
typedef union
{
functions_struct by_type;
func_ptr_t func_ptr [DLL_FUNCTIONS_N];
} functions_union;
Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type
union member.
But of course, it is a bit burdensome to type out something like
functions.by_type.dll_add_ptr(1, 1);
whenever you want to call a function.
As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:
#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)
And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:
int result = dll_add(1, 1);
Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.
Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert
to ensure that the struct/union has no padding might be in order still.
The tf.exe command line is included in the VSTS agent package in folder externals\vstsom.
$('#ur_id').slideUp("slow", function() { $('#ur_id').remove();});
The __pycache__
folder and *.pyc
files are totally unnecessary to the developer. To hide these files from the explorer view, we need to edit the settings.json for VSCode. Add the folder and the files as shown below:
"files.exclude": {
...
...
"**/*.pyc": {"when": "$(basename).py"},
"**/__pycache__": true,
...
...
}
Simple Solution
Here is a simple solution. No additional for loop required.
HTML part
<table ng-init="ResetTotalAmt()">
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat="product in cart.products">
<td ng-init="CalculateSum(product)">{{product.name}}</td>
<td>{{product.quantity}}</td>
<td>{{product.price * product.quantity}} €</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td>{{cart.TotalAmt}}</td> // Here is the total value of my cart
</tr>
</table>
Script Part
$scope.cart.TotalAmt = 0;
$scope.CalculateSum= function (product) {
$scope.cart.TotalAmt += (product.price * product.quantity);
}
//It is enough to Write code $scope.cart.TotalAmt =0; in the function where the cart.products get allocated value.
$scope.ResetTotalAmt = function (product) {
$scope.cart.TotalAmt =0;
}
You can use the following code snippet :
java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
-version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
In my pc I am getting following output :
uintx InitialHeapSize := 536870912 {product}
uintx MaxHeapSize := 1073741824 {product}
uintx PermSize := 67108864 {pd product}
uintx MaxPermSize := 134217728 {pd product}
intx ThreadStackSize := 512 {pd product}
I don't know specifically for redis, but for servers in general:
What OS or distribution? Often there will be a stop or /etc/init.d/... command that will be able to look up the existing pid in a pid file.
You can look up what process is already bound to the port with sudo netstat -nlpt
(linux options; other netstat flavors will vary) and signal it to stop. I would not use kill -9
on a running server unless there really is no other signal or method to shut it down.
You should \usepackage{longtable}
.
In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.
For example:
double doubleValue = 156.5d;
Double doubleObject = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();
Primitive data types are store the fastest available memory where the Helper class is complex and store in heap memory.
reference from "David Gassner" Java Essential Training.
Yes using Interface is a hassle because anytime we add a method in the class we have to add the signature in the interface. Also, what if we already have a class with a bunch of methods but no Interface for it? we have to manually create Interface for all the classes that we want to inherit from. And the worst thing is, we have to implement all methods in the Interfaces in the child class if the child class is to inherit from the multiple interface.
By following Facade design pattern we can simulate inheriting from multiple classes using accessors. Declare the classes as properties with {get;set;} inside the class that need to inherit and all public properties and methods are from that class, and in the constructor of the child class instantiate the parent classes.
For example:
namespace OOP
{
class Program
{
static void Main(string[] args)
{
Child somechild = new Child();
somechild.DoHomeWork();
somechild.CheckingAround();
Console.ReadLine();
}
}
public class Father
{
public Father() { }
public void Work()
{
Console.WriteLine("working...");
}
public void Moonlight()
{
Console.WriteLine("moonlighting...");
}
}
public class Mother
{
public Mother() { }
public void Cook()
{
Console.WriteLine("cooking...");
}
public void Clean()
{
Console.WriteLine("cleaning...");
}
}
public class Child
{
public Father MyFather { get; set; }
public Mother MyMother { get; set; }
public Child()
{
MyFather = new Father();
MyMother = new Mother();
}
public void GoToSchool()
{
Console.WriteLine("go to school...");
}
public void DoHomeWork()
{
Console.WriteLine("doing homework...");
}
public void CheckingAround()
{
MyFather.Work();
MyMother.Cook();
}
}
}
with this structure class Child will have access to all methods and properties of Class Father and Mother, simulating multiple inheritance, inheriting an instance of the parent classes. Not quite the same but it is practical.
It seems I'm kind of late :), but the discussion is pretty interesting so.. here it goes... Assuming you want to build a error handler, and you're using your own exception handler class like:
function errorHandler(error){
this.errorMessage = error;
}
errorHandler.prototype. displayErrors = function(){
throw new Error(this.errorMessage);
}
And you're wrapping your code like this:
try{
if(condition){
//whatever...
}else{
throw new errorHandler('Some Error Message');
}
}catch(e){
e.displayErrors();
}
Most probably you'll have the error handler in a separate .js file.
You'll notice that in firefox or chrome's error console the code line number(and file name) showed is the line(file) that throws the 'Error' exception and not the 'errorHandler' exception wich you really want in order to make debugging easy. Throwing your own exceptions is great but on large projects locating them can be quite an issue, especially if they have similar messages. So, what you can do is to pass a reference to an actual empty Error object to your error handler, and that reference will hold all the information you want( for example in firefox you can get the file name, and line number etc.. ; in chrome you get something similar if you read the 'stack' property of the Error instance). Long story short , you can do something like this:
function errorHandler(error, errorInstance){
this.errorMessage = error;
this. errorInstance = errorInstance;
}
errorHandler.prototype. displayErrors = function(){
//add the empty error trace to your message
this.errorMessage += ' stack trace: '+ this. errorInstance.stack;
throw new Error(this.errorMessage);
}
try{
if(condition){
//whatever...
}else{
throw new errorHandler('Some Error Message', new Error());
}
}catch(e){
e.displayErrors();
}
Now you can get the actual file and line number that throwed you custom exception.
Gonna answer in opposite direction.
2) For a full explanation about \r
and \n
I have to refer to this question, which is far more complete than I will post here: Difference between \n and \r?
Long story short, Linux uses \n
for a new-line, Windows \r\n
and old Macs \r
. So there are multiple ways to write a newline. Your second tool (RegExr) does for example match on the single \r
.
1) [\r\n]+
as Ilya suggested will work, but will also match multiple consecutive new-lines. (\r\n|\r|\n)
is more correct.
Try using an ontouch listener instead of a clicklistener.
http://developer.android.com/reference/android/view/View.OnTouchListener.html
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:
PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;
You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.
For example:
Y:\> **sqlite3 booktest**
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT
NULL);**
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**
Error: BOOKS.publication_date may not be NULL
sqlite> **PRAGMA writable_schema = 1;**
sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT
NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**
sqlite> **PRAGMA writable_schema = 0;**
sqlite> **.q**
Y:\> **sqlite3 booktest**
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**
sqlite> **.q**
REFERENCES FOLLOW:
pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.
[alter table](From http://www.sqlite.org/lang_altertable.html)
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.
This works fine for me . [Ref: the very nice plug in by Gavin G]
(function($){
$.fn.focusTextToEnd = function(){
this.focus();
var $thisVal = this.val();
this.val('').val($thisVal);
return this;
}
}(jQuery));
$('#mytext').focusTextToEnd();
This is an Android 8 update.
In earlier version of Android, to LoadLibrary native shared libraries (for access via JNI for example) I hard-wired my native code to iterate through a range of potential directory paths for the lib folder, based on the various apk installation/upgrade algorithms:
/data/data/<PackageName>/lib
/data/app-lib/<PackageName>-1/lib
/data/app-lib/<PackageName>-2/lib
/data/app/<PackageName>-1/lib
/data/app/<PackageName>-2/lib
This approach is hokey and will not work for Android 8; from https://developer.android.com/about/versions/oreo/android-8.0-changes.html you'll see that as part of their "Security" changes you now need to use sourceDir:
"You can no longer assume that APKs reside in directories whose names end in -1 or -2. Apps should use sourceDir to get the directory, and not rely on the directory format directly."
Correction, sourceDir is not the way to find your native shared libraries; use something like. Tested for Android 4.4.4 --> 8.0
// Return Full path to the directory where native JNI libraries are stored.
private static String getNativeLibraryDir(Context context) {
ApplicationInfo appInfo = context.getApplicationInfo();
return appInfo.nativeLibraryDir;
}
You should add first jquery.cookie.js
then add your js or jQuery where you are using that function.
When browser loads the webpage first it loads this jquery.cookie.js
and after then you js or jQuery and now that function is available for use
You can achieve an expected result with requests
library as well:
import requests
url = "http://www.mywebsite.org/Data%20Set.zip"
print(f"Before: {url}")
print(f"After: {requests.utils.unquote(url)}")
Output:
$ python3 test_url_unquote.py
Before: http://www.mywebsite.org/Data%20Set.zip
After: http://www.mywebsite.org/Data Set.zip
Might be handy if you are already using requests
, without using another library for this job.
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
toFixed
isn't a method of non-numeric variable types. In other words, Low
and High
can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat()
(or parseInt()
with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed()
function to work.
var Low = parseFloat($SliderValFrom.val()),
High = parseFloat($SliderValTo.val());
A better way to solve it is to start small.
Let's start with 1 bit. Which can either be 1
or 0
. That's 2 values, or 10
in binary.
Now 2 bits, which can either be 00
, 01
, 10
or 11
That's 4 values, or 100
in binary... See the pattern?
mysqladmin -u [username] -p password
worked for me on OS X El Capitan and MySQL 5.7.12 Community Server. Example:
$ /usr/local/mysql/bin/mysqladmin -u root -p password
Enter password:
New password:
Confirm new password:
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
This is similar to pavan sachi's answer, but with password prompts.
My error was "#1862 - Your password has expired. To log in you must change it using a client that supports expired passwords." at phpMyAdmin login screen first time.
Why to use regex? PHP has some built in functionality to do that
<?php
$valid_symbols = array('-', '_');
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
echo "String 1 not acceptable acceptable";
}
?>
preg_match('/\s/',$username)
will check for blank space
!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols
first make the script executable using
sudo chmod 755 /path/of/the/file.sh
now add the script in the rc.local
sh /path/of/the/file.sh
before exit 0
in the rc.local,
next make the rc.local to executable with
sudo chmod 755 /etc/rc.local
next to initialize the rc.local use
sudo /etc/init.d/rc.local start
this will initiate the rc.local
now reboot the system.
Done..
I may also add, that nowadays it is possible to decompile Android application online, no software needed!
Here are 2 options for you:
Add into ~/.Rprofile
local({r <- getOption("repos")
r["CRAN"] <- "mirror_site" #for example, https://mirrors.ustc.edu.cn/CRAN/
options(repos=r)
options(BioC_mirror="bioc_mirror_site") #if using biocLite
})
You can use flexbox for this.
ul {
display: flex;
align-items: center;
}
A detailed explanation of how to use flexbox can be found here.
Try:
v = (float)s / (float)t;
Casting the ints to floats will allow floating-point division to take place.
You really only need to cast one, though.
In Python we can use the __str__()
method.
We can override it in our class like this:
class User:
firstName = ''
lastName = ''
...
def __str__(self):
return self.firstName + " " + self.lastName
and when running
print(user)
it will call the function __str__(self)
and print the firstName and lastName
if(!empty($youtube) && empty($link)) {
}
else if(empty($youtube) && !empty($link)) {
}
else if(empty($youtube) && empty($link)) {
}
Since you tagged Java-ee as well - then YES it is possible.
and in core java as well it is possible using static blocks
and check this How can you run a Java program without main method?
Edit:
as already pointed out in other answers - it does not support from Java 7
You can put them into a list and then sort them using their natural ordering, like so:
final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list
If the numbers are stored in the same variable, then you'll have to somehow put them into a List
and then call sort
, like so:
final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...
Collections.sort( list );
// Use the sorted list
Run your application in debug mode by clicking on
in the upper menu of Android Studio.
In the bottom status bar, click 5: Debug
button, next to the 4: Run
button.
Now you should select the Logcat
console.
In search box, you can type the tag of your message, and your message should appear, like in the following picture (where the tag is CREATION
):
Check this article for more information.
Short list of some of the major differences:
bool
, true
and false
, Objective-C uses BOOL
, YES
and NO
.void*
and nullptr
, Objective-C prefers id
and nil
.SEL
) as an approximate equivalent to function pointers.nil
, unlike C++ which will crash if you try to call a member function of nullptr
self
, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new
) it is guaranteed to be of the type you originally specified.int foo (void)
and int foo (int)
define an implicit overload of the method foo
, but to achieve the same in Objective-C requires the explicit overloads - (int) foo
and - (int) foo:(int) intParam
. This is due to Objective-C's named parameters being functionally equivalent to C++'s name mangling.alloc
message, or implicitly in an appropriate factory method).In my opinion, probably the biggest difference is the syntax. You can achieve essentially the same things in either language, but in my opinion the C++ syntax is simpler while some of Objective-C's features make certain tasks (such as GUI design) easier thanks to dynamic dispatch.
Probably plenty of other things too that I've missed, I'll update with any other things I think of. Other than that, can highly recommend the guide LiraNuna pointed you to. Incidentally, another site of interest might be this.
I should also point out that I'm just starting learning Objective-C myself, and as such a lot of the above may not quite be correct or complete - I apologise if that's the case, and welcome suggestions for improvement.
EDIT: updated to address the points raised in the following comments, added a few more items to the list.
Here Is my snippet try it. I hope it will helpfull for u.
<!DOCTYPE HTML>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div id="hello"></div>_x000D_
_x000D_
<script type ="text/javascript">_x000D_
what();_x000D_
function what(){_x000D_
document.getElementById('hello').innerHTML = 'hi';_x000D_
};_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
When I encountered this exception, I solved this by using Run Configurations... panel as picture shows below.Especially, at JRE tab, the VM Arguments are the critical
( "-Xmx1024m -Xms512m -XX:MaxPermSize=1024m -XX:PermSize=512m" ).
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
you will need to convert given string to JSONObject
instead of JSONArray
because current String contain JsonObject
as root element instead of JsonArray
:
JSONObject jsonObject = new JSONObject(readlocationFeed);
I was having the same problem using the python email functions. Below is the code I was trying to retrieve email subject into a variable. This works fine for most emails and the variable populates. If you receive an email from Yahoo or the like and the sender did no fill out the subject line Yahoo does not create a subject line in the email and you get a NoneType returned from the function. Martineau provided a correct answer as well as Soviut. IMO Soviut's answer is more concise from a programming stand point; not necessarily from a Python one. Here is some code to show the technique:
import sys, email, email.Utils
afile = open(sys.argv[1], 'r')
m = email.message_from_file(afile)
subject = m["subject"]
# Soviut's Concise test for unset variable.
if subject is None:
subject = "[NO SUBJECT]"
# Alternative way to test for No Subject created in email (Thanks for NoneThing Yahoo!)
try:
if len(subject) == 0:
subject = "[NO SUBJECT]"
except TypeError:
subject = "[NO SUBJECT]"
print subject
afile.close()
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
According to your example here it seems that they both reside in the same namespace, i conclude that they are both part of the same project ( if you haven't created another project with the same namespace) and all class by default are defined as internal to the project they are defined in, if haven't declared otherwise, therefore i guess the problem is that your file is not included in your project. You can include it by right clicking the file in the solution explorer window => Include in project, if you cannot see the file inside the project files in the solution explorer then click the show the upper menu button of the solution explorer called show all files ( just hove your mouse cursor over the button there and you'll see the names of the buttons)
Just for basic knowledge: If the file resides in a different project\ assembly then it has to be defined, otherwise it has to be define at least as internal or public. in case your class is inheriting from that class that it can be protected as well.
Please check this:
$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';
$connection = mysqli_connect($servername,$username,$password);
if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}
/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");
if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}
mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");
$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/
I had the same problem and my solution was the following:
Instead of deleting the main applicationhost.config
(in your "Documents/IIS Express" folder), check your solution folder for a hidden ".vs" folder with a "config" sub-folder. If that folder exists and it has it's own applicationhost.config
file you need to either rename (or delete) that file or edit it and make sure the website(s) configured inside match the ASP.NET web app(s) in your solution that you are trying to debug. Hope this helps.
You can use this:
$("#id").click(function()
{
$(this).data('clicked', true);
});
Now check it via an if statement:
if($("#id").data('clicked'))
{
// code here
}
For more information you can visit the jQuery website on the .data() function.
you can set the environment variable JAVA_TOOL_OPTS like as follows, which will be picked by JVM for any application.
set JAVA_TOOL_OPTS=-Djava.net.preferIPv4Stack=true
You can set this from the command prompt or set in system environment variables, based on your need. Note that this will reflect into all the java applications that run in your machine, even if it's a java interpreter that you have in a private setup.
' i modify the code for Datatable
For Each c as DataColumn in dt.Columns
For j=0 To _dataTable.Columns.Count-1
xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName
Next
Next
Hope this could be help!
1.) First off, what is the correct terminology for an array created on the end of the name element of an input tag in a form?
"Oftimes Confusing PHPism"
As far as JavaScript is concerned a bunch of form controls with the same name are just a bunch of form controls with the same name, and form controls with names that include square brackets are just form controls with names that include square brackets.
The PHP naming convention for form controls with the same name is sometimes useful (when you have a number of groups of controls so you can do things like this:
<input name="name[1]">
<input name="email[1]">
<input name="sex[1]" type="radio" value="m">
<input name="sex[1]" type="radio" value="f">
<input name="name[2]">
<input name="email[2]">
<input name="sex[2]" type="radio" value="m">
<input name="sex[2]" type="radio" value="f">
) but does confuse some people. Some other languages have adopted the convention since this was originally written, but generally only as an optional feature. For example, via this module for JavaScript.
2.) How do I get the information from that array with JavaScript?
It is still just a matter of getting the property with the same name as the form control from elements
. The trick is that since the name of the form controls includes square brackets, you can't use dot notation and have to use square bracket notation just like any other JavaScript property name that includes special characters.
Since you have multiple elements with that name, it will be a collection rather then a single control, so you can loop over it with a standard for loop that makes use of its length property.
var myForm = document.forms.id_of_form;
var myControls = myForm.elements['p_id[]'];
for (var i = 0; i < myControls.length; i++) {
var aControl = myControls[i];
}
One may be tempted to keep the Powershell/cmd open on Windows. I've spent reasonable time till I decided to close and reopen my Powershell only to realize that I've done everything right.
This is largely a duplicate of another question.
Here's the section of that answer that is relevant to this question:
Do I need to do my own synchronization if I use java.util.ConcurrentLinkedQueue?
Atomic operations on the concurrent collections are synchronized for you. In other words, each individual call to the queue is guaranteed thread-safe without any action on your part. What is not guaranteed thread-safe are any operations you perform on the collection that are non-atomic.
For example, this is threadsafe without any action on your part:
queue.add(obj);
or
queue.poll(obj);
However; non-atomic calls to the queue are not automatically thread-safe. For example, the following operations are not automatically threadsafe:
if(!queue.isEmpty()) {
queue.poll(obj);
}
That last one is not threadsafe, as it is very possible that between the time isEmpty is called and the time poll is called, other threads will have added or removed items from the queue. The threadsafe way to perform this is like this:
synchronized(queue) {
if(!queue.isEmpty()) {
queue.poll(obj);
}
}
Again...atomic calls to the queue are automatically thread-safe. Non-atomic calls are not.
There are a lot of excellent answers here, but dplyr gives the only syntax that I can quickly and easily remember (and so now use very often):
library(dplyr)
# sort mtcars by mpg, ascending... use desc(mpg) for descending
arrange(mtcars, mpg)
# sort mtcars first by mpg, then by cyl, then by wt)
arrange(mtcars , mpg, cyl, wt)
For the OP's problem:
arrange(dd, desc(z), b)
b x y z
1 Low C 9 2
2 Med D 3 1
3 Hi A 8 1
4 Hi A 9 1
This is because of the Stacking Context, setting a z-index will make it apply to all children as well.
You could make the two <div>
s siblings instead of descendants.
<div class="absolute"></div>
<div id="relative"></div>
Eclipse had a bug which reported more cycles than necessary. This has been fixed with the 2019-12 release. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=551105
You can define your versionName
and versionCode
in your module's build.gradle
file like this :
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
.... //Other Configuration
}
name
is deprecated for link targets, and invalid in HTML5. It no longer works at least in latest Firefox (v13). Change <a name="hello">
to<a id="hello">
The target does not need to be an <a>
tag, it can be <p id="hello"
> or <h2 id="hello">
etc. which is often cleaner code.
As other posts say clearly, name
is still used (needed) in forms. It is also still used in META tags.
Not sure if this is official but this worked for me in typescript 2.7.1:
class Item {
configs: Map<string, string>;
constructor () {
this.configs = new Map();
}
}
In simple Map<keyType, valueType>
you are a PyCharm User, its good easy to install Flask First open the pycharm press Open Settings(Ctrl+Alt+s) Goto Project Interpreter
Double click pip>>
search bar (top of page) you search the flask and click install package
such Cases in which flask is not shown in pip: Open Manage Repository>> Add(+) >> Add this following url
https://www.palletsprojects.com/p/flask/
Now back to pip, it will show related packages of flask,
select flask>>
install package
Create the intent like this:
Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address","your desired phoneNumber");
smsIntent.putExtra("sms_body","your desired message");
smsIntent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(smsIntent);
Julien Danjou wrote a good article explaining why you should never deal with timezones. An excerpt:
Indeed, Python datetime API always returns unaware datetime objects, which is very unfortunate. Indeed, as soon as you get one of this object, there is no way to know what the timezone is, therefore these objects are pretty "useless" on their own.
Alas, even though you may use utcnow()
, you still won't see the timezone info, as you discovered.
Recommendations:
Always use aware
datetime
objects, i.e. with timezone information. That makes sure you can compare them directly (aware and unawaredatetime
objects are not comparable) and will return them correctly to users. Leverage pytz to have timezone objects.Use ISO 8601 as the input and output string format. Use
datetime.datetime.isoformat()
to return timestamps as string formatted using that format, which includes the timezone information.If you need to parse strings containing ISO 8601 formatted timestamps, you can rely on
iso8601
, which returns timestamps with correct timezone information. This makes timestamps directly comparable.
What you do here is called a JOIN
(although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.
But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!
If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).
In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg
dew 4 ./images/dew-1.jpg
In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:
SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew 4 ./images/dew-1.jpg,./images/dew-2.jpg
However, this can get dangerous if you have ,
within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.
If the same error occurs in ADT/Eclipse
Add Action Bar Sherlock library in your project.
Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.
This will surely removes your both errors.
simple program to find a function execution time taken.
#include <iostream>
#include <ctime> // time_t
#include <cstdio>
void function()
{
for(long int i=0;i<1000000000;i++)
{
// do nothing
}
}
int main()
{
time_t begin,end; // time_t is a datatype to store time values.
time (&begin); // note time before execution
function();
time (&end); // note time after execution
double difference = difftime (end,begin);
printf ("time taken for function() %.2lf seconds.\n", difference );
return 0;
}
I just need one line to show a website in my app:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://match4app.com")));
The IEnumerable<T>
interface does not include an indexer, you're probably confusing it with IList<T>
If the object really is an IList<T>
(e.g. List<T>
or an array T[]
), try making the reference to it of type IList<T>
too.
Otherwise, you can use myEnumerable.ElementAt(index)
which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>
s .
Note that unless the (run-time) object implements IList<T>
, this will cause all of the first index + 1
items to be enumerated, with all but the last being discarded.
EDIT:
As an explanation, IEnumerable<T>
is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T>
must support all these cases, indexers are excluded from its definition.
From jacoco:prepare-agent that says:
One of the ways to do this in case of maven-surefire-plugin - is to use syntax for late property evaluation:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>@{argLine} -your -extra -arguments</argLine> </configuration> </plugin>
Note the @{argLine}
that's added to -your -extra -arguments
.
Thanks Slava Semushin for noticing the change and reporting in the comment.
Following jacoco:prepare-agent that says:
[org.jacoco:jacoco-maven-plugin:0.7.2-SNAPSHOT:prepare-agent] Prepares a property pointing to the JaCoCo runtime agent that can be passed as a VM argument to the application under test. Depending on the project packaging type by default a property with the following name is set:
- tycho.testArgLine for packaging type eclipse-test-plugin and
- argLine otherwise.
Note that these properties must not be overwritten by the test configuration, otherwise the JaCoCo agent cannot be attached. If you need custom parameters please append them. For example:
<argLine>${argLine} -your -extra -arguments</argLine>
Resulting coverage information is collected during execution and by default written to a file when the process terminates.
you should change the following line in maven-surefire-plugin
plugin configuration from (note the ${argLine}
inside <argLine>
):
<argLine>-Xmx2048m</argLine>
to
<argLine>${argLine} -Xmx2048m</argLine>
Make also the necessary changes to the other plugin maven-failsafe-plugin
and replace the following (again, notice the ${argLine}
):
<argLine>-Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
to
<argLine>${argLine} -Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML
I believe. I use the jQuery html
function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>?
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
Using equals()
LocalDate
does override equals:
int compareTo0(LocalDate otherDate) {
int cmp = (year - otherDate.year);
if (cmp == 0) {
cmp = (month - otherDate.month);
if (cmp == 0) {
cmp = (day - otherDate.day);
}
}
return cmp;
}
If you are not happy with the result of equals()
, you are good using the predefined methods of LocalDate
.
Notice that all of those method are using the compareTo0()
method and just check the cmp
value. if you are still getting weird result (which you shouldn't), please attach an example of input and output
I encountered this problem when I import GridSearchCV
.
Just changed sklearn.model_selection
to sklearn.grid_search
.
With Swift 5, according to your needs, you may choose one of the 6 following Playground codes in order to solve your problem.
subscript(_:)
subscriptlet array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array[..<5]
//let arraySlice = array[0..<5] // also works
//let arraySlice = array[0...4] // also works
//let arraySlice = array[...4] // also works
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
prefix(_:)
methodComplexity: O(1) if the collection conforms to RandomAccessCollection
; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(5)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
Apple states for prefix(_:)
:
If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.
prefix(upTo:)
methodComplexity: O(1)
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(upTo: 5)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
Apple states for prefix(upTo:)
:
Using the
prefix(upTo:)
method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred overprefix(upTo:)
.
prefix(through:)
methodlet array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let arraySlice = array.prefix(through: 4)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
removeSubrange(_:)
methodComplexity: O(n), where n is the length of the collection.
var array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
array.removeSubrange(5...)
print(array) // prints: ["A", "B", "C", "D", "E"]
dropLast(_:)
methodComplexity: O(1) if the collection conforms to RandomAccessCollection
; otherwise, O(k), where k is the number of elements to drop.
let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
let distance = array.distance(from: 5, to: array.endIndex)
let arraySlice = array.dropLast(distance)
let newArray = Array(arraySlice)
print(newArray) // prints: ["A", "B", "C", "D", "E"]
Insert \u0020 directly in the XML for a blank you would like to preserve.
<string name="spelatonertext3">-4, \u00205, \u0020\u0020-5, \u00206, \u0020-6,</string>
If you are developing for Android, Color's method for this is rgb(int, int, int)
So you would do something like
myPaint.setColor(Color.rgb(int, int, int));
For retrieving the individual color values you can use the methods for doing so:
Color.red(int color)
Color.blue(int color)
Color.green(int color)
Refer to this document for more info
On Visual Studio 2015 the only way I finally got it to work was to run git init
from the root of my directory using the command line. Then I went into Team Explorer and added a local git repository. Then I selected that local git repository, went to Settings->Repository Settings, and added my Remote Repo. That's how I was finally able to integrate Visual Studio to use my existing project with git.
I read all of the answers but none of them worked for me. I went to File->Add To Source Control, which was suppose to basically do the same as git init
, but it didn't seem to initialize my project because when I would then go to Team Explorer all of the options were grayed out. Also nothing would show up in the Changes dialog either. Another answer stated that I just had to create a local repo in Team Explorer and then my changes would show up, but that didn't work either. All the Git options on Team Explorer only worked after I initialized my project through the command line.
I'm new to Visual Studio so I don't know if I just missed something obvious, but it seems like my project wasn't initializing from Visual Studio.
Define a broadcast receiver anywhere in Activity/Fragment like this:
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG," onRecieve"); //do something with intent
}
};
Define IntentFilter in onCreate()
mIntentFilter=new IntentFilter("action_name");
Now register the BroadcastReciever in onResume()
and Unregister it in onPause()
[because there is no use of broadcast if the activity is paused].
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
@Override
protected void onPause() {
if(mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
super.onPause();
}
For detail tutorial, have a look at broadcast receiver-two ways to implement.
My best approach is:
var item = {...}
var items = [{id:2}, {id:2}, {id:2}];
items[items.findIndex(el => el.id === item.id)] = item;
Reference for findIndex
And in case you don't want to replace with new object, but instead to copy the fields of item
, you can use Object.assign
:
Object.assign(items[items.findIndex(el => el.id === item.id)], item)
as an alternative with .map()
:
Object.assign(items, items.map(el => el.id === item.id? item : el))
Don't modify the array, use a new one, so you don't generate side effects
const updatedItems = items.map(el => el.id === item.id ? item : el)
As other people have commented above, using TRUNC will prevent the use of indexes (if there was an index on TIME_CREATED). To avoid that problem, the query can be structured as
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED BETWEEN TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TO_DATE('26/JAN/2011','dd/mon/yyyy') + INTERVAL '86399' second;
86399 being 1 second less than the number of seconds in a day.
This works for me:
scroll-content {
overflow-x: hidden;
overflow-y: scroll;
}
scroll-content::-webkit-scrollbar {
width: 0;
}
Yes. I recommend you check out Kimberly Tripp's articles on indexing.
If an index is "covering", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.
Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.
You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.
FWIW, in Boostrap 4.4, you can add .text-wrap
style to things like buttons:
<a href="#" class="btn btn-primary text-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
https://getbootstrap.com/docs/4.4/utilities/text/#text-wrapping-and-overflow
For Win32:
While GetSystemInfo() gets you the number of logical processors, use GetLogicalProcessorInformationEx() to get the number of physical processors.
To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:
$ find /target_directory -type f -mmin -60
To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):
$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r
To pause for 0.8 of a second:
Sub main()
startTime = Timer
Do
Loop Until Timer - startTime >= 0.8
End Sub
This is an improvement on the ".localized" approach. Start with adding the class extension as this will help with any strings you were setting programatically:
extension String {
func localized (bundle: Bundle = .main, tableName: String = "Localizable") -> String {
return NSLocalizedString(self, tableName: tableName, value: "\(self)", comment: "")
}
}
Example use for strings you set programmatically:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Now Xcode's storyboard translation files make the file manager messy and don't handle updates to the storyboard well either. A better approach is to create a new basic label class and assign it to all your storyboard labels:
class BasicLabel: UILabel {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.text
text = storyboardText?.localized()
}
}
Now every label you add and provide default default for in the storyboard will automatically get translated, assuming you've provide a translation for it.
You could do the same for UIButton:
class BasicBtn: UIButton {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.titleLabel?.text
let lclTxt = storyboardText?.localized()
setTitle(lclTxt, for: .normal)
}
}
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
The customized spinner posted by @Menol had a small issue where the spinner would be shifted down and to the right by the size of one dot. I have updated the code so that it compensates for this offset by subtracting by half the dot.
Here is the updated code:
private void initialSetup()
{
float horizontalCenter = (float)(SpinnerWidth / 2);
float verticalCenter = (float)(SpinnerHeight / 2);
float distance = (float)Math.Min(SpinnerHeight, SpinnerWidth) / 2;
float dotComp = (float)(EllipseSize / 2);
double angleInRadians = 44.8;
float cosine = (float)Math.Cos(angleInRadians);
float sine = (float)Math.Sin(angleInRadians);
EllipseN = newPos(left: horizontalCenter - dotComp, top: verticalCenter - distance - dotComp);
EllipseNE = newPos(left: horizontalCenter + (distance * cosine) - dotComp, top: verticalCenter - (distance * sine) - dotComp);
EllipseE = newPos(left: horizontalCenter + distance - dotComp, top: verticalCenter - dotComp);
EllipseSE = newPos(left: horizontalCenter + (distance * cosine) - dotComp, top: verticalCenter + (distance * sine) - dotComp);
EllipseS = newPos(left: horizontalCenter - dotComp, top: verticalCenter + distance - dotComp);
EllipseSW = newPos(left: horizontalCenter - (distance * cosine) - dotComp, top: verticalCenter + (distance * sine) - dotComp);
EllipseW = newPos(left: horizontalCenter - distance - dotComp, top: verticalCenter - dotComp);
EllipseNW = newPos(left: horizontalCenter - (distance * cosine) - dotComp, top: verticalCenter - (distance * sine) - dotComp);
}
Sadly the other posters are correct that you're
...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.
Out of completeness, the type selector is - similar to xpath - of the form [attribute=value]
but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.
If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:
Right click on database -> Tasks -> Restore -> Database.
In General tab, click on Timeline -> select Specific date and time option.
Move the timeline slider to before update command time -> click OK.
In the destination database name, type a new name.
In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.
In the options tab, check in Overwrite ... and remove Take tail-log... check option.
Finally, click on OK and wait until the recovery process is over.
I have used this method myself in an operational database and it was very useful.
Another alternative is to use the mapPartitionsWithIndex
method as you'll get the partition index number and a list of all lines within that partition. Partition 0 and line 0 will be be the header
val rows = sc.textFile(path)
.mapPartitionsWithIndex({ (index: Int, rows: Iterator[String]) =>
val results = new ArrayBuffer[(String, Int)]
var first = true
while (rows.hasNext) {
// check for first line
if (index == 0 && first) {
first = false
rows.next // skip the first row
} else {
results += rows.next
}
}
results.toIterator
}, true)
rows.flatMap { row => row.split(",") }
Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.
I Think you should have to concentrate on the
SchemaExport Class
this Class Makes Your Configuration Dynamic So it allows you to choose whatever suites you best...
Checkout [SchemaExport]
You need to compare, not assign:
if (strcmp("hello", "hello") == 0)
^
Because you want to check if the result of strcmp("hello", "hello")
equals to 0
.
About the error:
lvalue required as left operand of assignment
lvalue
means an assignable value (variable), and in assignment the left value to the =
has to be lvalue
(pretty clear).
Both function results and constants are not assignable (rvalue
s), so they are rvalue
s. so the order doesn't matter and if you forget to use ==
you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write =
instead of ==
, you will get a compilation error. for example:
int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
//...
}
vs.
int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
//...
}
(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)
I believe you need to .f
file as a parameter, not as a command-single-string. same with the "--domain "+i
, which i would split in two elements of the list.
Assuming that:
FORTRAN
executable, ~/
is indeed the correct way for the FORTRAN
executableI would change this line:
subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])
to
subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])
If that doesn't work, you should do a os.path.exists()
for the .f
file, and check that you can launch the FORTRAN
executable without any path, and set the path or system path variable accordingly
[EDIT 6-Mar-2017]
As the exception, detailed in the original post, is a python exception from subprocess
; it is likely that the WinError 2
is because it cannot find FORTRAN
I highly suggest that you specify full path for your executable:
for i in input:
exe = r'c:\somedir\fortrandir\fortran.exe'
fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
subprocess.Popen([exe, fortran_script, "--domain", i])
if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:
for i in input:
exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[EDIT 7-Mar-2017]
The following line is incorrect:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'
I am not sure why you have ~/
as a prefix for every path, don't do that.
for i in input:
exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[2nd EDIT 7-Mar-2017]
I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:
subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)
You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess
command.
Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start
Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/
This answer is out of date. Fig not longer exists and has been replaced by Docker compose. Accepted answers cannot be deleted ....
Docker Compose supports the building of project hierachy. So it's now easy to support a Dockerfile in each sub directory.
+-- docker-compose.yml
+-- project1
¦ +-- Dockerfile
+-- project2
+-- Dockerfile
I just create a directory containing a Dockerfile for each component. Example:
When building the containers just give the directory name and Docker will select the correct Dockerfile.
You only need to use magic if the object is indeed "magical". If you have a classic object with fixed properties then use setters and getters, they work fine.
If your object have dynamic properties for example it is part of a database abstraction layer, and its parameters are set at runtime then you indeed need the magic methods for convenience.
In my case I had to start a list of exclude extensions from the second line because xcopy ignored the first line.
for random every RUN file
size_t randomGenerator(size_t min, size_t max) {
std::mt19937 rng;
rng.seed(std::random_device()());
//rng.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);
return dist(rng);
}
The following may help (study the impacts of disable-verity
first):
adb root
adb disable-verity
adb reboot
This is an improvement of Saik0's answer based on Anwar Shaikh's comment that too big files (above available memory) will throw an exception:
Using Apache Commons FileUtils
private void printEmptyFileName(final File file) throws IOException {
/*Arbitrary big-ish number that definitely is not an empty file*/
int limit = 4096;
if(file.length < limit && FileUtils.readFileToString(file).trim().isEmpty()) {
System.out.println("File is empty: " + file.getName());
}
}
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
Set the SelectedPath property before you call ShowDialog ...
folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();
Will start them at C:\Temp
In iOS6, Apple supports this via the <input type="file">
tag. I couldn't find a useful link in Apple's developer documentation, but there's an example here.
It looks like overlays and more advanced functionality is not yet available, but this should work for a lot of use cases.
EDIT: The w3c has a spec that iOS6 Safari seems to implement a subset of. The capture
attribute is notably missing.
I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:
public event EventHandler Foo;
If you need more complicated subscription/unsubscription logic, you can do that explicitly:
public event EventHandler Foo
{
add
{
// Subscription logic here
}
remove
{
// Unsubscription logic here
}
}
Simple answer:
In the preamble make sure you have \usepackage{amssymb}
Then in the preamble we can define this simple command: \newcommand{\qed}{\hfill $\blacksquare$}
Then whenever you want the QED symbol to complete a proof, you type \qed
.
If you prefer a hollow square, replace \blacksquare
with \square
You should define the style on the td
element like so:
<html>
<head>
<style type="text/css">
.bb
{
border-bottom: solid 1px black;
}
</style>
</head>
<body>
<table>
<tr>
<td>
Test 1
</td>
</tr>
<tr>
<td class="bb">
Test 2
</td>
</tr>
</table>
</body>
</html>
There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.
Class.getSuperclass() Returns the super class for the given class. Class c = javax.swing.JButton.class.getSuperclass(); The super class of javax.swing.JButton is javax.swing.AbstractButton. Class.getClasses()
Returns all the public classes, interfaces, and enums that are members of the class including inherited members.
Class<?>[] c = Character.class.getClasses();
Character contains two member classes Character.Subset and
Character.UnicodeBlock.Class.getDeclaredClasses() Returns all of the classes interfaces, and enums that are explicitly declared in this class. Class<?>[] c = Character.class.getDeclaredClasses(); Character contains two public member classes Character.Subset and Character.UnicodeBlock and one private class
Character.CharacterCache.
Class.getDeclaringClass() java.lang.reflect.Field.getDeclaringClass() java.lang.reflect.Method.getDeclaringClass() java.lang.reflect.Constructor.getDeclaringClass() Returns the Class in which these members were declared. Anonymous Class Declarations will not have a declaring class but will
have an enclosing class.
import java.lang.reflect.Field; Field f = System.class.getField("out"); Class c = f.getDeclaringClass(); The field out is declared in System. public class MyClass { static Object o = new Object() { public void m() {} }; static Class<c> = o.getClass().getEnclosingClass(); } The declaring class of the anonymous class defined by o is null. Class.getEnclosingClass() Returns the immediately enclosing class of the class. Class c = Thread.State.class().getEnclosingClass(); The enclosing class of the enum Thread.State is Thread. public class MyClass { static Object o = new Object() { public void m() {} }; static Class<c> = o.getClass().getEnclosingClass(); } The anonymous class defined by o is enclosed by MyClass.
If your binary search tree is a red black tree, or you intend to any kind of "tree rotation" operations, duplicate nodes will cause problems. Imagine your tree rule is this:
left < root <= right
Now imagine a simple tree whose root is 5, left child is nil, and right child is 5. If you do a left rotation on the root you end up with a 5 in the left child and a 5 in the root with the right child being nil. Now something in the left tree is equal to the root, but your rule above assumed left < root.
I spent hours trying to figure out why my red/black trees would occasionally traverse out of order, the problem was what I described above. Hopefully somebody reads this and saves themselves hours of debugging in the future!
The field identifiers are indeed C initializer syntax. In C++ just give the values in the correct order without the field names. Unfortunately this means you need to give them all (actually you can omit trailing zero-valued fields and the result will be the same):
address temp_address = { 0, 0, "Hamilton", "Ontario", 0 };
This is how it is done
select * from
(select top 100 percent pointx, pointy from point
where pointtype = 1
order by pointy) A
union all
select * from
(select top 100 percent pointx, pointy from point
where pointtype = 2
order by pointy desc) B
In gradle build i simply:
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-devtools')
removed
**`compile('org.springframework.boot:spring-boot-starter-data-jpa')`**
and it worked for me.
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
This should answer:
How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations
Web Farm Deployment Considerations
If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.
With manually generated key values, the settings should be similar to the following example.
<machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7 AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B" decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F" validation="SHA1" decryption="AES" />
If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.
In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.
Setting Up the Machine Key Using IIS Manager
If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.
Start the management console and then select the web site. Open the machine key configuration:
The machine key control panel has the following settings:
Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.
Click "Generate Keys" under "Actions" on the right side of the panel.
Click "Apply".
and add the following line to the web.config
file in all the webservers
under system.web
tag if it does not exist.
<machineKey
validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>
Please make sure that you have a permanent backup of the machine keys and web.config
file
public function index() {
$user = $this->session->userdata("username");
$file_path = "./images/" . $user . '/';
if (isset($_FILES['multipleUpload'])) {
if (!is_dir('images/' . $user)) {
mkdir('./images/' . $user, 0777, TRUE);
}
$files = $_FILES;
$cpt = count($_FILES ['multipleUpload'] ['name']);
for ($i = 0; $i < $cpt; $i ++) {
$name = time().$files ['multipleUpload'] ['name'] [$i];
$_FILES ['multipleUpload'] ['name'] = $name;
$_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
$_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
$_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
$_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];
$this->upload->initialize($this->set_upload_options($file_path));
if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
{
print_r($this->upload->display_errors());
}
else
{
$this->load->model('uploadModel','um');
$this->um->insertRecord($user,$name);
}
}
} else {
$this->load->view('uploadForm');
}
}
public function set_upload_options($file_path) {
// upload an image options
$config = array();
$config ['upload_path'] = $file_path;
$config ['allowed_types'] = 'gif|jpg|png';
return $config;
}
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
You can right-click on the project, click on export, type 'jar', choose 'Runnable JAR File Export'. There you have the option 'Extract required libraries into generated JAR'.
Two's complement is a clever way of storing integers so that common math problems are very simple to implement.
To understand, you have to think of the numbers in binary.
It basically says,
Let's try it with a mini-byte of 4 bits (we'll call it a nibble - 1/2 a byte).
0000
- zero0001
- one0010
- two0011
- three0100
to 0111
- four to sevenThat's as far as we can go in positives. 23-1 = 7.
For negatives:
1111
- negative one1110
- negative two1101
- negative three1100
to 1000
- negative four to negative eightNote that you get one extra value for negatives (1000
= -8) that you don't for positives. This is because 0000
is used for zero. This can be considered as Number Line of computers.
Distinguishing between positive and negative numbers
Doing this, the first bit gets the role of the "sign" bit, as it can be used to distinguish between nonnegative and negative decimal values. If the most significant bit is 1
, then the binary can be said to be negative, where as if the most significant bit (the leftmost) is 0
, you can say the decimal value is nonnegative.
"Sign-magnitude" negative numbers just have the sign bit flipped of their positive counterparts, but this approach has to deal with interpreting 1000
(one 1
followed by all 0
s) as "negative zero" which is confusing.
"Ones' complement" negative numbers are just the bit-complement of their positive counterparts, which also leads to a confusing "negative zero" with 1111
(all ones).
You will likely not have to deal with Ones' Complement or Sign-Magnitude integer representations unless you are working very close to the hardware.
sys.path
is only searched for Python modules. For dynamic linked libraries, the paths searched must be in LD_LIBRARY_PATH
. Check if your LD_LIBRARY_PATH
includes /usr/local/lib
, and if it doesn't, add it and try again.
Some more information (source):
In Linux, the environment variable LD_LIBRARY_PATH is a colon-separated set of directories where libraries should be searched for first, before the standard set of directories; this is useful when debugging a new library or using a nonstandard library for special purposes. The environment variable LD_PRELOAD lists shared libraries with functions that override the standard set, just as /etc/ld.so.preload does. These are implemented by the loader /lib/ld-linux.so. I should note that, while LD_LIBRARY_PATH works on many Unix-like systems, it doesn't work on all; for example, this functionality is available on HP-UX but as the environment variable SHLIB_PATH, and on AIX this functionality is through the variable LIBPATH (with the same syntax, a colon-separated list).
Update: to set LD_LIBRARY_PATH
, use one of the following, ideally in your ~/.bashrc
or equivalent file:
export LD_LIBRARY_PATH=/usr/local/lib
or
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
Use the first form if it's empty (equivalent to the empty string, or not present at all), and the second form if it isn't. Note the use of export.
I've been to this post about 10 times now and I just wanted to leave my two cents here. You can just unmount it conditionally.
if (renderMyComponent) {
<MyComponent props={...} />
}
All you have to do is remove it from the DOM in order to unmount it.
As long as renderMyComponent = true
, the component will render. If you set renderMyComponent = false
, it will unmount from the DOM.
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
Had same experience, however what did the magic for me is not to change embed to v.
So the code will look like this...
<iframe width="560" height="315" src="https://www.youtube.com/embed/cTYuscQu-Og?Version=3&loop=1&playlist=cTYuscQu-Og" frameborder="0" allowfullscreen></iframe>
Hope it helps...
Here's an iterator-based method.
ifstream file("file", ios::binary);
string fileStr;
istreambuf_iterator<char> inputIt(file), emptyInputIt
back_insert_iterator<string> stringInsert(fileStr);
copy(inputIt, emptyInputIt, stringInsert);
If you don't want to install MySQL workbench, and are looking for an online tool, this might help: http://ondras.zarovi.cz/sql/demo/
I use it quite often to create simple DB schemas for various apps I build.
This is just a possible scenario which happened to me. Well if it helps someone then great: I wrote a complicated app which somewhere along the code I used a function to clear all textboxes values before showing them. Sometime later I tried to set a textbox value using jquery val('value') but I did'nt notice that right after that I invoked the ClearAllInputs method.. so, this could also happen.
You can either do this on a PHP level or on a Javascript level. If you use Javascript, and/or JQuery, you can check and validate if all the checkboxes are checked with a selector...
Jquery also offers several validation libraries. Check out: http://jqueryvalidation.org/
The problem with using Javascript to validate is that it may be bypassed so it is wise to check on the server too.
Example using PHP and assuming you are calling a PO
<?php
if( $_GET["BoxSelect"] )
{
//Process your form here
// Save to database, send email, redirect...
} else {
// Return an error and do not anything
echo "Checkbox is missing";
exit();
}
?>
http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2
NumPy's main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy's array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:
ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.
For me it was a mistake in the pom.xml
- I'd set <scope>provided<scope>
on my dependencies, and this was making them not get copied during the mvn package
stage.
My symptoms were the error message the OP posted, and that the jars were not included in the WEB-INF/lib path inside the .war after package was run. When I removed the scope, the jars appeared in the output, and all loads up fine now.
Another solution just using a standard library and deque:
from collections import deque
import itertools
def moving_average(iterable, n=3):
# http://en.wikipedia.org/wiki/Moving_average
it = iter(iterable)
# create an iterable object from input argument
d = deque(itertools.islice(it, n-1))
# create deque object by slicing iterable
d.appendleft(0)
s = sum(d)
for elem in it:
s += elem - d.popleft()
d.append(elem)
yield s / n
# example on how to use it
for i in moving_average([40, 30, 50, 46, 39, 44]):
print(i)
# 40.0
# 42.0
# 45.0
# 43.0
DO $$
DECLARE
a integer := 10;
b integer := 20;
c integer;
BEGIN
c := a + b;
RAISE NOTICE'Value of c: %', c;
END $$;
It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.
After some googling I found this link:
The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged
So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.
JTAttributedLabel (by mystcolor) lets you use the attributed string support in UILabel under iOS 6 and at the same time its JTAttributedLabel class under iOS 5 through its JTAutoLabel.
Python is case sensitive and needs proper indentation. You need to use lowercase "if", indent your conditions properly and the code has a bug. proceed
will evaluate to y
Specifically, I want to mention one situation, by which you may confuse.
What is the difference between "\0" and ""?
The answer is that "\0"
represents in array is {0 0}
and ""
is {0}
.
Because "\0"
is still a string literal and it will also add "\0"
at the end of it. And ""
is empty but also add "\0"
.
Understanding of this will help you understand "\0"
deeply.
I highly recommend you to use ViewStubs like this
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ViewStub
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout="@layout/empty" />
</FrameLayout>
See the full example from Cyril Mottier
Try this:
Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A2:L" & Lastrow).Select
Let's pretend that the value of Lastrow
is 50. When you use the following:
Range("A2:L2" & Lastrow).Select
Then it is selecting a range from A2 to L250.
There are occasions where I do wish to force code to be in-lined.
For example if I have a complex routine where there are a large number of decisions made within a highly iterative block and those decisions result in similar but slightly differing actions to be carried out. Consider for example, a complex (non DB driven) sort comparer where the sorting algorythm sorts the elements according to a number of different unrelated criteria such as one might do if they were sorting words according to gramatical as well as semantic criteria for a fast language recognition system. I would tend to write helper functions to handle those actions in order to maintain the readability and modularity of the source code.
I know that those helper functions should be in-lined because that is the way that the code would be written if it never had to be understood by a human. I would certainly want to ensure in this case that there were no function calling overhead.
or you can just
<script>
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>
Using auxiliary Result class to track if node is found and current k.
public class KthSmallestElementWithAux {
public int kthsmallest(TreeNode a, int k) {
TreeNode ans = kthsmallestRec(a, k).node;
if (ans != null) {
return ans.val;
} else {
return -1;
}
}
private Result kthsmallestRec(TreeNode a, int k) {
//Leaf node, do nothing and return
if (a == null) {
return new Result(k, null);
}
//Search left first
Result leftSearch = kthsmallestRec(a.left, k);
//We are done, no need to check right.
if (leftSearch.node != null) {
return leftSearch;
}
//Consider number of nodes found to the left
k = leftSearch.k;
//Check if current root is the solution before going right
k--;
if (k == 0) {
return new Result(k - 1, a);
}
//Check right
Result rightBalanced = kthsmallestRec(a.right, k);
//Consider all nodes found to the right
k = rightBalanced.k;
if (rightBalanced.node != null) {
return rightBalanced;
}
//No node found, recursion will continue at the higher level
return new Result(k, null);
}
private class Result {
private final int k;
private final TreeNode node;
Result(int max, TreeNode node) {
this.k = max;
this.node = node;
}
}
}
I found this solution in this article
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
It work like a charm if the height of element is not fixed.
You could also do this:
#!/usr/bin/perl
use strict;
use warnings;
$^I = '.bak'; # create a backup copy
while (<>) {
s/<PREF>/ABCD/g; # do the replacement
print; # print to the modified file
}
Invoke the script with by
./script.pl input_file
You will get a file named input_file
, containing your changes, and a file named input_file.bak
, which is simply a copy of the original file.
if your project has a target above or equal iOS 12 and uses combine you could use this little piece of code.
import Combine
import Network
enum NerworkType {
case wifi
case cellular
case loopBack
case wired
case other
}
protocol ReachabilityServiceContract {
var reachabilityInfos: PassthroughSubject<NWPath, Never> { get set }
var isNetworkAvailable: CurrentValueSubject<Bool, Never> { get set }
var typeOfCurrentConnection: PassthroughSubject<NerworkType, Never> { get set }
}
final class ReachabilityService: ReachabilityServiceContract {
var reachabilityInfos: PassthroughSubject<NWPath, Never> = .init()
var isNetworkAvailable: CurrentValueSubject<Bool, Never> = .init(false)
var typeOfCurrentConnection: PassthroughSubject<NerworkType, Never> = .init()
private let monitor: NWPathMonitor
private let backgroudQueue = DispatchQueue.global(qos: .background)
init() {
monitor = NWPathMonitor()
setUp()
}
init(with interFaceType: NWInterface.InterfaceType) {
monitor = NWPathMonitor(requiredInterfaceType: interFaceType)
setUp()
}
deinit {
monitor.cancel()
}
}
private extension ReachabilityService {
func setUp() {
monitor.pathUpdateHandler = { [weak self] path in
self?.reachabilityInfos.send(path)
switch path.status {
case .satisfied:
self?.isNetworkAvailable.send(true)
case .unsatisfied, .requiresConnection:
self?.isNetworkAvailable.send(false)
@unknown default:
self?.isNetworkAvailable.send(false)
}
if path.usesInterfaceType(.wifi) {
self?.typeOfCurrentConnection.send(.wifi)
} else if path.usesInterfaceType(.cellular) {
self?.typeOfCurrentConnection.send(.cellular)
} else if path.usesInterfaceType(.loopback) {
self?.typeOfCurrentConnection.send(.loopBack)
} else if path.usesInterfaceType(.wiredEthernet) {
self?.typeOfCurrentConnection.send(.wired)
} else if path.usesInterfaceType(.other) {
self?.typeOfCurrentConnection.send(.other)
}
}
monitor.start(queue: backgroudQueue)
}
}
Just subscribe to the variable you want to follow and you should be updated of any changes.
The original query used user variables and ORDER BY
on derived tables; the behavior of both quirks is not guaranteed. Revised answer as follows.
In MySQL 5.x you can use poor man's rank over partition to achieve desired result. Just outer join the table with itself and for each row, count the number of rows lesser than it. In the above case, lesser row is the one with higher rate:
SELECT t.id, t.rate, t.year, COUNT(l.rate) AS rank
FROM t
LEFT JOIN t AS l ON t.id = l.id AND t.rate < l.rate
GROUP BY t.id, t.rate, t.year
HAVING COUNT(l.rate) < 5
ORDER BY t.id, t.rate DESC, t.year
| id | rate | year | rank |
|-----|------|------|------|
| p01 | 8.0 | 2006 | 0 |
| p01 | 7.4 | 2003 | 1 |
| p01 | 6.8 | 2008 | 2 |
| p01 | 5.9 | 2001 | 3 |
| p01 | 5.3 | 2007 | 4 |
| p02 | 12.5 | 2001 | 0 |
| p02 | 12.4 | 2004 | 1 |
| p02 | 12.2 | 2002 | 2 |
| p02 | 10.3 | 2003 | 3 |
| p02 | 8.7 | 2000 | 4 |
Note that if the rates had ties, for example:
100, 90, 90, 80, 80, 80, 70, 60, 50, 40, ...
The above query will return 6 rows:
100, 90, 90, 80, 80, 80
Change to HAVING COUNT(DISTINCT l.rate) < 5
to get 8 rows:
100, 90, 90, 80, 80, 80, 70, 60
Or change to ON t.id = l.id AND (t.rate < l.rate OR (t.rate = l.rate AND t.pri_key > l.pri_key))
to get 5 rows:
100, 90, 90, 80, 80
In MySQL 8 or later just use the RANK
, DENSE_RANK
or ROW_NUMBER
functions:
SELECT *
FROM (
SELECT *, RANK() OVER (PARTITION BY id ORDER BY rate DESC) AS rnk
FROM t
) AS x
WHERE rnk <= 5
Use Remove()...
string foo = "1234567890";
int trimLength = 5;
if (foo.Length > trimLength) foo = foo.Remove(trimLength);
// foo is now "12345"
EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value
syntax is incorrect.
I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
error message. In 2008, the modified script is still successful.
declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)
For SQL server 2012,
First, log in to the SQL server as an administrator and go to Security tab
Then move into Server Roles and double click on sysadmin role
Now add user which you want to give permission to create Database by clicking Add button
Click OK button and now run the query
Hope this will help for someone
This method may be equivalent to Kyle's.
Say your list is of size n and you want k elements.
Random rand = new Random();
for(int i = 0; k>0; ++i)
{
int r = rand.Next(0, n-i);
if(r<k)
{
//include element i
k--;
}
}
Works like a charm :)
-Alex Gilbert
let qs = event.queryStringParameters;
const query = Object.keys(qs).map(key => key + '=' + qs[key]).join('&');
In your script you can add the following to the lines that you know are going to give an output:
some_code 2>>/dev/null
Or else you can also try
some_code >>/dev/null
A better and more organized way of overriding Devise controllers and views using namespaces:
Create the following folders:
app/controllers/my_devise
app/views/my_devise
Put all controllers that you want to override into app/controllers/my_devise and add MyDevise
namespace to controller class names. Registrations
example:
# app/controllers/my_devise/registrations_controller.rb
class MyDevise::RegistrationsController < Devise::RegistrationsController
...
def create
# add custom create logic here
end
...
end
Change your routes accordingly:
devise_for :users,
:controllers => {
:registrations => 'my_devise/registrations',
# ...
}
Copy all required views into app/views/my_devise
from Devise gem folder or use rails generate devise:views
, delete the views you are not overriding and rename devise
folder to my_devise
.
This way you will have everything neatly organized in two folders.
In Android studio 2.2 you can directly analyze the apk. Goto build- analyze apk. Select the apk, navigate to androidmanifest.xml. You can see the details of androidmanifest.
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
Another useful tool for this from the command line interface, is the pager command.
eg
pager grep -v Sleep | more; show full processlist;
Then you can page through the results.
You can also look for certain users, IPs or queries with grep or sed in this way.
The pager command is persistent per session.
I'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:
public List<Integer> asList(final int[] is)
{
return new AbstractList<Integer>() {
public Integer get(int i) { return is[i]; }
public int size() { return is.length; }
};
}
This function worked perfectly for me. It detects Edge as well.
Originally from this Codepen:
https://codepen.io/gapcode/pen/vEJNZN
/**
* detect IE
* returns version of IE or false, if browser is not Internet Explorer
*/
function detectIE() {
var ua = window.navigator.userAgent;
// Test values; Uncomment to check result …
// IE 10
// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11
// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// Edge 12 (Spartan)
// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
// Edge 13
// ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
Then you can use if (detectIE()) { /* do IE stuff */ }
in your code.
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
Start monogdb service using
sudo service mongod start
then from the new window or terminal start mongo client using
mongo
The way I understand it is that they are subtly different by design (and I am certainly open for correction): filter(A, B)
will first filter according to A and then subfilter according to B, while filter(A).filter(B)
will return a row that matches A 'and' a potentially different row that matches B.
Look at the example here:
https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
particularly:
Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects
...
In this second example (filter(A).filter(B)), the first filter restricted the queryset to (A). The second filter restricted the set of blogs further to those that are also (B). The entries select by the second filter may or may not be the same as the entries in the first filter.`
Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".
See
Rule of thumb would be to use slash with things that do BEGIN .. END
or where you can use CREATE OR REPLACE
.
For inserts that need to be unique use
INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT
FROM my_table
WHERE <identify data that you are trying to insert>)
A native debugger is being made available as an extension to JupyterLab. Released a few weeks ago, this can be installed by getting the relevant extension, as well as xeus-python kernel (which notably comes without the magics well-known to ipykernel users):
jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge
This enables a visual debugging experience well-known from other IDEs.
Source: A visual debugger for Jupyter
Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...
from operator import lt, gt
def ultimate (l,op,c=1,u=0):
try:
if op(l[c],l[u]):
u = c
c += 1
return ultimate(l,op,c,u)
except IndexError:
return l[u]
def minimum (l):
return ultimate(l,lt)
def maximum (l):
return ultimate(l,gt)
The solution is simple. Use this to set yourself apart from obvious choices.
you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">
$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');
The best solution to this in my opinion is this:
Create a custom filter which can be in a common.module.js file for example - used through out your app:
var app = angular.module('common.module', []);
// html filter (render text as html)
app.filter('html', ['$sce', function ($sce) {
return function (text) {
return $sce.trustAsHtml(text);
};
}])
Usage:
<span ng-bind-html="yourDataValue | html"></span>
Now - I don't see why the directive ng-bind-html
does not trustAsHtml
as part of its function - seems a bit daft to me that it doesn't
Anyway - that's the way I do it - 67% of the time, it works ever time.
Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.
Right-click project in Package explorer Build path -> Add external archives...
Select your ojdbc6.jar archive
Press OK
Or
Go through this link and read and do carefully.
The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.
A concise ES6 approach:
fetch('https://example.com?' + new URLSearchParams({
foo: 'value',
bar: 2,
}))
URLSearchParams's toString() function will convert the query args into a string that can be appended onto the URL. In this example, toString() is called implicitly when it gets concatenated with the URL. You will likely want to call toString() explicitly to improve readability.
IE does not support URLSearchParams (or fetch), but there are polyfills available.
If using node, you can add the fetch API through a package like node-fetch. URLSearchParams comes with node, and can be found as a global object since version 10. In older version you can find it at require('url').URLSearchParams
.
One practical use is if you have committed to your local repo already (ie. git commit -m ) then you can reverse that last commit by doing git reset --soft HEAD~1
Also for your knowledge, if you have staged your changes already (ie with git add .) then you can reverse the staging by doing git reset --mixed HEAD or i've commonly also just used git reset
lastly, git reset --hard wipes everything out including your local changes. The ~ after head tells you how many commits to go to from the top.
When I looked at the solutions in the other answers I saw some things that I know are bad for performance. I was going to put them in a comment but I thought it was better to benchmark it and share the results. You can test it yourself. Below are my results (ymmv) normalized after the fastest operation in each browser (multiply the 1.0 time with the normalized value to get the absolute time in ms).
Chrome Firefox Opera MSIE Safari Node ------------------------------------------------------------------- 1.0 time 37ms 73ms 68ms 184ms 73ms 21ms if-immediate 1.0 1.0 1.0 2.6 1.0 1.0 if-indirect 1.2 1.8 3.3 3.8 2.6 1.0 switch-immediate 2.0 1.1 2.0 1.0 2.8 1.3 switch-range 38.1 10.6 2.6 7.3 20.9 10.4 switch-range2 31.9 8.3 2.0 4.5 9.5 6.9 switch-indirect-array 35.2 9.6 4.2 5.5 10.7 8.6 array-linear-switch 3.6 4.1 4.5 10.0 4.7 2.7 array-binary-switch 7.8 6.7 9.5 16.0 15.0 4.9
Test where performed on Windows 7 32bit with the folowing versions: Chrome 21.0.1180.89m, Firefox 15.0, Opera 12.02, MSIE 9.0.8112, Safari 5.1.7. Node was run on a Linux 64bit box because the timer resolution on Node.js for Windows was 10ms instead of 1ms.
This is the fastest in all tested environments, except in ... drumroll MSIE! (surprise, surprise). This is the recommended way to implement it.
if (val < 1000) { /*do something */ } else
if (val < 2000) { /*do something */ } else
...
if (val < 30000) { /*do something */ } else
This is a variant of switch-indirect-array
but with if
-statements instead and performs much faster than switch-indirect-array
in almost all tested environments.
values=[
1000, 2000, ... 30000
];
if (val < values[0]) { /* do something */ } else
if (val < values[1]) { /* do something */ } else
...
if (val < values[29]) { /* do something */ } else
This is pretty fast in all tested environments, and actually the fastest in MSIE. It works when you can do a calculation to get an index.
switch (Math.floor(val/1000)) {
case 0: /* do something */ break;
case 1: /* do something */ break;
...
case 29: /* do something */ break;
}
This is about 6 to 40 times slower than the fastest in all tested environments except for Opera where it takes about one and a half times as long. It is slow because the engine has to compare the value twice for each case. Surprisingly it takes Chrome almost 40 times longer to complete this compared to the fastest operation in Chrome, while MSIE only takes 6 times as long. But the actual time difference was only 74ms in favor to MSIE at 1337ms(!).
switch (true) {
case (0 <= val && val < 1000): /* do something */ break;
case (1000 <= val && val < 2000): /* do something */ break;
...
case (29000 <= val && val < 30000): /* do something */ break;
}
This is a variant of switch-range
but with only one compare per case and therefore faster, but still very slow except in Opera. The order of the case statement is important since the engine will test each case in source code order ECMAScript262:5 12.11
switch (true) {
case (val < 1000): /* do something */ break;
case (val < 2000): /* do something */ break;
...
case (val < 30000): /* do something */ break;
}
In this variant the ranges is stored in an array. This is slow in all tested environments and very slow in Chrome.
values=[1000, 2000 ... 29000, 30000];
switch(true) {
case (val < values[0]): /* do something */ break;
case (val < values[1]): /* do something */ break;
...
case (val < values[29]): /* do something */ break;
}
This is a combination of a linear search of values in an array, and the switch statement with fixed values. The reason one might want to use this is when the values isn't known until runtime. It is slow in every tested environment, and takes almost 10 times as long in MSIE.
values=[1000, 2000 ... 29000, 30000];
for (sidx=0, slen=values.length; sidx < slen; ++sidx) {
if (val < values[sidx]) break;
}
switch (sidx) {
case 0: /* do something */ break;
case 1: /* do something */ break;
...
case 29: /* do something */ break;
}
This is a variant of array-linear-switch
but with a binary search.
Unfortunately it is slower than the linear search. I don't know if it is my implementation or if the linear search is more optimized. It could also be that the keyspace is to small.
values=[0, 1000, 2000 ... 29000, 30000];
while(range) {
range = Math.floor( (smax - smin) / 2 );
sidx = smin + range;
if ( val < values[sidx] ) { smax = sidx; } else { smin = sidx; }
}
switch (sidx) {
case 0: /* do something */ break;
...
case 29: /* do something */ break;
}
If performance is important, use if
-statements or switch
with immediate values.
Object files are codes that are dependent on functions, symbols, and text to run the program. Just like old telex machines, which required teletyping to send signals to other telex machine.
In the same way processor's require binary code to run, object files are like binary code but not linked. Linking creates additional files so that the user does not have to have compile the C language themselves. Users can directly open the exe file once the object file is linked with some compiler like c language , or vb etc.
The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).
You can return it as an int by casting it as follows:
string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";
int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();
LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.
In LL(1)
For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).
Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique
What do you want to force yourself (or another programmer) to adhere to and when do you want to allow yourself (or another programmer) more freedom. It has been argued that inheritance is helpful when you want to force someone into a way of dealing with/solving a particular problem so they can't head off in the wrong direction.
Is-a
and Has-a
is a helpful rule of thumb.
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show
function and savefig
function.
before you plot:
fig = pylab.figure()
ax = fig.gca()
ax.set_autoscale_on(False)
This is to request an ax
which is subplot(1,1,1)
.
During the plot:
ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
After the plot:
To show the image :
fig.show()
To save the figure :
fig.savefig('the name of your figure')
I find out that put axis
at the front of the code won't work even though I have set autoscale_on
to False
.
I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation.
sa
is a system administrator account which comes with SQL Server by default. As you know might already know, you can use two ways to log in to SQL Server.
Therefore there are connection strings which suitable for each scenario (such as Windows authentication, localdb, etc.). Use SQL Server Connection Strings for ASP.NET Web Applications to build your connection string. These are XML tags. You just need a value of connectionString.
Below is for Python-
df.select("col_name").rdd.flatMap(lambda x: x).collect()
SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).
(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).
You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.
It's embedded in a standard XML comment, and looks like this:
<!--#include virtual="top.shtml" -->
It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.
You can read more in this Wikipedia article.
First of all if the size of the image is smaller than the container, then only "img-fluid" class will not solve your problem. you have to set the width of image to 100%, for that you can use Bootstrap class "w-100". keep in mind that "container-fluid" and "col-12" class sets left and right padding to 15px and "row" class sets left and right margin to "-15px" by default. make sure to set them to 0.
Note:
"px-0" is a bootstrap class which sets left and right padding to 0 and
"mx-0" is a bootstrap class which sets left and right margin to 0
P.S. i am using Bootstrap 4.0 version.
<div class="container-fluid px-0">
<div class="row mx-0">
<div class="col-12 px-0">
<img src="images/top.jpg" class="img-fluid w-100">
</div>
</div>
</div>
Here is the actual code that does it...
$(document).ready(function()
{
var oTable = $('#myTable').dataTable();
// Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
oTable.fnSort( [ [1,'asc'] ] );
// And to sort another column descending (at position 2 in the array (base 0).
oTable.fnSort( [ [2,'desc'] ] );
} );
To not have the column highlighted, modify the CSS like so:
table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }
Try
df.loc[df.my_channel > 20000, 'my_channel'] = 0
Note: Since v0.20.0, ix
has been deprecated in favour of loc
/ iloc
.
All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover()
is the better choice:
$(window).hover(function(event) {
if (event.fromElement) {
console.log("inactive");
} else {
console.log("active");
}
});
This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.