My Answer: All of the following should be overridden (i.e. describe them all within columndefinition
, if appropriate):
length
precision
scale
nullable
unique
i.e. the column DDL will consist of: name
+ columndefinition
and nothing else.
Rationale follows.
Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.
Other annotation purely logical - properties used in-memory in java to control JPA processing.
That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true)
and once via @Column(...,nullable=true)
. Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.
In your example, length and nullable properties are overridden and redundant.
So, when specifying columnDefinition, what other properties of @Column are made redundant?
In JPA Spec & javadoc:
columnDefinition
definition:
The SQL fragment that is used when generating the DDL for the column.
columnDefinition
default:
Generated SQL to create a column of the inferred type.
The following examples are provided:
@Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
@Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
And, err..., that's it really. :-$ ?!
Does columnDefinition override other properties provided in the same annotation?
The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.
The following can be safely implied from examples provided in the JPA spec
name
& table
can be used in conjunction with columnDefinition
, neither are overriddennullable
is overridden/made redundant by columnDefinition
The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):
length
, precision
, scale
are overridden/made redundant by the columnDefinition
- they are integral to the typeinsertable
and updateable
are provided separately and never included in columnDefinition
, because they control SQL generation in-memory, before it is emmitted to the database.That leaves just the "unique
" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.
Test My Answer For columns "A" & "B", respectively:
@Column(name="...", table="...", insertable=true, updateable=false,
columndefinition="NUMBER(5,2) NOT NULL UNIQUE"
@Column(name="...", table="...", insertable=false, updateable=true,
columndefinition="NVARCHAR2(100) NULL"
Just in case someone is using Bootstrap, I was able to add more than one class:
<a href="" class="baseclass" th:classappend="${isAdmin} ?: 'text-danger font-italic' "></a>
AFAIK you must reformat your String in ISO format to be able to cast it as a Date:
cast(concat(substr(STR_DMY,7,4), '-',
substr(STR_DMY,1,2), '-',
substr(STR_DMY,4,2)
)
as date
) as DT
To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()
=> did you check the documentation by the way?
Try like this:
select field1, array_to_string(array_agg(field2), ',')
from table1
group by field1;
On MSDN, the documentation for Task.Run Method (Action) provides this example which shows how to run a method asynchronously from main
:
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
ShowThreadInfo("Application");
var t = Task.Run(() => ShowThreadInfo("Task") );
t.Wait();
}
static void ShowThreadInfo(String s)
{
Console.WriteLine("{0} Thread ID: {1}",
s, Thread.CurrentThread.ManagedThreadId);
}
}
// The example displays the following output:
// Application thread ID: 1
// Task thread ID: 3
Note this statement that follows the example:
The examples show that the asynchronous task executes on a different thread than the main application thread.
So, if instead you want the task to run on the main application thread, see the answer by @StephenCleary.
And regarding the thread on which the task runs, also note Stephen's comment on his answer:
You can use a simple
Wait
orResult
, and there's nothing wrong with that. But be aware that there are two important differences: 1) allasync
continuations run on the thread pool rather than the main thread, and 2) any exceptions are wrapped in anAggregateException
.
(See Exception Handling (Task Parallel Library) for how to incorporate exception handling to deal with an AggregateException
.)
Finally, on MSDN from the documentation for Task.Delay Method (TimeSpan), this example shows how to run an asynchronous task that returns a value:
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var t = Task.Run(async delegate
{
await Task.Delay(TimeSpan.FromSeconds(1.5));
return 42;
});
t.Wait();
Console.WriteLine("Task t Status: {0}, Result: {1}",
t.Status, t.Result);
}
}
// The example displays the following output:
// Task t Status: RanToCompletion, Result: 42
Note that instead of passing a delegate
to Task.Run
, you can instead pass a lambda function like this:
var t = Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1.5));
return 42;
});
Create a custom adapter with a custom layout for your spinner.
Spinner spinner = (Spinner) findViewById(R.id.pioedittxt5);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.travelreasons, R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
R.layout.simple_spinner_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
R.layout.simple_spinner_dropdown_item
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerDropDownItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="?android:attr/dropdownListPreferredItemHeight"
android:ellipsize="marquee" />
In styles add your custom dimensions and height as per your requirement.
<style name="spinnerItemStyle" parent="android:Widget.TextView.SpinnerItem">
</style>
<style name="spinnerDropDownItemStyle" parent="android:TextAppearance.Widget.TextView.SpinnerItem">
</style>
No you can not do that, MyClass *myclass
will define a pointer (memory for the pointer is allocated on stack) which is pointing at a random memory location. Trying to use this pointer will cause undefined behavior.
In C++, you can create objects either on stack or heap like this:
MyClass myClass;
myClass.DoSomething();
Above will allocate myClass on stack (the term is not there in the standard I think but I am using for clarity). The memory allocated for the object is automatically released when myClass
variable goes out of scope.
Other way of allocating memory is to do a new
. In that case, you have to take care of releasing the memory by doing delete
yourself.
MyClass* p = new MyClass();
p->DoSomething();
delete p;
Remeber the delete
part, else there will be memory leak.
I always prefer to use the stack allocated objects whenever possible as I don't have to be bothered about the memory management.
Booting from CD to rescue the installation and editing /etc/selinux/config: changed SELINUX from enforcing to permissive. Rebooted and system booted
/etc/selinux/config
before change:
SELINUX=enforcing and SELINUXTYPE=permissive
/etc/selinux/config
after change:
SELINUX=permissive and SELINUXTYPE=permissive
jQuery Form Validation Custom Error Message -tutsmake
$(document).ready(function(){_x000D_
$("#registration").validate({_x000D_
// Specify validation rules_x000D_
rules: {_x000D_
firstname: "required",_x000D_
lastname: "required",_x000D_
email: {_x000D_
required: true,_x000D_
email: true_x000D_
}, _x000D_
phone: {_x000D_
required: true,_x000D_
digits: true,_x000D_
minlength: 10,_x000D_
maxlength: 10,_x000D_
},_x000D_
password: {_x000D_
required: true,_x000D_
minlength: 5,_x000D_
}_x000D_
},_x000D_
messages: {_x000D_
firstname: {_x000D_
required: "Please enter first name",_x000D_
}, _x000D_
lastname: {_x000D_
required: "Please enter last name",_x000D_
}, _x000D_
phone: {_x000D_
required: "Please enter phone number",_x000D_
digits: "Please enter valid phone number",_x000D_
minlength: "Phone number field accept only 10 digits",_x000D_
maxlength: "Phone number field accept only 10 digits",_x000D_
}, _x000D_
email: {_x000D_
required: "Please enter email address",_x000D_
email: "Please enter a valid email address.",_x000D_
},_x000D_
},_x000D_
_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
.error{_x000D_
color: red;_x000D_
}_x000D_
label,_x000D_
input,_x000D_
button {_x000D_
border: 0;_x000D_
margin-bottom: 3px;_x000D_
display: block;_x000D_
width: 100%;_x000D_
}_x000D_
.common_box_body {_x000D_
padding: 15px;_x000D_
border: 12px solid #28BAA2;_x000D_
border-color: #28BAA2;_x000D_
border-radius: 15px;_x000D_
margin-top: 10px;_x000D_
background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
<h2>Registration</h2>_x000D_
<form action="#" name="registration" id="registration">_x000D_
_x000D_
<label for="firstname">First Name</label>_x000D_
<input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
_x000D_
<label for="lastname">Last Name</label>_x000D_
<input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
_x000D_
<label for="phone">Phone</label>_x000D_
<input type="text" name="phone" id="phone" placeholder="8889988899"><br> _x000D_
_x000D_
<label for="email">Email</label>_x000D_
<input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
_x000D_
<label for="password">Password</label>_x000D_
<input type="password" name="password" id="password" placeholder=""><br>_x000D_
_x000D_
<input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
If you are using custom filter, you might want to hide search box but still want to enable the filter function, so bFilter: false
is not the way. Use dom: 'lrtp'
instead, default is 'lfrtip'
. Documentation: https://datatables.net/reference/option/dom
As for every "3rd-party" library in flavor of a JAR file which is to be used by the webapp, just copy/drop the physical JAR file in webapp's /WEB-INF/lib
. It will then be available in webapp's default classpath. Also, Eclipse is smart enough to notice that. No need to hassle with buildpath. However, make sure to remove all unnecessary references you added before, else it might collide.
An alternative is to install it in the server itself by dropping the physical JAR file in server's own /lib
folder. This is required when you're using server-provided JDBC connection pool data source which in turn needs the MySQL JDBC driver.
I got it work by overriding annotation with XML file for Postgres. Annotation is kept for Oracle. In my opinion, in this case it would be best we override the mapping of this trouble-some enity with xml mapping. We can override single / multiple entities with xml mapping. So we would use annotation for our mainly-supported database, and a xml file for each other database.
Note: we just need to override one single class , so it is not a big deal. Read more from my example Example to override annotation with XML
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);
You could create a custom HashMap class for that in php. example as shown below containing the basic HashMap attributes such as get and set.
class HashMap{
public $arr;
function init() {
function populate() {
return null;
}
// change to 999 for efficiency
$this->arr = array_map('populate', range(0, 9));
return $this->arr;
}
function get_hash($key) {
$hash = 0;
for ($i=0; $i < strlen($key) ; $i++) {
$hash += ord($key[$i]);
}
// arr index starts from 0
$hash_idx = $hash % (count($this->arr) - 1);
return $hash_idx;
}
function add($key, $value) {
$idx = $this->get_hash($key);
if ($this->arr[$idx] == null) {
$this->arr[$idx] = [$value];
} else{
$found = false;
$content = $this->arr[$idx];
$content_idx = 0;
foreach ($content as $item) {
// checking if they have same number of streams
if ($item == $value) {
$content[$content_idx] = [$value];
$found = true;
break;
}
$content_idx++;
}
if (!$found) {
// $value is already an array
array_push($content, $value);
// updating the array
$this->arr[$idx] = $content;
}
}
return $this->arr;
}
function get($key) {
$idx = $this->get_hash($key);
$content = $this->arr[$idx];
foreach ($content as $item) {
if ($item[1] == $key) {
return $item;
break;
}
}
}
}
Hope this was useful
jQuery simple solution.
Should be triggered by user's click.
$("<textarea/>").appendTo("body").val(text).select().each(function () {
document.execCommand('copy');
}).remove();
Try Jedi! There's a Vim plugin at https://github.com/davidhalter/jedi-vim.
It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).
It's the same problem with managed and easy to use programming language as always - they are slow (and sometimes memory-eating).
These are languages to do control rather than processing. If I would have to write application to transform images and had to use Python too all the processing could be written in C++ and connected to Python via bindings while interface and process control would be definetely Python.
You of course need to use the correct locale. This question will help.
Add this to your macro and it will recalculate all the cells and formulae.
Call Application.CalculateFullRebuild
Hope it has been already fixed.
PS The above code is for the people looking for a macro to solve the issue.
Some people say C doesn't have namespaces but that is not technically correct. It has three:
enum
, union
, and struct
)typedef enum { } XYZ;
declares an anonymous enumeration and imports it into the global namespace with the name XYZ
.
typedef enum ABC { } XYZ;
declares an enum named ABC
in the tag namespace, then imports it into the global namespace as XYZ
.
Some people don't want to bother with the separate namespaces so they typedef everything. Others never typedef because they want the namespacing.
This is my solution using the for i in range loop:
def reverse(string):
tmp = ""
for i in range(1,len(string)+1):
tmp += string[len(string)-i]
return tmp
It's pretty easy to understand. I start from 1 to avoid index out of bound.
If you didnt know that mojb
is of type MyClass
, then how can you create that variable?
If MyClass is an interface type, or a super type, then there is no need to do a cast.
I had the same issue. The length of my column was too short.
What you can do is either increase the length or shorten the text you want to put in the database.
By close, do you mean you want the current instance of the console app to close, or do you want the application process, to terminate? Missed that all important exit code:
Environment.Exit(0);
Or to close the current instance of the form:
this.Close();
Useful link.
You could use the ngSwitch directive:
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.
This is just an (untested) example. It can and should be optimized:
HTML:
<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>
Directive:
app.directive('conditionalTemplate', function($http, $compile) {
return {
restrict: 'E',
require: '^ngModel',
link: function(sope, element, attrs, ctrl) {
// get template with $http
// check model via ctrl.$viewValue
// compile with $compile
// replace element with element.replaceWith()
}
};
});
This doesn't apply to the current .NET implementation, but one thing to keep in mind with garbage collected/managed runtimes is the allocated size of an object can change throughout the lifetime of the program. For example, some generational garbage collectors (such as the Generational/Ulterior Reference Counting Hybrid collector) only need to store certain information after an object is moved from the nursery to the mature space.
This makes it impossible to create a reliable, generic API to expose the object size.
My solution: Because all others did not work for me. I deleted the symlinks at C:\ProgramData\Oracle\Java\javapath. this makes eclipse to run with the jre declared in the PATH. This is better for me because I want to develop Java with the JRE I chose, not the system JRE. Often you want to develop with older versions and such
class MathsOperations:
def __init__ (self, x, y):
self.a = x
self.b = y
def testAddition (self):
return (self.a + self.b)
def testMultiplication (self):
return (self.a * self.b)
then
temp = MathsOperations()
print(temp.testAddition())
SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.
When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.
There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.
The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.
Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).
If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.
Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.
Traditional (well not all the way back to the beginning) arm syntax:
...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...
stm is store multiple you can save more than one register at a time, up to all of them in one instruction.
db means decrement before, this is a downward moving stack from high addresses to lower addresses.
You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.
The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.
Then in the brackets { } list the registers you want to save, comma separated.
ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm
So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.
Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:
void myfun ( void )
{
int somedata;
}
In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.
A global variable would not be found on the stack.
Going back...
Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.
...
bl myfun
<--- the return from my fun returns here
...
myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
<---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.
So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.
ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use
push {r5,r6}
...
pop {r5,r6}
in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).
No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.
push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}
assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.
The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.
If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.
sorry for the very long post, hope it is useful.
Note : This answer is now out-of-date. You are now required to have an API key to use google maps. Read More
you need to change your API from V2 to V3, Since Google Map Version 3 don't required API Key
Check this out..
write your script
as
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
doesn't
<?php get_the_category( $id ) ?>
do just that, inside the loop?
For outside:
<?php
global $post;
$categories = get_the_category($post->ID);
var_dump($categories);
?>
While creating the object for the progressbar check the following.
This fails:
dialog = new ProgressDialog(getApplicationContext());
While adding the activities context works..
dialog = new ProgressDialog(MainActivity.this);
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
I found a easy solution: make the tag " li "be inside the tag " a ":
<a href="#"><li>Something1</li></a>
Have you tried what is on the sample. I am new to this but here is the command: puppet --test --trace --debug. I hope this helps.
You're trying to access a 3 dimensional array with 4 de-references
You only need 3 loops instead of 4, or int myArray[10][10][10][10];
Suppose you need to pass Username
and Password
to Stored Procedure and know whether login is successful or not and check if any error has occurred in Stored Procedure.
public bool IsLoginSuccess(string userName, string password)
{
try
{
SqlConnection SQLCon = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
SQLCon.Open();
sqlcomm.CommandType = CommandType.StoredProcedure;
sqlcomm.CommandText = "spLoginCheck"; // Stored Procedure name
sqlcomm.Parameters.AddWithValue("@Username", userName); // Input parameters
sqlcomm.Parameters.AddWithValue("@Password", password); // Input parameters
// Your output parameter in Stored Procedure
var returnParam1 = new SqlParameter
{
ParameterName = "@LoginStatus",
Direction = ParameterDirection.Output,
Size = 1
};
sqlcomm.Parameters.Add(returnParam1);
// Your output parameter in Stored Procedure
var returnParam2 = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam2);
sqlcomm.ExecuteNonQuery();
string error = (string)sqlcomm.Parameters["@Error"].Value;
string retunvalue = (string)sqlcomm.Parameters["@LoginStatus"].Value;
}
catch (Exception ex)
{
}
return false;
}
Your connection string in Web.Config
<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Databasename;User id=yourusername;Password=yourpassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
And here is the Stored Procedure for reference
CREATE PROCEDURE spLoginCheck
@Username Varchar(100),
@Password Varchar(100) ,
@LoginStatus char(1) = null output,
@Error Varchar(1000) output
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN
SET @Error = 'None'
SET @LoginStatus = ''
IF EXISTS(SELECT TOP 1 * FROM EMP_MASTER WHERE EMPNAME=@Username AND EMPPASSWORD=@Password)
BEGIN
SET @LoginStatus='Y'
END
ELSE
BEGIN
SET @LoginStatus='N'
END
END
END TRY
BEGIN CATCH
BEGIN
SET @Error = ERROR_MESSAGE()
END
END CATCH
END
GO
In my case this (a with caret) occurred in code I generated from visual studio using my own tool for generating code. It was easy to solve:
Select single spaces ( ) in the document. You should be able to see lots of single spaces that are looking different from the other single spaces, they are not selected. Select these other single spaces - they are the ones responsible for the unwanted characters in the browser. Go to Find and Replace with single space ( ). Done.
PS: It's easier to see all similar characters when you place the cursor on one or if you select it in VS2017+; I hope other IDEs may have similar features
Aforementioned answers are great, just putting few points I see might be helpful:
Func is built-in delegate type
Func delegate type must return a value. Use Action delegate if no return type needed.
Func delegate type can have zero to 16 input parameters.
Func delegate does not allow ref and out parameters.
Func delegate type can be used with an anonymous method or lambda expression.
Func<int, int, int> Sum = (x, y) => x + y;
document.getElementById(button_id).innerHTML = 'Lock';
You need the python-dev
package which contains Python.h
@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
if you use one line folder or file
chmod 755 $(find /yourfolder -type d)
chmod 644 $(find /yourfolder -type f)
To write in the Visual Studio output window I used IVsOutputWindow
and IVsOutputWindowPane
. I included as members in my OutputWindow
class which look like this :
public class OutputWindow : TextWriter
{
#region Members
private static readonly Guid mPaneGuid = new Guid("AB9F45E4-2001-4197-BAF5-4B165222AF29");
private static IVsOutputWindow mOutputWindow = null;
private static IVsOutputWindowPane mOutputPane = null;
#endregion
#region Constructor
public OutputWindow(DTE2 aDte)
{
if( null == mOutputWindow )
{
IServiceProvider serviceProvider =
new ServiceProvider(aDte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
mOutputWindow = serviceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
}
if (null == mOutputPane)
{
Guid generalPaneGuid = mPaneGuid;
mOutputWindow.GetPane(ref generalPaneGuid, out IVsOutputWindowPane pane);
if ( null == pane)
{
mOutputWindow.CreatePane(ref generalPaneGuid, "Your output window name", 0, 1);
mOutputWindow.GetPane(ref generalPaneGuid, out pane);
}
mOutputPane = pane;
}
}
#endregion
#region Properties
public override Encoding Encoding => System.Text.Encoding.Default;
#endregion
#region Public Methods
public override void Write(string aMessage) => mOutputPane.OutputString($"{aMessage}\n");
public override void Write(char aCharacter) => mOutputPane.OutputString(aCharacter.ToString());
public void Show(DTE2 aDte)
{
mOutputPane.Activate();
aDte.ExecuteCommand("View.Output", string.Empty);
}
public void Clear() => mOutputPane.Clear();
#endregion
}
If you have a big text to write in output window you usually don't want to freeze the UI. In this purpose you can use a Dispatcher
. To write something in output window using this implementation now you can simple do this:
Dispatcher mDispatcher = HwndSource.FromHwnd((IntPtr)mDte.MainWindow.HWnd).RootVisual.Dispatcher;
using (OutputWindow outputWindow = new OutputWindow(mDte))
{
mDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
outputWindow.Write("Write what you want here");
}));
}
In my case, this error was due to the Network connection error that i was noticed in log.
Now you can hover the key input and select "file", which will give you a file selector in the value column:
Button OnClickListener implementation from function in android using kotlin.
Very First Create Button View From .xml File
`<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button2"
android:layout_weight="0.5"/>`
//and create button instance in Activity
private var btn1:Button?=null
or
//For Late Initialization can Follow like this,
private lateinit var btn1:Button
//in onCreate,
btn1=findViewById(R.id.btn1) as Button
btn1?.setOnClickListener { btn1Click() }
//implementing button OnClick event from Function,
private fun btn1Click() {
Toast.makeText(this, "button1", Toast.LENGTH_LONG).show()
}
There is actually a property for this in the CSS4 media query draft.
The ‘pointer’ media feature is used to query about the presence and accuracy of a pointing device such as a mouse. If a device has multiple input mechanisms, it is recommended that the UA reports the characteristics of the least capable pointing device of the primary input mechanisms. This media query takes the following values:
‘none’
- The input mechanism of the device does not include a pointing device.‘coarse’
- The input mechanism of the device includes a pointing device of limited accuracy.‘fine’
- The input mechanism of the device includes an accurate pointing device.
This would be used as such:
/* Make radio buttons and check boxes larger if we have an inaccurate pointing device */
@media (pointer:coarse) {
input[type="checkbox"], input[type="radio"] {
min-width:30px;
min-height:40px;
background:transparent;
}
}
I also found a ticket in the Chromium project related to this.
Browser compatibility can be tested at Quirksmode. These are my results (22 jan 2013):
https://jsfiddle.net/2w0k5tz8/
function remove_duplicates(array_){
var ret_array = new Array();
for (var a = array_.length - 1; a >= 0; a--) {
for (var b = array_.length - 1; b >= 0; b--) {
if(array_[a] == array_[b] && a != b){
delete array_[b];
}
};
if(array_[a] != undefined)
ret_array.push(array_[a]);
};
return ret_array;
}
console.log(remove_duplicates(Array(1,1,1,2,2,2,3,3,3)));
Loop through, remove duplicates, and create a clone array place holder because the array index will not be updated.
Loop backward for better performance ( your loop wont need to keep checking the length of your array)
Try this:
import java.net.HttpURLConnection;
URL url = new URL("http://www.myurl.com/sample.xml");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
huc.setConnectTimeout(15 * 1000);
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
huc.connect();
InputStream input = huc.getInputStream();
import org.jsoup.nodes.Document;
Document doc = null;
try {
doc = Jsoup.connect("http://www.myurl.com/sample.xml").get();
} catch (Exception e) {
//log error
}
And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url
To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:
image = (ImageView) findViewById(R.id.imageViewCompass);
image.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shortclick();
}
});
image.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
longclick();
return true;
}
});
//Then the functions that are called:
public void shortclick()
{
Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();
}
public void longclick()
{
Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();
}
It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.
Notice the cool thing in S.Lott's comment - you can also call functions with *mylist
and **mydict
to unpack positional and keyword arguments:
def foo(a, b, c, d):
print a, b, c, d
l = [0, 1]
d = {"d":3, "c":2}
foo(*l, **d)
Will print: 0 1 2 3
Assuming that it's a TCP (rather than UDP) port that you're trying to use:
On the server itself, use netstat -an
to check to see which ports are listening.
From outside, just use telnet host port
(or telnet host:port
on Unix systems) to see if the connection is refused, accepted, or timeouts.
On that latter test, then in general:
On Windows 7 or Windows Vista the default option 'telnet' is not recognized as an internal or external command, operable program or batch file. To solve this, just enable it: Click *Start** → Control Panel → Programs → Turn Windows Features on or off. In the list, scroll down and select Telnet Client and click OK.
You can easily launch Firefox from the command line with a proxy server using the -proxy-server option.
This works on Mac, Windows and Linux.
path_to_firefox/firefox.exe -proxy-server %proxy_URL%
Mac Example:
/Applications/Firefox.app/Contents/MacOS/firefox -proxy-server proxy.example.com
That is a curried function
First, examine this function with two parameters …
const add = (x, y) => x + y
add(2, 3) //=> 5
Here it is again in curried form …
const add = x => y => x + y
Here is the same1 code without arrow functions …
const add = function (x) {
return function (y) {
return x + y
}
}
Focus on return
It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.
const f = someParam => returnValue
So our add
function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add
const add = x => (y => x + y)
In other words add
of some number returns a function
add(2) // returns (y => 2 + y)
Calling curried functions
So in order to use our curried function, we have to call it a bit differently …
add(2)(3) // returns 5
This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. This is more evident if we separate the calls on two lines …
const add2 = add(2) // returns function(y) { return 2 + y }
add2(3) // returns 5
Applying our new understanding to your code
related: ”What’s the difference between binding, partial application, and currying?”
OK, now that we understand how that works, let's look at your code
handleChange = field => e => {
e.preventDefault()
/// Do something here
}
We'll start by representing it without using arrow functions …
handleChange = function(field) {
return function(e) {
e.preventDefault()
// Do something here
// return ...
};
};
However, because arrow functions lexically bind this
, it would actually look more like this …
handleChange = function(field) {
return function(e) {
e.preventDefault()
// Do something here
// return ...
}.bind(this)
}.bind(this)
Maybe now we can see what this is doing more clearly. The handleChange
function is creating a function for a specified field
. This is a handy React technique because you're required to setup your own listeners on each input in order to update your applications state. By using the handleChange
function, we can eliminate all the duplicated code that would result in setting up change
listeners for each field. Cool!
1 Here I did not have to lexically bind this
because the original add
function does not use any context, so it is not important to preserve it in this case.
Even more arrows
More than two arrow functions can be sequenced, if necessary -
const three = a => b => c =>
a + b + c
const four = a => b => c => d =>
a + b + c + d
three (1) (2) (3) // 6
four (1) (2) (3) (4) // 10
Curried functions are capable of surprising things. Below we see $
defined as a curried function with two parameters, yet at the call site, it appears as though we can supply any number of arguments. Currying is the abstraction of arity -
const $ = x => k =>_x000D_
$ (k (x))_x000D_
_x000D_
const add = x => y =>_x000D_
x + y_x000D_
_x000D_
const mult = x => y =>_x000D_
x * y_x000D_
_x000D_
$ (1) // 1_x000D_
(add (2)) // + 2 = 3_x000D_
(mult (6)) // * 6 = 18_x000D_
(console.log) // 18_x000D_
_x000D_
$ (7) // 7_x000D_
(add (1)) // + 1 = 8_x000D_
(mult (8)) // * 8 = 64_x000D_
(mult (2)) // * 2 = 128_x000D_
(mult (2)) // * 2 = 256_x000D_
(console.log) // 256
_x000D_
Partial application
Partial application is a related concept. It allows us to partially apply functions, similar to currying, except the function does not have to be defined in curried form -
const partial = (f, ...a) => (...b) =>
f (...a, ...b)
const add3 = (x, y, z) =>
x + y + z
partial (add3) (1, 2, 3) // 6
partial (add3, 1) (2, 3) // 6
partial (add3, 1, 2) (3) // 6
partial (add3, 1, 2, 3) () // 6
partial (add3, 1, 1, 1, 1) (1, 1, 1, 1, 1) // 3
Here's a working demo of partial
you can play with in your own browser -
const partial = (f, ...a) => (...b) =>_x000D_
f (...a, ...b)_x000D_
_x000D_
const preventDefault = (f, event) =>_x000D_
( event .preventDefault ()_x000D_
, f (event)_x000D_
)_x000D_
_x000D_
const logKeypress = event =>_x000D_
console .log (event.which)_x000D_
_x000D_
document_x000D_
.querySelector ('input[name=foo]')_x000D_
.addEventListener ('keydown', partial (preventDefault, logKeypress))
_x000D_
<input name="foo" placeholder="type here to see ascii codes" size="50">
_x000D_
You should separate the host from the port number. You could have something, like:
development:
adapter: mysql2
encoding: utf8
database: my_db_name
username: root
password: my_password
host: 127.0.0.1
port: 3306
Expressed explicitly ...
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CertCheck);
private static bool CertCheck(object sender, X509Certificate cert,
X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
Given a first selector: SelectorA, you can find the next match of SelectorB as below:
Example with mouseover to change border-with:
$("SelectorA").on("mouseover", function() {
var i = $(this).find("SelectorB")[0];
$(i).css({"border" : "1px"});
});
}
General use example to change border-with:
var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});
view.isVisible = true
view.isInvisible = true
view.isGone = true
// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone
If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:
// Example
view.hide()
fun View?.show() {
if (this == null) return
if (!isVisible) isVisible = true
}
fun View?.hide() {
if (this == null) return
if (!isInvisible) isInvisible = true
}
fun View?.gone() {
if (this == null) return
if (!isGone) isGone = true
}
To make conditional visibility simple, also add these:
fun View?.show(visible: Boolean) {
if (visible) show() else gone()
}
fun View?.hide(hide: Boolean) {
if (hide) hide() else show()
}
fun View?.gone(gone: Boolean = true) {
if (gone) gone() else show()
}
You can do this using the WITH clause of the SELECT statement:
;
WITH my_select As (SELECT ... FROM ...)
SELECT * FROM foo
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)
That's the ANSI/ISO SQL Syntax. I know that SQL Server, Oracle and DB2 support it. Not sure about the others...
You can do this program in this way. The range is in between 0 to 99,999
def num_to_word(num):
word_num = { "0": "zero", "00": "", "1" : "One" , "2" : "Two", "3" : "Three", "4" : "Four", "5" : "Five","6" : "Six", "7": "Seven", "8" : "eight", "9" : "Nine","01" : "One" , "02" : "Two", "03" : "Three", "04" : "Four", "05" : "Five","06" : "Six", "07": "Seven", "08" : "eight", "09" : "Nine", "10" : "Ten", "11": "Eleven", "12" :"Twelve", "13" : "Thirteen", "14" : "Fourteen", "15" : "Fifteen", "17":"Seventeen", "18" :"Eighteen", "19": "Nineteen", "20" : "Twenty", "30" : "Thirty", "40" : "Forty", "50" : "Fifty", "60" : "Sixty", "70": "seventy", "80" : "eighty", "90" : "ninety"}
keys = []
for k in word_num.keys():
keys.append(k)
if len(num) == 1:
return(word_num[num[0]])
elif len(num) == 2:
c = 0
for k in keys:
if k == num[0] + num[1]:
c += 1
if c == 1:
return(word_num[num[0] + num[1]])
else:
return(word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]])
elif len(num) == 3:
c = 0
for k in keys:
if k == num[1] + num[2]:
c += 1
if c == 1:
return(word_num[num[0]]+ " Hundred " + word_num[num[1] + num[2]])
else:
return(word_num[num[0]]+ " Hundred " + word_num[str(int(num[1]) * 10)] + " " + word_num[num[2]])
elif len(num) == 4:
c = 0
for k in keys:
if k == num[2] + num[3]:
c += 1
if c == 1:
if num[1] == '0' :
return(word_num[num[0]]+ " Thousand " + word_num[num[2] + num[3]])
else:
return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[num[2] + num[3]])
else:
if num[1] == '0' :
return(word_num[num[0]]+ " Thousand " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
else:
return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
elif len(num) == 5:
c = 0
d = 0
for k in keys:
if k == num[3] + num[4]:
c += 1
for k in keys:
if k == num[0] + num[1]:
d += 1
if d == 1:
val = word_num[num[0] + num[1]]
else:
val = word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]]
if c == 1:
if num[1] == '0' :
return(val + " Thousand " + word_num[num[3] + num[4]])
else:
return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[num[3] + num[4]])
else:
if num[1] == '0' :
return(val + " Thousand " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])
else:
return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])
num = [str(d) for d in input("Enter number: ")]
print(num_to_word(num).upper())
For Git
Create a new feature
via Terminal/Shell:
git checkout origin/feature/<featurename>
git merge --squash origin/feature/<featurename>
This doesnt commit it, allows you to review it first.
Then commit, and finish feature from this new branch, and delete/ignore the old one (the one you did dev on).
You can use JQuery, select the item by id:
$("input#Password").attr("autocomplete","off");
Or select the item by type:
$("input[type='password']").attr("autocomplete","off");
Or also:
You can use pure Javascript:
document.getElementById('Password').autocomplete = 'off';
I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:
script.js
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
var myString = 'newData='+JSON.stringify(yourObject); //converts json to string and prepends the POST variable name
$.ajax({
type: "POST",
url: "buildJson.php", //the name and location of your php file
data: myString, //add the converted json string to a document.
success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false; //prevents the page from reloading. this helps if you want to bind this whole process to a click event.
buildJson.php
<?php
$file = "data.json"; //name and location of json file. if the file doesn't exist, it will be created with this name
$fh = fopen($file, 'a'); //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.
$new_data = $_POST["newData"]; //put POST data from ajax request in a variable
fwrite($fh, $new_data); //write the data with fwrite
fclose($fh); //close the dile
?>
New in Django 1.7 is a app registry that stores configuration and provides introspection. This machinery let's you change several app attributes.
The main point I want to make is that renaming an app isn't always necessary: With app configuration it is possible to resolve conflicting apps. But also the way to go if your app needs friendly naming.
As an example I want to name my polls app 'Feedback from users'. It goes like this:
Create a apps.py
file in the polls
directory:
from django.apps import AppConfig
class PollsConfig(AppConfig):
name = 'polls'
verbose_name = "Feedback from users"
Add the default app config to your polls/__init__.py
:
default_app_config = 'polls.apps.PollsConfig'
For more app configuration: https://docs.djangoproject.com/en/1.7/ref/applications/
I solved in this way: I logged in with root username
mysql -u root -p -h localhost
I created a new user with
CREATE USER 'francesco'@'localhost' IDENTIFIED BY 'some_pass';
then I created the database
CREATE DATABASE shop;
I granted privileges for new user for this database
GRANT ALL PRIVILEGES ON shop.* TO 'francesco'@'localhost';
Then I logged out root and logged in new user
quit;
mysql -u francesco -p -h localhost
I rebuilt my database using a script
source shop.sql;
And that's it.. Now from php works without problems with the call
$conn = new mysqli("localhost", "francesco", "some_pass", "shop");
Thanks to all for your time :)
Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/
This will add 10 pixels to the left of the paragraph element
p {
margin-left: 10px;
}
or if you just want some padding within your paragraph element
p {
padding-left: 10px;
}
Basically, this will not work out
Format("20130423014854","yyyy-MM-dd hh:mm:ss")
the format
function will only work if your string has correct format
Format (#17/04/2004#, "yyyy/mm/dd")
And you need to specify, what datatype of field [Date]
is, because I can't put this value 2013-04-23 13:48:54.0
under a General Date field (I use MS access2007
).
You might want to view this topic:
select date in between
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.
git push origin
will push all changes on the local branches that have matching remote branches at origin
As for git push
Works like
git push <remote>
, where<remote>
is the current branch's remote (or origin, if no remote is configured for the current branch).
From the Examples section of the git-push
man page
Use this Way in this circle image is also working + you have preloader also for network image:
new ClipRRect(
borderRadius: new BorderRadius.circular(30.0),
child: FadeInImage.assetNetwork(
placeholder:'asset/loader.gif',
image: 'Your Image Path',
),
)
In .Net Core use User.Identity.Name
to get the Name claim of the user.
This problem also occurs if you have a private Rule in you class:
@Rule
private TemporaryFolder folderRule;
Make it public.
Calling SubString()
allocates a new string. For optimal performance, you should avoid that extra allocation. Starting with C# 7.2
you can take advantage of the Span pattern.
When targeting .NET Framework
, include the System.Memory NuGet
package. For .NET Core
projects this works out of the box.
static void Main(string[] args)
{
var str = "hello world!";
var span = str.AsSpan(10); // No allocation!
// Outputs: d!
foreach (var c in span)
{
Console.Write(c);
}
Console.WriteLine();
}
You can use the function file_get_contents();
if(file_get_contents('https://example.com/example.txt')) {
//File exists
}
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
In your particular example you'd do the following routerLink
:
[routerLink]="['user', user.id, 'details']"
To do so in a controller, you can inject Router
and use:
router.navigate(['user', user.id, 'details']);
More info in the Angular docs Link Parameters Array section of Routing & Navigation
public class Test{
Test2 test = new Test2();
JFrame frame = new JFrame();
Test(){
...
frame.setLayout(new BorderLayout());
frame.add(test, BorderLayout.CENTER);
...
}
//main
...
}
//public class Test2{
public class Test2 extends JPanel {
//JPanel test2 = new JPanel();
Test2(){
...
}
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
div
has an ID.class
"collapse", this will hide your block by
default. If you want your div to be collapsible AND be shown by
default you need to add "in" class to the collapse. Otherwise the
toggle behavior will not work properly.data-toggle="collapse"
to instruct
Bootstrap to add an appropriate toggle script to this tag.Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
This div (Bar) is shown by default and can toggle
</div>
Group your report data based on the category that you want your sheets to be based on. Specify that you want that grouping to start a new page for every new category. Each page becomes a new worksheet in the Excel workbook.
Note: I use SQL Server 2003 and Excel 2003.
Just wanted to leave a simple working solution here that does not require user interaction.
As I stated in a post I made:
Basically all you need to do is load your page on top.location, create the session and redirect it back to facebook.
Add this code in the top of your index.php
and set $page_url
to your application final tab/app URL and you’ll see your application will work without any problem.
<?php
// START SAFARI SESSION FIX
session_start();
$page_url = "http://www.facebook.com/pages/.../...?sk=app_...";
if (isset($_GET["start_session"]))
die(header("Location:" . $page_url));
if (!isset($_GET["sid"]))
die(header("Location:?sid=" . session_id()));
$sid = session_id();
if (empty($sid) || $_GET["sid"] != $sid):
?>
<script>
top.window.location="?start_session=true";
</script>
<?php
endif;
// END SAFARI SESSION FIX
?>
Note: This was made for facebook, but it would actually work within any other similar situations.
The above code does not maintain the requests post data, and you would loose the signed_request, if your application relies on signed request feel free to try the following code:
Note: This is still being tested properly and may be less stable than the first version. Use at your own risk / Feedback is appreciated.
(Thanks to CBroe for pointing me into the right direction here allowing to improve the solution)
// Start Session Fix
session_start();
$page_url = "http://www.facebook.com/pages/.../...?sk=app_...";
if (isset($_GET["start_session"]))
die(header("Location:" . $page_url));
$sid = session_id();
if (!isset($_GET["sid"]))
{
if(isset($_POST["signed_request"]))
$_SESSION["signed_request"] = $_POST["signed_request"];
die(header("Location:?sid=" . $sid));
}
if (empty($sid) || $_GET["sid"] != $sid)
die('<script>top.window.location="?start_session=true";</script>');
// End Session Fix
Additionally, if it's a folder to be removed and it's subsequent child folders or files, use:
git rm -r foldername
To decode:
byte[] image = Base64.getDecoder().decode(base64string);
To encode:
String text = Base64.getEncoder().encodeToString(imageData);
just remove them
"ext-intl" : "*"
from your composer.json file.
Because sometimes for some helper functions, the IDE complains that the extension is missing from the composer.json file. Immediately press Alt+Enter to add it to the composer. But that doesn't mean that composer will count them in. The composer will complain next time while doing some operations. So that, we should not blindly type Alt+Enter rather than installing them manually in composer by doing composer install <package-name>
.
As I think you have entered it manually, you should remove it, then install it in proper procedure composer install <package-name>
Or else you can run composer update
to count that added dependencies in.
This worked for me:
command prompt or gitbash into the node_modules folder in your project then execute:
npm uninstall *
Removed all of the local packages for that project.
To create not optional data I recommend using it:
let key = "1234567"
let keyData = Data(key.utf8)
just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
In $CUDA_HOME/include/host_config.h
, find lines like these (may slightly vary between different CUDA version):
//...
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 9)
#error -- unsupported GNU version! gcc versions later than 4.9 are not supported!
#endif [> __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 9) <]
//...
Remove or change them matching your condition.
Note this method is potentially unsafe and may break your build. For example, gcc 5 uses C++11 as default, however this is not the case for nvcc as of CUDA 7.5. A workaround is to add
--Xcompiler="--std=c++98"
for CUDA<=6.5
or
--std=c++11
for CUDA>=7.0.
This is how I solved this in ImpressPages:
//initial request with login data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name'); //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
//another request preserving the session
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
Or you can style it with pixels.
.big-checkbox {width: 30px; height: 30px;}
Be wary of "slurping" files. That's when you read the entire file into memory at once.
The problem is that it doesn't scale well. You could be developing code with a reasonably sized file, then put it into production and suddenly find you're trying to read files measuring in gigabytes, and your host is freezing up as it tries to read and allocate memory.
Line-by-line I/O is very fast, and almost always as effective as slurping. It's surprisingly fast actually.
I like to use:
IO.foreach("testfile") {|x| print "GOT ", x }
or
File.foreach('testfile') {|x| print "GOT", x }
File inherits from IO, and foreach
is in IO, so you can use either.
I have some benchmarks showing the impact of trying to read big files via read
vs. line-by-line I/O at "Why is "slurping" a file not a good practice?".
Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.
In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
//your operations on file
} else {
String name = item.getFieldName();
String value = item.getString();
//you operations on paramters
}
}
In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
The <f:viewParam>
manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>
, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{bean.id}
value, or if the value
attribute is absent, then set it as request attribtue on name id
so that it's available by #{id}
in the view.So when you open the page as foo.xhtml?id=10
then the parameter value 10
get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true"
and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
You can use the <f:viewAction>
for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction>
is however new since JSF 2.2 (the <f:viewParam>
already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event>
instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event>
this way is in essence a workaround/hack, that's exactly why the <f:viewAction>
was introduced in JSF 2.2.
You can "pass-through" the view parameters in navigation links by setting includeViewParams
attribute to true
or by adding includeViewParams=true
request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata>
example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml
has also a <f:viewParam>
on the very same parameter, otherwise it won't be passed through.
The <f:viewParam>
can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this @RequestScoped
bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message>
is for the <f:viewParam>
, not the plain HTML <input type="text">
! Also note that the input value displays #{param.query}
when #{bean.query}
is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
The only working method for me:
function removeItem (array, value) {
var i = 0;
while (i < array.length) {
if(array[i] === value) {
array.splice(i, 1);
} else {
++i;
}
}
return array;
}
Usage:
var new = removeItem( ["apple","banana", "orange"], "apple");
// ---> ["banana", "orange"]
You can use resize like this:
For n = 1 To 5
Columns(n).Resize(, 5).Select
'~~> rest of your code
Next
In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.
Another example:
Dim myPath As String = """" & Path.Combine(part1, part2) & """"
Good luck!
I tried to convert ddmmyy format to date("Y-m-d"
format but was not working when I directly pass ddmmyy =date('dmy')
then realized it has to be in yyyy-mm-dd format so. used substring to organize
$strParam = '20'.substr($_GET['date'], 4, 2).'-'.substr($_GET['date'], 2, 2).'-'.substr($_GET['date'], 0, 2);
then passed to date("Y-m-d",strtotime($strParam));
it worked!
This works. Tested.
.popover {
top: 71px !important;
left: 379px !important;
}
I noticed previous comments uses google adsense as object to test. Some pages don't uses adsense, and using adsense block as test is not really a good idea. Because adsense block may harm your SEO. Here is example how I detect by adblocker simple blocked class:
Html:
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>
Jquery:
$(document).ready(function()
{
if(!$("#ablockercheck").is(":visible"))
{
$("#ablockermsg").text("Please disable adblocker.").show();
}
});
"ablockercheck" is an ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.
This is a very obscure fault that WCF services throw. The issue is that WCF is unable to verify the security of the message that was passed to the service.
This is almost always because of a server time skew. The remote server and the client's system time must be within (typically) 10 minutes of each other. If they are not, security validation will fail.
I'd call eloqua.com and find out what their server time is, and compare that to your server time.
I am not sure if this is pythonic, but seems to work
def alternate_list(a):
return a[::2], a[1::2]
key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))
Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery
You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/
All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter
<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">
and run js function
app_handle_listing_horisontal_scroll($('#table-listing'))
cat filename.sql | mysql -u username -p # type mysql password when asked for it
Where filename.sql holds all the sql to create your database. Or...
echo "create database `database-name`" | mysql -u username -p
If you really only want to create a database.
This is a very c# type of code:
var bks: Book[] = new Book[2];
In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:
var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;
Now to explain what new Book[2];
would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:
Book[2] = function (){alert("hey");}
var foo = new Book[2]
and you should see hey. Try it
OnClientClick seems to be very picky when used with OnClick.
I tried unsuccessfully with the following use cases:
OnClientClick="return ValidateSearch();"
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"
But they did not work. The following worked:
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1"
OnClick="keywordSearch_Click"
OnClientClick="if (!ValidateSearch()) { return false;};" />
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend
You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.
Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000, 'localhost');
server.on('listening', function() {
console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});
This works just fine in nodejs v0.6+ and Express v3.0+.
on jupyter notebook using
np_load_old = np.load
# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)
worked fine, but the problem appears when you use this method in spyder(you have to restart the kernel every time or you will get an error like:
TypeError : () got multiple values for keyword argument 'allow_pickle'
I solved this issue using the solution here:
I suggest doing it in two steps:
# set fixed value to 'c2' where the condition is met
df.loc[df['c1'] == 'Value', 'c2'] = 10
# copy value from 'c3' to 'c2' where the condition is NOT met
df.loc[df['c1'] != 'Value', 'c2'] = df[df['c1'] != 'Value', 'c3']
You can also perform Implicit Type Conversions with template literals. Example:
let fruits = ["mango","orange","pineapple","papaya"];
console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya
You are getting the same random number each time, because you are setting a seed inside the loop. Even though you're using time()
, it only changes once per second, so if your loop completes in a second (which it likely will), you'll get the same seed value each time, and the same initial random number.
Move the srand()
call outside the loop (and call it only once, at the start of your app) and you should get random "random" numbers.
A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.
The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.
This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.
In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris
As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually
It sounds trivial, but my issue was that I wasn't in the right project. Make sure you are in the project you expect to be in; otherwise, you won't be able to pull down the correct branches.
if we update <select>
constantly and we need to save previous value :
var newOptions = {
'Option 1':'value-1',
'Option 2':'value-2'
};
var $el = $('#select');
var prevValue = $el.val();
$el.empty();
$.each(newOptions, function(key, value) {
$el.append($('<option></option>').attr('value', value).text(key));
if (value === prevValue){
$el.val(value);
}
});
$el.trigger('change');
WITH UPD AS (UPDATE TEST_TABLE SET SOME_DATA = 'Joe' WHERE ID = 2
RETURNING ID),
INS AS (SELECT '2', 'Joe' WHERE NOT EXISTS (SELECT * FROM UPD))
INSERT INTO TEST_TABLE(ID, SOME_DATA) SELECT * FROM INS
Tested on Postgresql 9.3
You can use @JsonFormat
annotation with shape
as STRING
on your BigDecimal
variables. Refer below:
import com.fasterxml.jackson.annotation.JsonFormat;
class YourObjectClass {
@JsonFormat(shape=JsonFormat.Shape.STRING)
private BigDecimal yourVariable;
}
if you are using angularjs & aspnet/mvc, to retrieve json files, you have to allow mime type at web config
<staticContent>
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
If you're using GNU find
, you can try -execdir
parameter, e.g.:
find . -type d -execdir realpath "{}" ';'
or (as per @gniourf_gniourf comment):
find . -type d -execdir sh -c 'printf "%s/%s\n" "$PWD" "$0"' {} \;
Note: You can use ${0#./}
instead of $0
to fix ./
in the front.
or more practical example:
find . -name .git -type d -execdir git pull -v ';'
If you want to include the current directory, it's even simpler by using -exec
:
find . -type d -exec sh -c 'cd -P -- "{}" && pwd -P' \;
or using xargs
:
find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'
Or similar example suggested by @gniourf_gniourf:
find . -type d -print0 | while IFS= read -r -d '' file; do
# ...
done
The above examples support directories with spaces in their name.
Or by assigning into bash array:
dirs=($(find . -type d))
for dir in "${dirs[@]}"; do
cd "$dir"
echo $PWD
done
Change .
to your specific folder name. If you don't need to run recursively, you can use: dirs=(*)
instead. The above example doesn't support directories with spaces in the name.
So as @gniourf_gniourf suggested, the only proper way to put the output of find in an array without using an explicit loop will be available in Bash 4.4 with:
mapfile -t -d '' dirs < <(find . -type d -print0)
Or not a recommended way (which involves parsing of ls
):
ls -d */ | awk '{print $NF}' | xargs -n1 sh -c 'cd $0 && pwd && echo Do stuff'
The above example would ignore the current dir (as requested by OP), but it'll break on names with the spaces.
See also:
Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()
The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.
So:
Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket();
? This is called casting
If you're looking for the absolute path relative to the server root, I've found that this works well:
$_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['SCRIPT_NAME'])
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
You have a syntax error on line 5:
$('#logo').hide();.fadeIn(3000);
Should be:
$('#logo').hide().fadeIn(3000);
I know of few packages that support "make uninstall" but many more that support make install DESTDIR=xxx" for staged installs.
You can use this to create a package which you install instead of installing directly from the source. I had no luck with checkinstall but fpm works very well.
This can also help you remove a package previously installed using make install. You simply force install your built package over the make installed one and then uninstall it.
For example, I used this recently to deal with protobuf-3.3.0. On RHEL7:
make install DESTDIR=dest
cd dest
fpm -f -s dir -t rpm -n protobuf -v 3.3.0 \
--vendor "You Not RedHat" \
--license "Google?" \
--description "protocol buffers" \
--rpm-dist el7 \
-m [email protected] \
--url "http:/somewhere/where/you/get/the/package/oritssource" \
--rpm-autoreqprov \
usr
sudo rpm -i -f protobuf-3.3.0-1.el7.x86_64.rpm
sudo rpm -e protobuf-3.3.0
Prefer yum to rpm if you can.
On Debian9:
make install DESTDIR=dest
cd dest
fpm -f -s dir -t deb -n protobuf -v 3.3.0 \
-C `pwd` \
--prefix / \
--vendor "You Not Debian" \
--license "$(grep Copyright ../../LICENSE)" \
--description "$(cat README.adoc)" \
--deb-upstream-changelog ../../CHANGES.txt \
--url "http:/somewhere/where/you/get/the/package/oritssource" \
usr/local/bin \
usr/local/lib \
usr/local/include
sudo apt install -f *.deb
sudo apt-get remove protobuf
Prefer apt to dpkg where you can.
I've also posted answer this here
If you know you will want a 'c' key, but do not know the value, insert 'c' with a dummy value when you create the dict.
d1 = OrderedDict([('c', None), ('a', '1'), ('b', '2')])
and change the value later.
d1['c'] = 3
Compared to the other parser libraries lxml
is extremely fast:
And with cssselect
it’s quite easy to use for scraping HTML pages too:
from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
print '%s: %s' % (div.text_content(), div.get('href'))
I Think This will be helpful
+ (NSString *)toBase64String:(NSString *)string {
NSData *data = [string dataUsingEncoding: NSUnicodeStringEncoding];
NSString *ret = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
return ret;
}
+ (NSString *)fromBase64String:(NSString *)string {
NSData *aData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData *aDataDecoded = [[NSData alloc]initWithBase64EncodedString:string options:0];
NSString *decryptedStr = [[NSString alloc]initWithData:aDataDecoded encoding:NSUTF8StringEncoding];
return [decryptedStr autorelease];
}
you can use this
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/YOUR_DB_NAME";
static final String USER = "root";
static final String PASS = "YOUR_ROOT_PASSWORD";
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
you have to give the right root password .
The scoping is correct as you've noted. However, you are not calling the inner
function anywhere.
You can do either:
function outer() {
// when you define it this way, the inner function will be accessible only from
// inside the outer function
function inner() {
alert("hi");
}
inner(); // call it
}
Or
function outer() {
this.inner = function() {
alert("hi");
}
}
<input type="button" onclick="(new outer()).inner();" value="ACTION">?
javax.xml.bind.DatatypeConverter
should do it:
byte [] b = javax.xml.bind.DatatypeConverter.parseHexBinary("E62DB");
String s = javax.xml.bind.DatatypeConverter.printHexBinary(b);
You mean Selenium WebDriver? Huh....
Prerequisite: Install Python based on your OS
Install with following command
pip install -U selenium
And use this module in your code
from selenium import webdriver
You can also use many of the following as required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
I would recommend you to run script without IDE... Here is my approach
An example below shows login page automation
#ScriptName : Login.py
#---------------------
from selenium import webdriver
#Following are optional required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
baseurl = "http://www.mywebsite.com/login.php"
username = "admin"
password = "admin"
xpaths = { 'usernameTxtBox' : "//input[@name='username']",
'passwordTxtBox' : "//input[@name='password']",
'submitButton' : "//input[@name='login']"
}
mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.maximize_window()
#Clear Username TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()
#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)
#Clear Password TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()
#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()
There is an another way that you can find xpath of any object -
Run script -
python Login.py
You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn't an ID attribute on the elements you're interacting with).
Firepath can also capture the object's locator as a CSS selector if you move your cursor to the object. You'll have to update your code to use the equivalent find by CSS selector method instead -
find_element_by_css_selector(css_selector)
A BLOB is a Binary Large OBject. It is used to store large quantities of binary data in a database.
You can use it to store any kind of binary data that you want, includes images, video, or any other kind of binary data that you wish to store.
Different DBMSes treat BLOBs in different ways; you should read the documentation of the databases you are interested in to see how (and if) they handle BLOBs.
There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject]
or [JsonProperty]
.
There are predefined naming strategies like CamelCaseNamingStrategy
, but you can implement your own ones.
The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization
Try the following code:
SELECT *
FROM users
WHERE firstname IN ('joe','jane');
The API of java.io.File
only supports getting the last modified time. And the Internet is very quiet on this topic as well.
Unless I missed something significant, the Java library as is (up to but not yet including Java 7) does not include this capability. So if you were desperate for this, one solution would be to write some C(++) code to call system routines and call it using JNI. Most of this work seems to be already done for you in a library called JNA, though.
You may still need to do a little OS specific coding in Java for this, though, as you'll probably not find the same system calls available in Windows and Unix/Linux/BSD/OS X.
And in swift we can do
UIApplication.sharedApplication().sendAction("resignFirstResponder", to: nil, from: nil, forEvent: nil)
Ctrl+shift+L opens the Quick text search window
The answer by @hybrid is quite informative, except it doesn't explain the purpose as mentioned by @ashitaka "What if you use the Mobile First approach? So, we have the mobile CSS first and then use min-width to target larger sites. We shouldn't use the only keyword in that context, right? "
Want to add in here that the purpose is simply to prevent non supporting browsers to use that Other device style as if it starts from "screen" without it will take it for a screen whereas if it starts from "only" style will be ignored.
Answering to ashitaka consider this example
<link rel="stylesheet" type="text/css"
href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css"
href="desktop.css" media="screen and (min-width: 481px)" />
If we don't use "only" it will still work as desktop-style will also be used striking android styles but with unnecessary overhead. In this case, IF a browser is non-supporting it will fallback to the second Style-sheet ignoring the first.
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.
You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.
There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.
That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.
This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)
I'm sure you know that a std::vector<X>
stores a whole bunch of X
objects, right? But if you have a std::map<X, Y>
, what it actually stores is a whole bunch of std::pair<const X, Y>
s. That's exactly what a map is - it pairs together the keys and the associated values.
When you iterate over a std::map
, you're iterating over all of these std::pair
s. When you dereference one of these iterators, you get a std::pair
containing the key and its associated value.
std::map<std::string, int> m = /* fill it */;
auto it = m.begin();
Here, if you now do *it
, you will get the the std::pair
for the first element in the map.
Now the type std::pair
gives you access to its elements through two members: first
and second
. So if you have a std::pair<X, Y>
called p
, p.first
is an X
object and p.second
is a Y
object.
So now you know that dereferencing a std::map
iterator gives you a std::pair
, you can then access its elements with first
and second
. For example, (*it).first
will give you the key and (*it).second
will give you the value. These are equivalent to it->first
and it->second
.
you shoud use <a href="javascript:void(0)" ></a>
instead of <a href="#" ></a>
Check for secure_path on sudo
[root@host ~]# sudo -V | grep 'Value to override'
Value to override user's $PATH with: /sbin:/bin:/usr/sbin:/usr/bin
If $PATH
is being overridden use visudo
and edit /etc/sudoers
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
There are CSS options for the audio tag.
Like: html 5 audio tag width
But if you play around with it you'll see results can be unexpected - as of August 2012.
I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:
"Cannot install at this time".
Finally Zillan's link helped me to get apple documentation. So, check:
ax.init.itunes.apple.com
is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load). As soon as I changed the proxy it installed completely. Hope it will help someone.
But here's the rub, sometimes you can't or don't want to wait. For example I want to use the new support for RubyMotion which includes RubyMotion project structure support, setup of rake files, setup of configurations that are hooked to iOS Simulator etc.
RubyMine has all of these now, IDEA does not. So I would have to generate a RubyMotion project outside of IDEA, then setup an IDEA project and hook up to that source folder etc and God knows what else.
What JetBrains should do is have a licensing model that would allow me, with the purchase of IDEA to use any of other IDEs, as opposed to just relying on IDEAs plugins.
I would be willing to pay more for that i.e. say 50 bucks more for said flexibility.
The funny thing is, I was originally a RubyMine customer that upgraded to IDEA, because I did want that polyglot setup. Now I'm contemplating paying for the upgrade of RubyMine, just because I need to do RubyMotion now. Also there are other potential areas where this out of sync issue might bite me again . For example torque box workflow / deployment support.
JetBrains has good IDEs but I guess I'm a bit annoyed.
IMPORTANT NOTE: You have to sort your data first.
The part I didn't get is that in the example construction
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
k
is the current grouping key, and g
is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the groupby
iterator itself returns iterators.
Here's an example of that, using clearer variable names:
from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print("A %s is a %s." % (thing[1], key))
print("")
This will give you the output:
A bear is a animal.
A duck is a animal.A cactus is a plant.
A speed boat is a vehicle.
A school bus is a vehicle.
In this example, things
is a list of tuples where the first item in each tuple is the group the second item belongs to.
The groupby()
function takes two arguments: (1) the data to group and (2) the function to group it with.
Here, lambda x: x[0]
tells groupby()
to use the first item in each tuple as the grouping key.
In the above for
statement, groupby
returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.
Here's a slightly different example with the same data, using a list comprehension:
for key, group in groupby(things, lambda x: x[0]):
listOfThings = " and ".join([thing[1] for thing in group])
print(key + "s: " + listOfThings + ".")
This will give you the output:
animals: bear and duck.
plants: cactus.
vehicles: speed boat and school bus.
I use AquaFold at work on Windows, but it's based on Java and supports Mac OS X.
Any Activity that restarts has its onResume() method executed first.
To use this method, do this:
@Override
public void onResume(){
super.onResume();
// put your code here...
}
You can copy the HTML code to the clipboard and paste special it back as Unicode text. Excel will render the HTML in the cell. Check out this post http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii/
The relevant macro code from the post:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim objData As DataObject
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
If LCase(Left(Target.Text, 6)) = "<html>" Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
sSelAdd = Selection.Address
Target.Select
Me.PasteSpecial "Unicode Text"
Me.Range(sSelAdd).Select
End If
End If
Application.EnableEvents = True
End Sub
I ended up using (note the '.log' filename and the single quotes around 'myfilename_'):
<rollingStyle value="Date" />
<datePattern value="'myfilename_'yyyy-MM-dd"/>
<preserveLogFileNameExtension value="true" />
<staticLogFileName value="false" />
<file type="log4net.Util.PatternString" value="c:\\Logs\\.log" />
This gives me:
myfilename_2015-09-22.log
myfilename_2015-09-23.log
.
.
Use this css
.close-image {
cursor: pointer;
z-index: 3;
right: 5px;
top: 5px;
position: absolute;
}
If you want to open specific activity of another application we can use this.
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
startActivity(intent)
}catch(ActivityNotFoundException e){
Toast.makeText(context,"Activity Not Found",Toast.LENGTH_SHORT).show()
}
If you must need other application, instead of showing Toast you can show a dialog. Using dialog you can bring the user to Play-Store to download required application.
You can find out the Android version looking at Build.VERSION
.
The documentation recommends you check Build.VERSION.SDK_INT
against the values in Build.VERSION_CODES
.
This is fine as long as you realise that Build.VERSION.SDK_INT
was only introduced in API Level 4, which is to say Android 1.6 (Donut). So this won't affect you, but if you did want your app to run on Android 1.5 or earlier then you would have to use the deprecated Build.VERSION.SDK
instead.
Please use the sample at tutorialspoint.com. The whole implementation only needs a few lines of code without changing your xml file. Hope this helps.
STEP 1: Import library
import android.app.ProgressDialog;
STEP 2: Declare ProgressDialog global variable
ProgressDialog loading = null;
STEP 3: Start new ProgressDialog and use the following properties (please be informed that this sample only covers the basic circle loading bar without the real time progress status).
loading = new ProgressDialog(v.getContext());
loading.setCancelable(true);
loading.setMessage(Constant.Message.AuthenticatingUser);
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
STEP 4: If you are using AsyncTasks, you can start showing the dialog in onPreExecute method. Otherwise, just place the code in the beginning of your button onClick event.
loading.show();
STEP 5: If you are using AsyncTasks, you can close the progress dialog by placing the code in onPostExecute method. Otherwise, just place the code before closing your button onClick event.
loading.dismiss();
Tested it with my Nexus 5 android v4.0.3. Good luck!
I got the same error once, I created a template for a default toolbar( toolbar.xml) and then in another view I created a collapsable toolbar.
I required to add the collapsable toolbar to a view that show some information of the user(like whatsapp), but the method findViewById was referencing the default toolbar(id toolbar), not the collapsable one( id toolbar as well) yes, I wrote the same id to both toolbar, so when I tried to access the activity the app crashed showing me the error.
I fixed the error by changing the id of the collapsable toolbar to id:col_toolbar and the error gone away and my app worked perfectly
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
This code works for me perfectly
<LinearLayout
android:id="@+id/choosePhotosView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:clickable="true"
android:background="@drawable/transparent_button_bg_rev_selector">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/choose_photo"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:text="@string/choose_photos_tv"/>
</LinearLayout>
An easy way to get this is:
function getPathFromUrl(url) {
return url.split("?")[0];
}
For those who also wish to remove the hash (not part of the original question) when no querystring exists, that requires a little bit more:
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
EDIT
@caub (originally @crl) suggested a simpler combo that works for both query string and hash (though it uses RegExp, in case anyone has a problem with that):
function getPathFromUrl(url) {
return url.split(/[?#]/)[0];
}
Please follow below link to use bootstrap with React. https://react-bootstrap.github.io/
For installation :
$ npm install --save react react-dom
$ npm install --save react-bootstrap
------------------------------------OR-------------------------------------
Put Bootstrap CDN for CSS in tag of index.html file in react and Bootstrap CDN for Js in tag of index.html file. Use className instead of class follow below index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="../src/images/dropbox_logo.svg">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="root"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</body>
</html>
See http://msdn.microsoft.com/en-us/library/ms187928.aspx
You can concatenate it:
SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
More information would be useful.
But the simplest form:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main()
{
std::ifstream data("plop.csv");
std::string line;
while(std::getline(data,line))
{
std::stringstream lineStream(line);
std::string cell;
while(std::getline(lineStream,cell,','))
{
// You have a cell!!!!
}
}
}
Also see this question: CSV parser in C++
=== Common Saying (from months to years old) ===
If you just for common use, here is the code as your information:
DateTime today = DateTime.Today;
DateTime bday = DateTime.Parse("2016-2-14");
int age = today.Year - bday.Year;
var unit = "";
if (bday > today.AddYears(-age))
{
age--;
}
if (age == 0) // Under one year old
{
age = today.Month - bday.Month;
age = age <= 0 ? (12 + age) : age; // The next year before birthday
age = today.Day - bday.Day >= 0 ? age : --age; // Before the birthday.day
unit = "month";
}
else {
unit = "year";
}
if (age > 1)
{
unit = unit + "s";
}
The test result as below:
The birthday: 2016-2-14
2016-2-15 => age=0, unit=month;
2016-5-13 => age=2, unit=months;
2016-5-14 => age=3, unit=months;
2016-6-13 => age=3, unit=months;
2016-6-15 => age=4, unit=months;
2017-1-13 => age=10, unit=months;
2017-1-14 => age=11, unit=months;
2017-2-13 => age=11, unit=months;
2017-2-14 => age=1, unit=year;
2017-2-15 => age=1, unit=year;
2017-3-13 => age=1, unit=year;
2018-1-13 => age=1, unit=year;
2018-1-14 => age=1, unit=year;
2018-2-13 => age=1, unit=year;
2018-2-14 => age=2, unit=years;
_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_
Another way:
$c = 'A';
$chars = array($c);
while ($c < 'Z') $chars[] = ++$c;
After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.
Take a look:
QuadFlask Color Picker
the order of registering routes is important . register 404
routes after static files.
correct order:
app.use("/admin", admin);
...
app.use(express.static(join(__dirname, "public")));
app.use((req, res) => {
res.status(404);
res.send("404");
});
otherwise everything which is not in routes , like css files etc.. , will become 404 .
You can use virtualenv --clear
. which won't install any packages, then install the ones you want.
I was using View.INVISIBLE
and View.VISIBLE
and the ProgressBar
would slowly flash instead of constantly being visible, switched to View.GONE
and View.VISIBLE
and it works perfectly
There are a lot of answers here but I couldn't find the semantic distinction mentioned on any.
It's not about the thread itself; both methods are required as they support very different use-cases.
sleep()
sends the Thread to sleep as it was before, it just packs the context and stops executing for a predefined time. So in order to wake it up before the due time, you need to know the Thread reference. This is not a common situation in a multi-threaded environment. It's mostly used for time-synchronization (e.g. wake in exactly 3.5 seconds) and/or hard-coded fairness (just sleep for a while and let others threads work).
wait()
, on the contrary, is a thread (or message) synchronization mechanism that allows you to notify a Thread of which you have no stored reference (nor care). You can think of it as a publish-subscribe pattern (wait
== subscribe and notify()
== publish). Basically using notify() you are sending a message (that might even not be received at all and normally you don't care).
To sum up, you normally use sleep()
for time-syncronization and wait()
for multi-thread-synchronization.
They could be implemented in the same manner in the underlying OS, or not at all (as previous versions of Java had no real multithreading; probably some small VMs doesn't do that either). Don't forget Java runs on a VM, so your code will be transformed in something different according to the VM/OS/HW it runs on.
Multiple normal white space characters (space, tabulator and line break) are treated as one single white space character:
For all HTML elements except
PRE
, sequences of white space separate "words" (we use the term "word" here to mean "sequences of non-white space characters"). When formatting text, user agents should identify these words and lay them out according to the conventions of the particular written language (script) and target medium.
So
foo bar
is displayed as
foo bar
But no-break space is always displayed. So
foo&?nbsp;&?nbsp;&?nbsp;bar
is displayed as
foo bar
I resolved that situation in this way. I created a util method that return a object extracted from request body, using the readValue method of ObjectMapper that is capable of receiving a Reader.
public static <T> T getBody(ResourceRequest request, Class<T> class) {
T objectFromBody = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(request);
objectFromBody = objectMapper.readValue(httpServletRequest.getReader(), class);
} catch (IOException ex) {
log.error("Error message", ex);
}
return objectFromBody;
}
Solution for me was to use:
from flask_sqlalchemy import SQLAlchemy
instead of
from flask.ext.sqlalchemy import SQLAlchemy
I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.
For getting the buffer size in c/c++ program the following is the flow
int n;
unsigned int m = sizeof(n);
int fdsocket;
fdsocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // example
getsockopt(fdsocket,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m);
// now the variable n will have the socket size
If you can get i["MyPhone"]
as a long
, you can use the long.ToString()
method to format it:
Convert.ToLong(i["MyPhone"]).ToString("###-###-####");
See the MSDN page on Numeric Format Strings.
Be careful to use long rather than int: int could overflow.
sftp supports batch files.
From the man page:
-b batchfile
Batch mode reads a series of commands from an input batchfile instead of stdin.
Since it lacks user interaction it should be used in conjunction with non-interactive
authentication. A batchfile of `-' may be used to indicate standard input. sftp
will abort if any of the following commands fail: get, put, rename, ln, rm, mkdir,
chdir, ls, lchdir, chmod, chown, chgrp, lpwd, df, symlink, and lmkdir. Termination
on error can be suppressed on a command by command basis by prefixing the command
with a `-' character (for example, -rm /tmp/blah*).
You could use table
, i.e.
n_occur <- data.frame(table(vocabulary$id))
gives you a data frame with a list of id
s and the number of times they occurred.
n_occur[n_occur$Freq > 1,]
tells you which id
s occurred more than once.
vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]
returns the records with more than one occurrence.
Just for the sake of completeness, I invite you to think about it like this:
<p>
is a paragraph, an <li>
is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote>
whether the content was a quote or not.<div>
and <span>
, because otherwise, people would go back to abusing the elements which do have meanings.When I had similar problem gem update --system
helped me. Run this before bundle install
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.
The ANSI escape sequences you're looking for are the Select Graphic Rendition subset. All of these have the form
\033[XXXm
where XXX
is a series of semicolon-separated parameters.
To say, make text red, bold, and underlined (we'll discuss many other options below) in C you might write:
printf("\033[31;1;4mHello\033[0m");
In C++ you'd use
std::cout<<"\033[31;1;4mHello\033[0m";
In Python3 you'd use
print("\033[31;1;4mHello\033[0m")
and in Bash you'd use
echo -e "\033[31;1;4mHello\033[0m"
where the first part makes the text red (31
), bold (1
), underlined (4
) and the last part clears all this (0
).
As described in the table below, there are a large number of text properties you can set, such as boldness, font, underlining, &c. (Isn't it silly that StackOverflow doesn't allow you to put proper tables in answers?)
Code | Effect | Note |
---|---|---|
0 | Reset / Normal | all attributes off |
1 | Bold or increased intensity | |
2 | Faint (decreased intensity) | Not widely supported. |
3 | Italic | Not widely supported. Sometimes treated as inverse. |
4 | Underline | |
5 | Slow Blink | less than 150 per minute |
6 | Rapid Blink | MS-DOS ANSI.SYS; 150+ per minute; not widely supported |
7 | [[reverse video]] | swap foreground and background colors |
8 | Conceal | Not widely supported. |
9 | Crossed-out | Characters legible, but marked for deletion. Not widely supported. |
10 | Primary(default) font | |
11–19 | Alternate font | Select alternate font n-10 |
20 | Fraktur | hardly ever supported |
21 | Bold off or Double Underline | Bold off not widely supported; double underline hardly ever supported. |
22 | Normal color or intensity | Neither bold nor faint |
23 | Not italic, not Fraktur | |
24 | Underline off | Not singly or doubly underlined |
25 | Blink off | |
27 | Inverse off | |
28 | Reveal | conceal off |
29 | Not crossed out | |
30–37 | Set foreground color | See color table below |
38 | Set foreground color | Next arguments are 5;<n> or 2;<r>;<g>;<b> , see below |
39 | Default foreground color | implementation defined (according to standard) |
40–47 | Set background color | See color table below |
48 | Set background color | Next arguments are 5;<n> or 2;<r>;<g>;<b> , see below |
49 | Default background color | implementation defined (according to standard) |
51 | Framed | |
52 | Encircled | |
53 | Overlined | |
54 | Not framed or encircled | |
55 | Not overlined | |
60 | ideogram underline | hardly ever supported |
61 | ideogram double underline | hardly ever supported |
62 | ideogram overline | hardly ever supported |
63 | ideogram double overline | hardly ever supported |
64 | ideogram stress marking | hardly ever supported |
65 | ideogram attributes off | reset the effects of all of 60-64 |
90–97 | Set bright foreground color | aixterm (not in standard) |
100–107 | Set bright background color | aixterm (not in standard) |
You've got this already!
The standards implementing terminal colours began with limited (4-bit) options. The table below lists the RGB values of the background and foreground colours used for these by a variety of terminal emulators:
Using the above, you can make red text on a green background (but why?) using:
\033[31;42m
In their book "Basic Color Terms: Their Universality and Evolution", Brent Berlin and Paul Kay used data collected from twenty different languages from a range of language families to identify eleven possible basic color categories: white, black, red, green, yellow, blue, brown, purple, pink, orange, and gray.
Berlin and Kay found that, in languages with fewer than the maximum eleven color categories, the colors followed a specific evolutionary pattern. This pattern is as follows:
This may be why story Beowulf only contains the colours black, white, and red. It may also be why the Bible does not contain the colour blue. Homer's Odyssey contains black almost 200 times and white about 100 times. Red appears 15 times, while yellow and green appear only 10 times. (More information here)
Differences between languages are also interesting: note the profusion of distinct colour words used by English vs. Chinese. However, digging deeper into these languages shows that each uses colour in distinct ways. (More information)
Generally speaking, the naming, use, and grouping of colours in human languages is fascinating. Now, back to the show.
Technology advanced, and tables of 256 pre-selected colours became available, as shown below.
Using these above, you can make pink text like so:
\033[38;5;206m #That is, \033[38;5;<FG COLOR>m
And make an early-morning blue background using
\033[48;5;57m #That is, \033[48;5;<BG COLOR>m
And, of course, you can combine these:
\033[38;5;206;48;5;57m
The 8-bit colours are arranged like so:
0x00-0x07: standard colors (same as the 4-bit colours)
0x08-0x0F: high intensity colors
0x10-0xE7: 6 × 6 × 6 cube (216 colors): 16 + 36 × r + 6 × g + b (0 = r, g, b = 5)
0xE8-0xFF: grayscale from black to white in 24 steps
Now we are living in the future, and the full RGB spectrum is available using:
\033[38;2;<r>;<g>;<b>m #Select RGB foreground color
\033[48;2;<r>;<g>;<b>m #Select RGB background color
So you can put pinkish text on a brownish background using
\033[38;2;255;82;197;48;2;155;106;0mHello
Support for "true color" terminals is listed here.
Much of the above is drawn from the Wikipedia page "ANSI escape code".
Since I'm often in the position of trying to remember what colours are what, I have a handy script called: ~/bin/ansi_colours
:
#!/usr/bin/python
print "\\033[XXm"
for i in range(30,37+1):
print "\033[%dm%d\t\t\033[%dm%d" % (i,i,i+60,i+60);
print "\033[39m\\033[39m - Reset colour"
print "\\033[2K - Clear Line"
print "\\033[<L>;<C>H OR \\033[<L>;<C>f puts the cursor at line L and column C."
print "\\033[<N>A Move the cursor up N lines"
print "\\033[<N>B Move the cursor down N lines"
print "\\033[<N>C Move the cursor forward N columns"
print "\\033[<N>D Move the cursor backward N columns"
print "\\033[2J Clear the screen, move to (0,0)"
print "\\033[K Erase to end of line"
print "\\033[s Save cursor position"
print "\\033[u Restore cursor position"
print " "
print "\\033[4m Underline on"
print "\\033[24m Underline off"
print "\\033[1m Bold on"
print "\\033[21m Bold off"
This prints
Because of this, I'm creating a new object of CaseInsensitiveString for every event. So, it might hit performance.
Creating wrappers or converting key to lower case before lookup both create new objects. Writing your own java.util.Map implementation is the only way to avoid this. It's not too hard, and IMO is worth it. I found the following hash function to work pretty well, up to few hundred keys.
static int ciHashCode(String string)
{
// length and the low 5 bits of hashCode() are case insensitive
return (string.hashCode() & 0x1f)*33 + string.length();
}
According to HTTP terms, The PUT
request is just-like a database update statement.
PUT
- is used for modifying existing resource (Previously POSTED). On the other hand the PATCH
request is used to update some portion of existing resource.
For Example:
Customer Details:
// This is just a example.
firstName = "James";
lastName = "Anderson";
email = "[email protected]";
phoneNumber = "+92 1234567890";
//..
When we want to update to entire record ? we have to use Http
PUT
verb
for that.
such as:
// Customer Details Updated.
firstName = "James++++";
lastName = "Anderson++++";
email = "[email protected]";
phoneNumber = "+92 0987654321";
//..
On the other hand if we want to update only the portion of the record not the entire record then go for Http
PATCH
verb
.
such as:
// Only Customer firstName and lastName is Updated.
firstName = "Updated FirstName";
lastName = "Updated LastName";
//..
PUT VS POST:
When using PUT
request we have to send all parameter such as firstName, lastName, email, phoneNumber Where as In patch
request only send the parameters which one we want to update and it won't effecting or changing other data.
For more details please visit : https://fullstack-developer.academy/restful-api-design-post-vs-put-vs-patch/
Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.
Use this Format as per your requirements:
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
"arrayOneName" : [
{
"Id" : 1,
"Employee" : "EmpOne",
"Deptartment" : "HR"
},
{
"Id" : 2,
"Employee" : "EmpTwo",
"Deptartment" : "IT"
},
{
"Id" : 3,
"Employee" : "EmpThree",
"Deptartment" : "Sales"
}
],
"arrayTwoName": [
{
"Product": "3",
"Price": "6790"
}
],
"arrayThreeName" : [
"name1", "name2", "name3", "name4" // For Strings
],
"arrayFourName" : [
1, 2, 3, 4 // For Numbers
]
}
Remember to use this in POST with proper endpoint. Also, RAW selected and JSON(application/json) in Body Tab.
Like THIS:
Update 1:
I don't think multiple @RequestBody is allowed or possible.
@RequestBody parameter must have the entire body of the request and bind that to only one object.
You have to use something like Wrapper Object for this to work.
You will have to look through the various locations depending on your version of MySQL.
mysqld --help -verbose | grep my.cnf
For Homebrew:
/usr/local/Cellar/mysql/8.0.11/bin/mysqld (mysqld 8.0.11)
Default possible locations:
/etc/my.cnf
/etc/mysql/my.cnf
~/.my.cnf
Found mine here:
/usr/local/etc/my.cnf
var val =$("#inputname").val();
$("#inputname").removeAttr('value').attr('value', val).focus();
// I think this is beter for all browsers...
When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.
# mysqladmin -u root -p status
Output:
Enter password:
Uptime: 4 Threads: 1 Questions: 62 Slow queries: 0 Opens: 51 Flush tables: 1 Open tables: 45 Queries per second avg: 15.500
It means MySQL serer is running
If server is not running then it will dump error as follows
# mysqladmin -u root -p status
Output :
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
So Under Debian Linux you can type following command
# /etc/init.d/mysql status
There are several issues with pretty much all the answers here:
1] Hard-coded sql. Will brackets work on all database engines?
2] Entity framework Remove
and RemoveRange
calls. This loads all entities into memory affected by the operation. Yikes.
3] Truncate table. Breaks with foreign key references and may not work accross all database engines.
Use https://entityframework-plus.net/, they handle the cross database platform stuff, translate the delete into the correct sql statement and don't load entities into memory, and the library is free and open source.
Disclaimer: I am not affiliated with the nuget package. They do offer a paid version that does even more stuff.
With boost you can use any_of_equal
:
#include <boost/algorithm/cxx11/any_of.hpp>
bool item_present = boost::algorithm::any_of_equal(vector, element);
At the time this question was asked nobody thought about Bitcoin price. In the case of BTC, it is probably insufficient to use DECIMAL(15,2)
. If the Bitcoin will rise to $100,000 or more, we will need at least DECIMAL(18,9)
to support cryptocurrencies in our apps.
DECIMAL(18,9)
takes 12 bytes of space in MySQL (4 bytes per 9 digits).
$("#myid li").click(function() {
alert(this.id); // id of clicked li by directly accessing DOMElement property
alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
alert($(this).html()); // gets innerHTML of clicked li
alert($(this).text()); // gets text contents of clicked li
});
If you are talking about replacing the ID with something:
$("#myid li").click(function() {
this.id = 'newId';
// longer method using .attr()
$(this).attr('id', 'newId');
});
Demo here. And to be fair, you should have first tried reading the documentation: