This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;
ArrayList<String> recordings = new ArrayList<String>();
this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.
<ListView
android:clipToPadding="false"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:dividerHeight="10dp"
android:divider="@null"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
and set paddingTop
, paddingBottom
and dividerHeight
to the same value to get equal spacing between all elements and space at the top and bottom of the list.
I set clipToPadding
to false
to let the views be drawn in this padded area.
I set divider
to @null
to remove the lines between list elements.
to convert a TimestampTZ in oracle, you do
TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR')
at time zone 'region'
see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264
and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141
eg:
SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);
A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00
SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);
A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00
SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);
A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES
The following function would recursively iterate through all the directories in the \home\ubuntu
directory( whole directory structure under ubuntu ) and apply the necessary checks in else
block.
function check {
for file in $1/*
do
if [ -d "$file" ]
then
check $file
else
##check for the file
if [ $(head -c 4 "$file") = "%PDF" ]; then
rm -r $file
fi
fi
done
}
domain=/home/ubuntu
check $domain
In visual studio code if your front is too small or too big, then you just need to zoom out or zoom in. To do that you just have to do:
I can recommend make pre-init of future index value, this is very usefull in a lot of case like multi work, some export e.t.c.
just create additional User_Seq
table:
with two fields: id Uniq index
and SeqVal nvarchar(1)
and create next SP, and generated ID value from this SP and put to new User row!
CREATE procedure [dbo].[User_NextValue]
as
begin
set NOCOUNT ON
declare @existingId int = (select isnull(max(UserId)+1, 0) from dbo.User)
insert into User_Seq (SeqVal) values ('a')
declare @NewSeqValue int = scope_identity()
if @existingId > @NewSeqValue
begin
set identity_insert User_Seq on
insert into User_Seq (SeqID) values (@existingId)
set @NewSeqValue = scope_identity()
end
delete from User_Seq WITH (READPAST)
return @NewSeqValue
end
The only time I've ever used this in practice is with numpy/pandas
. For example, with the .isin()
dataframe method.
In the docs they show this basic example
>>> df.isin([0, 2])
num_legs num_wings
falcon True True
dog False True
But what if instead you wanted all the rows not in [0, 2]?
>>> ~df.isin([0, 2])
num_legs num_wings
falcon False False
dog True False
public ActionResult Index()
{
return View();
}
public ActionResult Test(string Name)
{
return RedirectToAction("Index");
}
Return View
Directly displays your view
but
Redirect ToAction
Action is performed
Similar to C# casting to (int)
with just using standard lib:
Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1
This should work:
$imageClear.on('click', function() {
$imageFile.val('');
});
I personally like the solution using the parser
module, which is the second Answer to this question and is beautiful, as you don't have to construct any string literals to get it working. BUT, one downside is that it is 90% slower than the accepted answer with strptime
.
from dateutil import parser
from datetime import datetime
import timeit
def dt():
dt = parser.parse("Jun 1 2005 1:33PM")
def strptime():
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
print(timeit.timeit(stmt=dt, number=10**5))
print(timeit.timeit(stmt=strptime, number=10**5))
>10.70296801342902
>1.3627995655316933
As long as you are not doing this a million times over and over again, I still think the parser
method is more convenient and will handle most of the time formats automatically.
Using the inline-block is better because it doesn't force the remaining elements and/or controls to be drawn in a new line.
label {
width:200px;
display: inline-block;
}
From Emacswiki, GNU Emacs 23 has a built-in key combination:
C-xC-+ and C-xC-- to increase or decrease the buffer text size
you can use pandas.set_option(), for column, you can specify any of these options
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_colwidth", 200)
For full print column, you can use like this
import pandas as pd
pd.set_option('display.max_colwidth', -1)
print(words.head())
the answers on this page eluded me until i found the show package details option
async handleResponse(){
const result = await this.axiosTest();
}
async axiosTest () {
return await axios.get(url)
.then(function (response) {
console.log(response.data);
return response.data;})
.catch(function (error) {
console.log(error);
});
}
You can find check https://flaviocopes.com/axios/#post-requests url and find some relevant information in the GET section of this post.
That's what i am currrently working, what a coincidence.
You also need to add the following lines into your LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
return redirect()->route('dashboard');
}
return redirect('/home');
}
/**
* Where to redirect users after login.
*
* @var string
*/
//protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
You declare the variable as extern
in a common header:
//globals.h
extern int x;
And define it in an implementation file.
//globals.cpp
int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace
.
if just using internet then use-
<uses-permission android:name="android.permission.INTERNET" />
if you are getting the state of internet then use also -
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
just above the application tag.
You can add the files which give error to .eslintignore file in your project.Like for all the .vue files just add /*.vue
It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as C#'s iterator blocks if you're familiar with those.
The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values - as if the generator method was paused. Now obviously you can't really "pause" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.
This can be done using:
plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)
For SwiftUI, try
TextField ("Email", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle()).padding()
SecureField ("Password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle()).padding()
Plug in your network cable into a switch which has no other connection/cables. That should work imho.
Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):
peregrino:$ java -Xmx4096M -cp bin WheelPrimes
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.
peregrino:$ java -Xmx4095M -cp bin WheelPrimes
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified
peregrino:$ java -Xmx4092M -cp bin WheelPrimes
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size
peregrino:$ java -Xmx4000M -cp bin WheelPrimes
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
(experiment reducing from 4000M until)
peregrino:$ java -Xmx2686M -cp bin WheelPrimes
(normal execution)
Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.
copy all meta values to a cache-object:
/* <meta name="video" content="some-video"> */
const meta = Array.from(document.querySelectorAll('meta[name]')).reduce((acc, meta) => (
Object.assign(acc, { [meta.name]: meta.content })), {});
console.log(meta.video);
There's a native and less intrusive alternative, which works only for your call.
URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
Notice how most of these can only be used WITHOUT a DOCTYPE. I'm looking for the same answer, but I have a DOCTYPE. There is one way to do it with a DOCTYPE however, although it doesn't apply to the style of my site, but it will work on the type of page you want to create:
div#full-size{
position: absolute;
top:0;
bottom:0;
right:0;
left:0;
overflow:hidden;
Now, this was mentioned earlier but I just wanted to clarify that this is normally used with a DOCTYPE, height:100%; only works without a DOCTYPE
Control characters:
(Hex codes assume an ASCII-compatible character encoding.)
\a
= \x07
= alert (bell)\b
= \x08
= backspace\t
= \x09
= horizonal tab\n
= \x0A
= newline (or line feed)\v
= \x0B
= vertical tab\f
= \x0C
= form feed\r
= \x0D
= carriage return\e
= \x1B
= escape (non-standard GCC extension)Punctuation characters:
\"
= quotation mark (backslash not required for '"'
)\'
= apostrophe (backslash not required for "'"
)\?
= question mark (used to avoid trigraphs)\\
= backslashNumeric character references:
\
+ up to 3 octal digits\x
+ any number of hex digits\u
+ 4 hex digits (Unicode BMP, new in C++11)\U
+ 8 hex digits (Unicode astral planes, new in C++11)\0
= \00
= \000
= octal ecape for null character
If you do want an actual digit character after a \0
, then yes, I recommend string concatenation. Note that the whitespace between the parts of the literal is optional, so you can write "\0""0"
.
Depending on what you want to do runnning it via a Proxy is not ideal. A transparent proxy might work ok as long as the packets do not get tampered with.
I am about to reverse the GPS data that gets transferred from the iPhone to the iPad on iOS 4.3.x to get to the the vanilla data the best way to get a clean Network Dump is to use "tcpdump" and/or "pirni" as already suggested.
In this particular case where we want the Tethered data it needs to be as transparent as possible. Obviously you need your phone to be JailBroken for this to work.
This is probably unlikely, but given that your observed behaviour is unusual it needs to be checked and no-one else has mentioned it.
Are you absolutely sure that all objects are owned by dbo and you don't have a rogue copies owned by yourself or a different user present as well?
Just occasionally when I've seen odd behaviour it's because there was actually two copies of an object and which one you get depends on what is specified and who you are logged on as. For example it is perfectly possible to have two copies of a view or procedure with the same name but owned by different owners - a situation that can arise where you are not logged onto the database as a dbo and forget to specify dbo as object owner when you create the object.
In note that in the text you are running some things without specifying owner, eg
sp_recompile ViewOpener
if for example there where two copies of viewOpener present owned by dbo and [some other user] then which one you actually recompile if you don't specify is dependent upon circumstances. Ditto with the Report_Opener view - if there where two copies (and they could differ in specification or execution plan) then what is used depends upon circumstances - and as you do not specify owner it is perfectly possible that your adhoc query might use one and the compiled procedure might use use the other.
As I say, it's probably unlikely but it is possible and should be checked because your issues could be that you're simply looking for the bug in the wrong place.
Open the registry and search for key LoginMode
under:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
Update the LoginMode value as 2.
You can do it using write() :
#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()
The general Angular way to get access to an element that triggered an event is to write a directive and bind() to the desired event:
app.directive('myChange', function() {
return function(scope, element) {
element.bind('change', function() {
alert('change on ' + element);
});
};
});
or with DDO (as per @tpartee's comment below):
app.directive('myChange', function() {
return {
link: function link(scope, element) {
element.bind('change', function() {
alert('change on ' + element);
});
}
}
});
The above directive can be used as follows:
<input id="searchText" ng-model="searchText" type="text" my-change>
Type into the text field, then leave/blur. The change callback function will fire. Inside that callback function, you have access to element
.
Some built-in directives support passing an $event object. E.g., ng-*click, ng-Mouse*. Note that ng-change does not support this event.
Although you can get the element via the $event object:
<button ng-click="clickit($event)">Hello</button>
$scope.clickit = function(e) {
var elem = angular.element(e.srcElement);
...
this goes "deep against the Angular way" -- Misko.
I think the given answers miss the point of the original question, which is how much space needs to be allocated to fit the base64 encoding for a given binary string of length n bytes.
The answer is (floor(n / 3) + 1) * 4 + 1
This includes padding and a terminating null character. You may not need the floor call if you are doing integer arithmetic.
Including padding, a base64 string requires four bytes for every three-byte chunk of the original string, including any partial chunks. One or two bytes extra at the end of the string will still get converted to four bytes in the base64 string when padding is added. Unless you have a very specific use, it is best to add the padding, usually an equals character. I added an extra byte for a null character in C, because ASCII strings without this are a little dangerous and you'd need to carry the string length separately.
You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.
Use sql
from sql
:
spool output of this to a file:
select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';
spoolfile will have something like this:
alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;
Simple, standard library only. Gives timezone-aware datetime, unlike datetime.utcnow()
.
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
Yet another solution to selection highlight problems with first, and last items in the list:
Add padding to the top and bottom of your list background equal to or greater than the radius. This ensures the selection highlighting doesn't overlap with your corner curves.
This is the easiest solution when you need non-transparent selection highlighting.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/listbg" />
<stroke
android:width="2dip"
android:color="#D5D5D5" />
<corners android:radius="10dip" />
<!-- Make sure bottom and top padding match corner radius -->
<padding
android:bottom="10dip"
android:left="2dip"
android:right="2dip"
android:top="10dip" />
</shape>
(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.
You can do this via the following CSS rule as an example:
text-decoration-color:green
If this rule isn't supported by an older browser, you can use the following solution:
Setting your word with a border-bottom:
a:link {
color: red;
text-decoration: none;
border-bottom: 1px solid blue;
}
a:hover {
border-bottom-color: green;
}
Some browsers such as Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively. Take a look at this Stackoverflow question. It's using btoa()
and atob()
functions.
For server-side JavaScript (Node), you can use Buffer
s to decode.
If you are going for a cross-browser solution, there are existing libraries like CryptoJS or code like:
http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
With the latter, you need to thoroughly test the function for cross browser compatibility. And error has already been reported.
Try:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal to NULL
(as NULL is the absence of a value). NULL
is also never not equal to NULL
. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL
.
You can run the following:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
And this returns:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
For completeness, in SQL Server you can:
SET ANSI_NULLS OFF;
Which would result in your equals comparisons working differently:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
Which returns:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
I know its too late but this solution is working perfect for both .net framework and .net core:
@System.Web.HttpUtility.JavaScriptStringEncode()
I would suggest an enum
, as you would use in Java, e.g.
enum SharedTPScopeManager: TPScopeManager {
case Singleton
}
Thanks everyone who helped. After doing some research myself (I'm the guy who asked the question), here is what I found to make sense most:
Database column type: the timezone-agnostic number of milliseconds since 1970 represented as decimal(20)
because 2^64 has 20 digits and disk space is cheap; let's be straightforward. Also, I will use neither DEFAULT CURRENT_TIMESTAMP
, nor triggers. I want no magic in the DB.
Java field type: long
. The Unix timestamp is well supported across various libs, long
has no Y2038 problems, timestamp arithmetic is fast and easy (mainly operator <
and operator +
, assuming no days/months/years are involved in the calculations). And, most importantly, both primitive long
s and java.lang.Long
s are immutable—effectively passed by value—unlike java.util.Date
s; I'd be really pissed off to find something like foo.getLastUpdate().setTime(System.currentTimeMillis())
when debugging somebody else's code.
The ORM framework should be responsible for filling in the data automatically.
I haven't tested this yet, but only looking at the docs I assume that @Temporal
will do the job; not sure about whether I might use @Version
for this purpose. @PrePersist
and @PreUpdate
are good alternatives to control that manually. Adding that to the layer supertype (common base class) for all entities, is a cute idea provided that you really want timestamping for all of your entities.
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
here's a way using the SSSE3 instruction pshufb using its Intel intrinsic, assuming you have a multiple of 4 int
s:
unsigned int *bswap(unsigned int *destination, unsigned int *source, int length) {
int i;
__m128i mask = _mm_set_epi8(12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3);
for (i = 0; i < length; i += 4) {
_mm_storeu_si128((__m128i *)&destination[i],
_mm_shuffle_epi8(_mm_loadu_si128((__m128i *)&source[i]), mask));
}
return destination;
}
Yes, should try reinstall mysql, but use the --reinstall
flag to force a package reconfiguration. So the operating system service configuration is not skipped:
sudo apt --reinstall install mysql-server
You could reference controls inside the master page this way:
void Page_Load()
{
ContentPlaceHolder cph;
Literal lit;
cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if (cph != null) {
lit = (Literal) cph.FindControl("Literal1");
if (lit != null) {
lit.Text = "Some <b>HTML</b>";
}
}
}
In this example you have to put a Literal control in your ContentPlaceholder.
ES6 String Template
Here is a simple way if you don't need IE/EDGE support
$(`input[id=${x}]`).hide();
or
$(`input[id=${$(this).attr("name")}]`).hide();
This is a es6 feature called template string
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
var x = $(this).attr("name");_x000D_
$(`input[id=${x}]`).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
String Concatenation
If you need IE/EDGE support use
$("#" + $(this).attr("name")).hide();
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
$("#" + $(this).attr("name")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
Selector in DOM as data attribute
This is my preferred way as it makes you code really DRY
// HTML
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
//JS
$($(this).data("input-sel")).hide();
(function($) {_x000D_
$(".js-hide-onclick").click(function() {_x000D_
$($(this).data("input-sel")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />_x000D_
_x000D_
_x000D_
If you want to check if your -vm eclipse.ini
option worked correctly you can use this to see under what JVM the IDE itself runs: menu Help > About Eclipse > Installation Details > Configuration tab. Locate the line that says: java.runtime.version=...
.
An example with VBScript (.vbs)
Sub sety(wsh, action, typey, vary, value)
Dim wu
Set wu = wsh.Environment(typey)
wui = wu.Item(vary)
Select Case action
Case "ls"
WScript.Echo wui
Case "del"
On Error Resume Next
wu.remove(vary)
On Error Goto 0
Case "set"
wu.Item(vary) = value
Case "add"
If wui = "" Then
wu.Item(vary) = value
ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
wu.Item(vary) = value & ";" & wui
End If
Case Else
WScript.Echo "Bad action"
End Select
End Sub
Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
Case 3
value = ""
Case 4
value = args(3)
Case Else
WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
value = "```"
End Select
If Not value = "```" Then
' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
sety wsh, args(0), args(1), UCase(args(2)), value
End If
For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom. Eclipse Project: android-custom-tabs ; Original explanation: blog; Hope this helped.
element.is('.class1, .class2')
works, but it's 35% slower than
element.hasClass('class1') || element.hasClass('class2')
If you doubt what i say, you can verify on jsperf.com.
Hope this help someone.
It looks like a location problem because that code is perfectly fine for adding the icon.
Since I don't know your folder structure, I suggest adding a simple check:
File imageCheck = new File("water.bmp");
if(imageCheck.exists())
System.out.println("Image file found!")
else
System.out.println("Image file not found!");
This way if you ever get your path name wrong it will tell you instead of displaying nothing. Exception should be thrown if file would not exist, tho.
This is my powershell newbie way of doing this
if ((Test-Path ".\Desktop\checkfile.txt") -ne "True") {
Write-Host "Damn it"
} else {
Write-Host "Yay"
}
My ls sorts by name by default. What are you seeing?
man ls
states:
List information about the FILEs (the current directory by default). Sort entries alpha-betically if none of -cftuvSUX nor --sort is specified.
:
If I understand correctly you want then
of the request function to be called only if request is successful, and you want to ignore errors. To do that you can create a new promise resolve it when axios request is successful and never reject it in case of failure.
Updated code would look something like this:
export function request(method, uri, body, headers) {
let config = {
method: method.toLowerCase(),
url: uri,
baseURL: API_URL,
headers: { 'Authorization': 'Bearer ' + getToken() },
validateStatus: function (status) {
return status >= 200 && status < 400
}
}
return new Promise(function(resolve, reject) {
axios(config).then(
function (response) {
resolve(response.data)
}
).catch(
function (error) {
console.log('Show error notification!')
}
)
});
}
db.getCollection('orders').aggregate([
{$group: {
_id: {name: "$name"},
uniqueIds: {$addToSet: "$_id"},
count: {$sum: 1}
}
},
{$match: {
count: {"$gt": 1}
}
}
])
First Group Query the group according to the fields.
Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.
sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just
echo "c1, c2, ... " >> file
cat testfile.csv >> file
?
In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:
Select ChargeNum, CategoryId, Sum(Hours)
From (
Select ChargeNum, CategoryId, Hours
From KnownHours
Union
Select ChargeNum, 'Unknown' As CategoryId, Hours
From UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId
And here is the output:
ChargeNum CategoryId
---------- ---------- ----------------------
111111 1 40
111111 2 50
111111 Unknown 70
222222 1 40
222222 Unknown 25.5
As @jib said,
Promise.all
is all or nothing.
Though, you can control certain promises that are "allowed" to fail and we would like to proceed to .then
.
For example.
Promise.all([
doMustAsyncTask1,
doMustAsyncTask2,
doOptionalAsyncTask
.catch(err => {
if( /* err non-critical */) {
return
}
// if critical then fail
throw err
})
])
.then(([ mustRes1, mustRes2, optionalRes ]) => {
// proceed to work with results
})
In your theme's functions.php
:
function my_custom_js() {
echo '<script type="text/javascript" src="myscript.js"></script>';
}
// Add hook for admin <head></head>
add_action( 'admin_head', 'my_custom_js' );
// Add hook for front-end <head></head>
add_action( 'wp_head', 'my_custom_js' );
I'm keeping the following list updated for a couple of years now:
1.0.0.0/24
1.1.1.0/24
1.2.3.0/24
8.6.48.0/21
8.8.8.0/24
8.35.192.0/21
8.35.200.0/21
8.34.216.0/21
8.34.208.0/21
23.236.48.0/20
23.251.128.0/19
63.161.156.0/24
63.166.17.128/25
64.9.224.0/19
64.18.0.0/20
64.233.160.0/19
64.233.171.0/24
65.167.144.64/28
65.170.13.0/28
65.171.1.144/28
66.102.0.0/20
66.102.14.0/24
66.249.64.0/19
66.249.92.0/24
66.249.86.0/23
70.32.128.0/19
72.14.192.0/18
74.125.0.0/16
89.207.224.0/21
104.154.0.0/15
104.132.0.0/14
107.167.160.0/19
107.178.192.0/18
108.59.80.0/20
108.170.192.0/18
108.177.0.0/17
130.211.0.0/16
142.250.0.0/15
144.188.128.0/24
146.148.0.0/17
162.216.148.0/22
162.222.176.0/21
172.253.0.0/16
173.194.0.0/16
173.255.112.0/20
192.158.28.0/22
193.142.125.0/28
199.192.112.0/22
199.223.232.0/21
206.160.135.240/24
207.126.144.0/20
208.21.209.0/24
209.85.128.0/17
216.239.32.0/19
With Java 8 you can use stream
and collect
to copy the items:
Set<Item> newSet = oldSet.stream().collect(Collectors.toSet());
Or you can collect to an ImmutableSet
(if you know that the set should not change):
Set<Item> newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());
You can use this commands:
docker exec -it yournamecontainer psql -U postgres -c "CREATE DATABASE mydatabase ENCODING 'LATIN1' TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C';"
docker exec -it yournamecontainer psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO postgres;"
int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
you need to type it in cmd not in the IDLE. becuse IDLE is not an command prompt if you want to install something from IDLE type this
>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])
this is calling pip like pip <commands>
in terminal. The commands will be seperated by spaces that you are doing there to.
Given that what you want makes sense only when debugging, you could start SQLAlchemy with echo=True
, to log all SQL queries. For example:
engine = create_engine(
"mysql://scott:tiger@hostname/dbname",
encoding="latin1",
echo=True,
)
This can also be modified for just a single request:
echo=False
– ifTrue
, the Engine will log all statements as well as arepr()
of their parameter lists to the engines logger, which defaults tosys.stdout
. Theecho
attribute ofEngine
can be modified at any time to turn logging on and off. If set to the string"debug"
, result rows will be printed to the standard output as well. This flag ultimately controls a Python logger; see Configuring Logging for information on how to configure logging directly.Source: SQLAlchemy Engine Configuration
If used with Flask, you can simply set
app.config["SQLALCHEMY_ECHO"] = True
to get the same behaviour.
You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.
It should look like that :
#!/usr/bin/env python
or the real path
#!/usr/bin/python
You should also check the file have the right to be execute. chmod +x file.py
As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)
I had the same warning. It was a very old key. I regenerated a key on the current OpenSSH 7, and the error was gone.
If you're programming in OpenGL, use GLUT. The following page should help: http://www.lighthouse3d.com/opengl/glut/index.php?5
GLUT_KEY_LEFT Left function key
GLUT_KEY_RIGHT Right function key
GLUT_KEY_UP Up function key
GLUT_KEY_DOWN Down function key
void processSpecialKeys(int key, int x, int y) {
switch(key) {
case GLUT_KEY_F1 :
red = 1.0;
green = 0.0;
blue = 0.0; break;
case GLUT_KEY_F2 :
red = 0.0;
green = 1.0;
blue = 0.0; break;
case GLUT_KEY_F3 :
red = 0.0;
green = 0.0;
blue = 1.0; break;
}
}
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
Try creating a javascript function which runs this:
document.getElementById("youriframeid").contentWindow.location.reload(true);
Or maybe use an HTML workaround:
<html>
<body>
<center>
<a href="pagename.htm" target="middle">Refresh iframe</a>
<p>
<iframe src="pagename.htm" name="middle">
</p>
</center>
</body>
</html>
Both might be what you're looking for...
Repeat for Multiple aggregations like:
SELECT sum(AMOUNT) AS TOTAL_AMOUNT FROM (
SELECT AMOUNT FROM table_1
UNION ALL
SELECT AMOUNT FROM table_2
UNION ALL
SELECT ASSURED_SUM FROM table_3
)
I used tableViewCell to show multiple data, after swipe () right to left on a cell it will show two buttons Approve And reject, there are two methods, the first one is ApproveFunc which takes one argument, and the another one is RejectFunc which also takes one argument.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let Approve = UITableViewRowAction(style: .normal, title: "Approve") { action, index in
self.ApproveFunc(indexPath: indexPath)
}
Approve.backgroundColor = .green
let Reject = UITableViewRowAction(style: .normal, title: "Reject") { action, index in
self.rejectFunc(indexPath: indexPath)
}
Reject.backgroundColor = .red
return [Reject, Approve]
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func ApproveFunc(indexPath: IndexPath) {
print(indexPath.row)
}
func rejectFunc(indexPath: IndexPath) {
print(indexPath.row)
}
Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.
return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();
Where CustomerGroupingKey takes the group keys:
private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}
public string Country { get; }
public string Gender { get; }
}
Open android studio then go to help menu > check for update > Update your Android Studio to newer version.
A solution that works:
Wrap the part of the document that needs this modified behavior with the code provided below. In my case the portion to wrap is a \part{} and some text following it.
\makeatletter\@openrightfalse
\part{Whatever}
Some text
\chapter{Foo}
\@openrighttrue\makeatother
The wrapped portion should also include the chapter at the beginning of which this behavior needs to stop. Otherwise LaTeX may generate an empty page before this chapter.
Source: folks at the #latex IRC channel on irc.freenode.net
Nothing was working for me.
PHP_EOL
. "\r\n";
$NEWLINE_RE = '/(\r\n)|\r|\n/'; // take care of all possible newline-encodings in input file
$var = preg_replace($NEWLINE_RE,'', $var);
Works for me:
$admin_email_Body = $admin_mail_body .'<br>' ."\r\n";
$admin_email_Body .= 'This is line 2 <br>' ."\r\n";
$admin_email_Body .= 'This is line 3 <br>' ."\r\n";
Based on saikirans solution, I have written this, which helped me. On the .m file:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedRowIndex = nil;
}
else { self.selectedRowIndex = [indexPath retain]; }
[tableView beginUpdates];
[tableView endUpdates];
}
And on the header file:
@property (retain, nonatomic) NSIndexPath* selectedRowIndex;
I am not very experienced either, so double check for memory leaks etc.
You could set both left
and right
property to 0
. This will make the div stretch to the document width, but requires that no parent element is positioned (which is not the case, seeing as #header
is position: relative;
)
#site_nav_global_primary {
position: absolute;
top: 0;
left: 0;
right: 0;
}
Demo at: http://jsfiddle.net/xWnq2/, where I removed position:relative;
from #header
To provide another method for DatePeriod
when using the UTC or GMT timezone.
$start = new \DateTime('2006-04-12T12:30:00');
$end = new \DateTime('2006-04-14T11:30:00');
//determine what interval should be used - can change to weeks, months, etc
$interval = new \DateInterval('PT1H');
//create periods every hour between the two dates
$periods = new \DatePeriod($start, $interval, $end);
//count the number of objects within the periods
$hours = iterator_count($periods);
echo $hours . ' hours';
//difference between Unix Epoch
$diff = $end->getTimestamp() - $start->getTimestamp();
$hours = $diff / ( 60 * 60 );
echo $hours . ' hours (60 * 60)';
//difference between days
$diff = $end->diff($start);
$hours = $diff->h + ($diff->days * 24);
echo $hours . ' hours (days * 24)';
Result
47 hours (iterator_count)
47 hours (60 * 60)
47 hours (days * 24)
Please be advised that DatePeriod
excludes an hour for DST but does not add another hour when DST ends. So its usage is subjective to your desired outcome and date range.
See the current bug report
//set timezone to UTC to disregard daylight savings
date_default_timezone_set('America/New_York');
$interval = new \DateInterval('PT1H');
//DST starts Apr. 2nd 02:00 and moves to 03:00
$start = new \DateTime('2006-04-01T12:00:00');
$end = new \DateTime('2006-04-02T12:00:00');
$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';
//DST ends Oct. 29th 02:00 and moves to 01:00
$start = new \DateTime('2006-10-28T12:00:00');
$end = new \DateTime('2006-10-29T12:00:00');
$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';
Result
#2006-04-01 12:00 EST to 2006-04-02 12:00 EDT
23 hours (iterator_count)
//23 hours (60 * 60)
//24 hours (days * 24)
#2006-10-28 12:00 EDT to 2006-10-29 12:00 EST
24 hours (iterator_count)
//25 hours (60 * 60)
//24 hours (days * 24)
#2006-01-01 12:00 EST to 2007-01-01 12:00 EST
8759 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)
//------
#2006-04-01 12:00 UTC to 2006-04-02 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)
#2006-10-28 12:00 UTC to 2006-10-29 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)
#2006-01-01 12:00 UTC to 2007-01-01 12:00 UTC
8760 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)
If you want to do it in database:
Set the default value in database (sql server sample):
ALTER TABLE [TABLE_NAME] ADD CONSTRAINT [CONSTRAINT_NAME] DEFAULT (newid()) FOR [COLUMN_NAME]
Mapping hibernate file:
<hibernate-mapping ....
...
<property name="fieldName" column="columnName" type="Guid" access="field" not-null="false" insert="false" update="false" />
...
See, the key is insert="false" update="false"
If you use RecycleView, first you need more efford to setup. You need to give more time to setup simple Item onclick, border, touch event and other simple thing. But end product will be perfect.
So decision is yours. I suggest, if you design simple app like phonebook loading, where simple click of item is enough, you can implement listview. But if you design like social media home page with unlimited scrolling. Several different decoration between item, much control of individual item than use recycle view.
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
If you are in Navigation controller
let viewController = YourViewController(nibName: "YourViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)
I will recommend you for second approach using navigation controller.
Instead of
Image.open(picture.jpg)
Img.show
You should have
from PIL import Image
#...
img = Image.open('picture.jpg')
img.show()
You should probably also think about an other system to show your messages, because this way it will be a lot of manual work. Look into string substitution (using %s
or .format()
).
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -
private static final validPattern = "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
Pattern pattern = Pattern.compile(validPattern);
Matcher matcher = pattern.matcher(inputString);
System.out.print(matcher.find()); // should print true or false.
Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.
for centos 8 var/log/httpd/error_log
I had this issue with npm v1.1.4
(and node v0.6.12
), which are the Ubuntu 12.04
repository versions.
It looks like that version of npm
isn't supported any more, updating node (and npm with it) resolved the issue.
First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).
sudo apt-get purge nodejs npm
Then enable nodesource's repo and install:
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs
Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:
From: here
sudo apt-get update
OpenGL: sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev
Locate your Visual Studio folder for where it puts libraries and also header files, download and copy lib files to lib folder and header files to header. Then copy dll files to system32. Then your code will 100% run.
Also Windows: For all of those includes you just need to download glut32.lib
, glut.h
, glut32.dll
.
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
It appears that it's a bug in the Facebook app that was reported in April 2011 and has still yet to be fixed by the Android Facebook developers.
The only work around for the moment is to use their SDK.
For iOS 8 we can just use this [UIScreen mainScreen].nativeBounds
, like that:
- (NSInteger)resolutionX
{
return CGRectGetWidth([UIScreen mainScreen].nativeBounds);
}
- (NSInteger)resolutionY
{
return CGRectGetHeight([UIScreen mainScreen].nativeBounds);
}
I used this method:
$(document).mousemove(function(e) {
window.x = e.pageX;
window.y = e.pageY;
});
function show_popup(str) {
$("#popup_content").html(str);
$("#popup").fadeIn("fast");
$("#popup").css("top", y);
$("#popup").css("left", x);
}
In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.
The short answer is: don't. If you want code that reads linearly, use a library like seq. But just don't expect synchronous. You really can't. And that's a good thing.
There's little or nothing that can't be put in a callback. If they depend on common variables, create a closure to contain them. What's the actual task at hand?
You'd want to have a counter, and only call the callback when the data is there:
var waiting = 2;
request( {url: base + u_ext}, function( err, res, body ) {
var split1 = body.split("\n");
var split2 = split1[1].split(", ");
ucomp = split2[1];
if(--waiting == 0) callback();
});
request( {url: base + v_ext}, function( err, res, body ) {
var split1 = body.split("\n");
var split2 = split1[1].split(", ");
vcomp = split2[1];
if(--waiting == 0) callback();
});
function callback() {
// do math here.
}
Update 2018: node.js supports async/await keywords in recent editions, and with libraries that represent asynchronous processes as promises, you can await them. You get linear, sequential flow through your program, and other work can progress while you await. It's pretty well built and worth a try.
Try this easy and it works
let input = elem.querySelector('input[type="file"]');
input.outerHTML=input.outerHTML;
this will reset the input
(1) Is it possible to pass a JSON object to the url like in Ex.2?
No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
is not a valid URL.
If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif
, and defined your method like this:
@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
// code here
}
(2) How can we pass and parse the parameters in Ex.1?
Just add two request parameters, and give the correct path.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
// code here
}
UPDATE (from comment)
What if we have a complicated parameter structure ?
"A": [ { "B": 37181, "timestamp": 1160100436, "categories": [ { "categoryID": 2653, "timestamp": 1158555774 }, { "categoryID": 4453, "timestamp": 1158555774 } ] } ]
Send that as a POST
with the JSON data in the request body, not in the URL, and specify a content type of application/json
.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
// code here
}
Implemented in JavaScript (ES6):
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
Usage:
const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
function draw( x, y ){
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.beginPath();
ctx.strokeStyle = "orange";
ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
ctx.lineWidth = 3;
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "indigo";
ctx.arc( x, y, 6, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
let angle = 0; // In degrees
setInterval(function(){
const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
console.log( x, y );
draw( x, y );
document.querySelector("#degrees").innerHTML = angle + "°";
document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
There is a new configuration section that is used to reference namespaces for Razor views.
Open the web.config
file in your Views
folder, and make sure it has the following:
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="SquishIt.Framework" />
<add namespace="Your.Namespace.Etc" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
Alternatively, you can add using statements to your shared layout:
@using Your.Namespace.Etc;
<!DOCTYPE html>
<head>
....
After editing the Web.config, restart Visual Studio to apply the changes.
If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.
If you don't want word wrap, assign the CSS style white-space: nowrap
to the cells.
Use md5 library: https://github.com/blueimp/JavaScript-MD5
The shortest way:
md5(Math.random())
If you want to limit the size to 5:
md5(Math.random()).substr(0, 5)
You can get the path programmatically:
using System.Configuration; // Add a reference to System.Configuration.dll
...
var path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
I would like to describe a very good example of why negative padding
would be useful and awesome.
As all of us CSS developers know, vertically aligning a dynamically sizing div within another is a hassle, and for the most part, viewed as being impossible only using CSS. The incorporation of negative padding
could change this.
Please review the following HTML:
<div style="height:600px; width:100%;">
<div class="vertical-align" style="width:100%;height:auto;" >
This DIV's height will change based the width of the screen.
</div>
</div>
With the following CSS, we would be able to vertically center the content of the inner div
within the outer div
:
.vertical-align {
position: absolute;
top:50%;
padding-top:-50%;
overflow: visible;
}
Allow me to explain...
Absolutely positioning the inner div's top at 50% places the top edge of the inner div at the center of the outer div. Pretty simple. This is because percentage based positioning is relative to the inner dimensions of the parent element.
Percentage based padding, on the other hand, is based on the inner dimensions of the targeted element. So, by applying the property of padding-top: -50%;
we have shifted the content of the inner div upward by a distance of 50% of the height of the inner div's content, therefore centering the inner div's content within the outer div and still allowing the height dimension of the inner div to be dynamic!
If you ask me OP, this would be the best use-case, and I think it should be implemented just so I can do this hack. lol. Or, they should just fix the functionality of vertical-align
and give us a version of vertical-align
that works on all elements.
There are a few misunderstandings in the discussion above.
First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.
As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION @transaction
Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)
This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.
As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.
If you happen to use [Py]Qt already, you may be interested in qimage2ndarray. Starting with version 1.4 (just released), PySide is supported as well, and there will be a tiny imsave(filename, array)
function similar to scipy's, but using Qt instead of PIL. With 1.3, just use something like the following:
qImage = array2qimage(image, normalize = False) # create QImage from ndarray
success = qImage.save(filename) # use Qt's image IO functions for saving PNG/JPG/..
(Another advantage of 1.4 is that it is a pure python solution, which makes this even more lightweight.)
You can use prepared statement with lucek's answer and export dynamically table with columns name in CSV :
--If your table has too many columns
SET GLOBAL group_concat_max_len = 100000000;
--Prepared statement
SET @SQL = ( select CONCAT('SELECT * INTO OUTFILE \'YOUR_PATH\' FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\' ESCAPED BY \'\' LINES TERMINATED BY \'\\n\' FROM (SELECT ', GROUP_CONCAT(CONCAT("'",COLUMN_NAME,"'")),' UNION select * from YOUR_TABLE) as tmp') from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YOUR_TABLE' AND TABLE_SCHEMA = 'YOUR_SCHEMA' order BY ORDINAL_POSITION );
--Execute it
PREPARE stmt FROM @SQL;
EXECUTE stmt;
Thank lucek.
For z-index:1000
to have an effect you need a non-static positioning scheme.
Add position:relative;
to a rule selecting the element you want to be on top
Here is a work around for IE 10 and 11 users that seemed pretty straight forward.
var elem = document.getElementById('elem');
['first','second','third'].forEach(item => elem.classList.add(item));
_x000D_
<div id="elem">Hello World!</div>
_x000D_
Or
var elem = document.getElementById('elem'),
classes = ['first','second','third'];
classes.forEach(function(item) {
return elem.classList.add(item);
});
_x000D_
<div id="elem">Hello World!</div>
_x000D_
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if($response === false) {
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
There is also JSON command line processing toolkit if you happen to have node.js and npm in your stack.
And another "json" command for massaging JSON on your Unix command line.
And here are the other alternatives:
Simple Response: This worked for me with no Problem. It seems the key is to ensure that the View has focus before you getHeight etc. Do this by using the hasFocus() method, then using getHeight() method in that order. Just 3 lines of code required.
ImageButton myImageButton1 =(ImageButton)findViewById(R.id.imageButton1);
myImageButton1.hasFocus();
int myButtonHeight = myImageButton1.getHeight();
Log.d("Button Height: ", ""+myButtonHeight );//Not required
Hope it helps.
DF <- data.frame(
x=1:10,
y=10:1,
z=rep(5,10),
a=11:20
)
DF
Output:
x y z a
1 1 10 5 11
2 2 9 5 12
3 3 8 5 13
4 4 7 5 14
5 5 6 5 15
6 6 5 5 16
7 7 4 5 17
8 8 3 5 18
9 9 2 5 19
10 10 1 5 20
DF[c("a","x")] <- list(NULL)
Output:
y z
1 10 5
2 9 5
3 8 5
4 7 5
5 6 5
6 5 5
7 4 5
8 3 5
9 2 5
10 1 5
Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)
.profile-header > div {
display: inline-block;
vertical-align: bottom;
float: none;
margin: -2px;
}
.profile-header {
margin-bottom:20px;
border:2px solid green;
display: table-cell;
}
.profile-pic {
height:300px;
border:2px solid red;
}
.profile-about {
border:2px solid blue;
}
.profile-about2 {
border:2px solid pink;
}
Example here: http://www.bootply.com/125740#
In CSS you can use the color string currentColor
inside a link to eg make the border the same color as your default link color:
.example {
border: 1px solid currentColor;
}
Use the one with mysql_fetch_row
because "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. "
To avoid getting the encryption error you can also try out below commands
ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()
ftp.prot_p() ensure that your connections are encrypted
Variables declared inside a function are local to that function. For instance:
foo <- function() {
bar <- 1
}
foo()
bar
gives the following error: Error: object 'bar' not found
.
If you want to make bar
a global variable, you should do:
foo <- function() {
bar <<- 1
}
foo()
bar
In this case bar
is accessible from outside the function.
However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:
if (x > 10) {
y <- 0
}
else {
y <- 1
}
y
remains accessible after the if-else
statement.
As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:
Here you have a small example:
test.env <- new.env()
assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100
get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
Check an MD5 hash of the public key to ensure that it matches with what is in a private key
openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in privateKey.key | openssl md5
http://ryanfait.com/sticky-footer/
You could possibly use this and use jQuery to update the css height of the elements to make sure it stays in place.
Natively that is not possible, yet. See also this feature request.
So far you need to do that in your containers CMD
to wait until all required services are there.
In the Dockerfile
s CMD
you could refer to your own start script that wraps starting up your container service. Before you start it, you wait for a depending one like:
Dockerfile
FROM python:2-onbuild
RUN ["pip", "install", "pika"]
ADD start.sh /start.sh
CMD ["/start.sh"]
start.sh
#!/bin/bash
while ! nc -z rabbitmq 5672; do sleep 3; done
python rabbit.py
Probably you need to install netcat in your Dockerfile
as well. I do not know what is pre-installed on the python image.
There are a few tools out there that provide easy to use waiting logic, for simple tcp port checks:
For more complex waits:
The accepted answer works if you set the JSON as a key/value pair in the form-data
panel (See the image hereunder)
Nevertheless, I am wondering if it is a very clean way to design an API. If it is mandatory for you to upload both image and JSON in a single call maybe it is ok but if you could separate the routes (one for image uploading, the other for JSON body with a proper content-type header), it seems better.
Here are clarified instruction combining Dawn Song's answer and Marmor's answer.
Drag a long Press Gesture Recognizer and drop it into your Table Cell. It will jump to the bottom of the list on the left.
Then connect the gesture recognizer the same way you would connect a button.
Add the code from Marmor in the the action handler
- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateBegan) {
CGPoint p = [sender locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
} else {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell.isHighlighted) {
NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
}
}
}
}
argc
is the number of arguments being passed into your program from the command line and argv
is the array of arguments.
You can loop through the arguments knowing the number of them like:
for(int i = 0; i < argc; i++)
{
// argv[i] is the argument at index i
}
It's code that can be used by many applications/contexts with little or no change.
Boilerplate is derived from the steel industry in the early 1900s.
There is boolean data type in SQL Server. Its values can be TRUE
, FALSE
or UNKNOWN
. However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. =
, <>
, <
, >=
) or logical operators (e.g. AND
, OR
, IN
, EXISTS
). Boolean expressions are only allowed in a handful of places including the WHERE
clause, HAVING
clause, the WHEN
clause of a CASE
expression or the predicate of an IF
or WHILE
flow control statement.
For all other usages, including the data type of a column in a table, boolean is not allowed. For those other usages, the BIT
data type is preferred. It behaves like a narrowed-down INTEGER
which allows only the values 0
, 1
and NULL
, unless further restricted with a NOT NULL
column constraint or a CHECK
constraint.
To use a BIT
column in a boolean expression it needs to be compared using a comparison operator such as =
, <>
or IS NULL
. e.g.
SELECT
a.answer_body
FROM answers AS a
WHERE a.is_accepted = 0;
From a formatting perspective, a bit
value is typically displayed as 0
or 1
in client software. When a more user-friendly format is required, and it can't be handled at an application tier in front of the database, it can be converted "just-in-time" using a CASE
expression e.g.
SELECT
a.answer_body,
CASE a.is_accepted WHEN 1 THEN 'TRUE' ELSE 'FALSE' END AS is_accepted
FROM answers AS a;
Storing boolean values as a character data type like char(1)
or varchar(5)
is also possible, but that is much less clear, has more storage/network overhead, and requires CHECK
constraints on each column to restrict illegal values.
For reference, the schema of answers
table would be similar to:
CREATE TABLE answers (
...,
answer_body nvarchar(MAX) NOT NULL,
is_accepted bit NOT NULL DEFAULT (0)
);
For leading and trailing whitespace:
s = ' foo \t '
print s.strip() # prints "foo"
Otherwise, a regular expression works:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s) # prints "foobar"
There are no default constructors in Go, but you can declare methods for any type. You could make it a habit to declare a method called "Init". Not sure if how this relates to best practices, but it helps keep names short without loosing clarity.
package main
import "fmt"
type Thing struct {
Name string
Num int
}
func (t *Thing) Init(name string, num int) {
t.Name = name
t.Num = num
}
func main() {
t := new(Thing)
t.Init("Hello", 5)
fmt.Printf("%s: %d\n", t.Name, t.Num)
}
The result is:
Hello: 5
I'm using this one, it works with coma separator and double quote escaping. Normally that's should solved your problem :
/(?<=^|,)(\"(?:[^"]+|"")*\"|[^,]*)(?:$|,)/g
I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts. PS: I found action for startup and logout user, there is not for shutdown.
Note that the IEnumerable<T>
allready implemented by the System.Collections
so another approach is to derive your MyObjects
class from System.Collections
as a base class (documentation):
System.Collections: Provides the base class for a generic collection.
We can later make our own implemenation to override the virtual System.Collections
methods to provide custom behavior (only for ClearItems
, InsertItem
, RemoveItem
, and SetItem
along with Equals
, GetHashCode
, and ToString
from Object
). Unlike the List<T>
which is not designed to be easily extensible.
Example:
public class FooCollection : System.Collections<Foo>
{
//...
protected override void InsertItem(int index, Foo newItem)
{
base.InsertItem(index, newItem);
Console.Write("An item was successfully inserted to MyCollection!");
}
}
public static void Main()
{
FooCollection fooCollection = new FooCollection();
fooCollection.Add(new Foo()); //OUTPUT: An item was successfully inserted to FooCollection!
}
Please note that driving from collection
recommended only in case when custom collection behavior is needed, which is rarely happens. see usage.
^\w{14}$
in Perl and any Perl-style regex.
If you want to learn more about regular expressions - or just need a handy reference - the Wikipedia Entry on Regular Expressions is actually pretty good.
if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:
<c:out value="${map['key']}"/>
where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.
Inside your AJAX callback you need to call the response
function; passing the array that contains items to display.
jQuery("input.suggest-user").autocomplete({
source: function (request, response) {
jQuery.get("usernames.action", {
query: request.term
}, function (data) {
// assuming data is a JavaScript array such as
// ["[email protected]", "[email protected]","[email protected]"]
// and not a string
response(data);
});
},
minLength: 3
});
If the response JSON does not match the formats accepted by jQuery UI autocomplete then you must transform the result inside the AJAX callback before passing it to the response callback. See this question and the accepted answer.
why making life hard-
PreparedStatement pstmt = conn.prepareStatement("select * from employee where id in ("+ StringUtils.join(arraylistParameter.iterator(),",") +)");
These are automatic variables, like $null
, $true
, $false
etc.
about_Automatic_Variables
, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396
$NULL
$null
is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.Windows PowerShell treats
$null
as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.For example, when
$null
is included in a collection, it is counted as one of the objects.C:\PS> $a = ".dir", $null, ".pdf" C:\PS> $a.count 3
If you pipe the
$null
variable to theForEach-Object
cmdlet, it generates a value for$null
, just as it does for the other objects.PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"} Hello Hello Hello
As a result, you cannot use
$null
to mean "no parameter value." A parameter value of$null
overrides the default parameter value.However, because Windows PowerShell treats the
$null
variable as a placeholder, you can use it scripts like the following one, which would not work if$null
were ignored.$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null) $days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" $currentDay = 0 foreach($day in $calendar) { if($day –ne $null) { "Appointment on $($days[$currentDay]): $day" } $currentDay++ }
output:
Appointment on Tuesday: Meeting Appointment on Friday: Team lunch
TEXT
and VarChar(MAX)
are Non-Unicode large Variable Length character data type, which can store maximum of 2147483647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).
As per MSDN link Microsoft is suggesting to avoid using the Text datatype and it will be removed in a future versions of Sql Server. Varchar(Max) is the suggested data type for storing the large string values instead of Text data type.
Data of a Text
type column is stored out-of-row in a separate LOB data pages. The row in the table data page will only have a 16 byte pointer to the LOB data page where the actual data is present. While Data of a Varchar(max)
type column is stored in-row if it is less than or equal to 8000 byte. If Varchar(max) column value is crossing the 8000 bytes then the Varchar(max) column value is stored in a separate LOB data pages and row will only have a 16 byte pointer to the LOB data page where the actual data is present. So In-Row
Varchar(Max) is good for searches and retrieval.
Some of the string functions, operators or the constructs which doesn’t work on the Text type column, but they do work on VarChar(Max) type column.
=
Equal to Operator on VarChar(Max) type columnGroup by clause on VarChar(Max) type column
As we know that the VarChar(Max) type column values are stored out-of-row only if the length of the value to be stored in it is greater than 8000 bytes or there is not enough space in the row, otherwise it will store it in-row. So if most of the values stored in the VarChar(Max) column are large and stored out-of-row, the data retrieval behavior will almost similar to the one that of the Text type column.
But if most of the values stored in VarChar(Max) type columns are small enough to store in-row. Then retrieval of the data where LOB columns are not included requires the more number of data pages to read as the LOB column value is stored in-row in the same data page where the non-LOB column values are stored. But if the select query includes LOB column then it requires less number of pages to read for the data retrieval compared to the Text type columns.
Conclusion
Use VarChar(MAX)
data type rather than TEXT
for good performance.
Using wilcards (*) prevent the calc of a score
You need a different seed at every execution.
You can start to call at the beginning of your program:
srand(time(NULL));
Note that % 10
yields a result from 0
to 9
and not from 1
to 10
: just add 1
to your %
expression to get 1
to 10
.
BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.
Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.
When writing datetime value to sql db
//Convert the time into UTC and build Timestamp object.
Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
//use setTimestamp on preparedstatement
preparedStatement.setTimestamp(1, ts);
When reading the value back from DB into java,
Then, change it to your desired timezone. Here I am changing it to Toronto timezone.
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
Timestamp timestamp = resultSet.getTimestamp(1);
ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
How to fix breakpoint error when debugging in Eclipse? Replace what you have with this lines only.
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
static void Main(string[] args)
{
long blah = 20948230498204;
Console.WriteLine(blah.ToString().Length);
}
OperationQueue.main.addOperation {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "Storyboard ID") as! NewViewController
self.present(newViewController, animated: true, completion: nil)
}
It worked for me when I put the code inside of the OperationQueue.main.addOperation
, that will execute in the main thread for me.
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
Note, while the above answers are correct, if you want, you can do something like:
alert("The variable named x1 has value: " + x1);
Posting a java based solution, incase your team only uses java. The keyword inner
will ensure that matching rows only are present in the final dataframe.
Dataset<Row> joined = PersonDf.join(ProfileDf,
PersonDf.col("personId").equalTo(ProfileDf.col("personId")),
"inner");
joined.show();
change:
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
to
$("input:text").change(function() {
var value=$("input[type=text].selector").val();
alert(value);
});
note: selector:id,class..
You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.
<input type="text" name="idtest" value="<?php echo $idtest; ?>" >
Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.
I ran into this today (mysql 2.16.0) and thought I'd share my solution:
const items = [
{name: 'alpha', description: 'describes alpha', value: 1},
...
];
db.query(
'INSERT INTO my_table (name, description, value) VALUES ?',
[items.map(item => [item.name, item.description, item.value])],
(error, results) => {...}
);
You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:
sourceSheetSum.Select
sourceSheetSum.Range("C3").Select
In general one could,
merge_list <- function(...) by(v<-unlist(c(...)),names(v),base::c)
Note that the by()
solution returns an attribute
d list, so it will print differently, but will still be a list. But you can get rid of the attributes with attr(x,"_attribute.name_")<-NULL
. You can probably also use aggregate()
.
It would be easier to recreate the data frame. This would also interpret the columns types from scratch.
headers = df.iloc[0]
new_df = pd.DataFrame(df.values[1:], columns=headers)
Note: if you're in a hurry, and/or looking for short answer scroll to the bottom of the answer, and read the last two lines.if Not in a hurry read the whole thing.
let me start by stating the facts:
Syntax:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
Note #1: slice()==substring()
What it does?
The slice()
method extracts parts of a string and returns the extracted parts in a new string.
The substr()
method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
The substring()
method extracts parts of a string and returns the extracted parts in a new string.
Note #2:slice()==substring()
Changes the Original String?
slice()
Doesn't
substr()
Doesn't
substring()
Doesn't
Note #3:slice()==substring()
Using Negative Numbers as an Argument:
slice()
selects characters starting from the end of the string
substr()
selects characters starting from the end of the string
substring()
Doesn't Perform
Note #3:slice()==substr()
if the First Argument is Greater than the Second:
slice()
Doesn't Perform
substr()
since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring()
will swap the two arguments, and perform as usual
the First Argument:
slice()
Required, indicates: Starting Index
substr()
Required, indicates: Starting Index
substring()
Required, indicates: Starting Index
Note #4:slice()==substr()==substring()
the Second Argument:
slice()
Optional, The position (up to, but not including) where to end the extraction
substr()
Optional, The number of characters to extract
substring()
Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()
What if the Second Argument is Omitted?
slice()
selects all characters from the start-position to the end of the string
substr()
selects all characters from the start-position to the end of the string
substring()
selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()
so, you can say that there's a difference between slice()
and substr()
, while substring()
is basically a copy of slice()
.
in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr()
.
Like others have already said, it's not immediately obvious what you're asking. I'm going to assume that you want to start a process and then perform another action when the process "is ready".
Of course, the "is ready" is the tricky bit. Depending on what you're needs are, you may find that simply waiting is sufficient. However, if you need a more robust solution, you can consider using a named Mutex to control the control flow between your two processes.
For example, in your main process, you might create a named mutex and start a thread or task which will wait. Then, you can start the 2nd process. When that process decides that "it is ready", it can open the named mutex (you have to use the same name, of course) and signal to the first process.
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
Check you have the line:
import org.json.JSONArray;
at the top of your source code
Use SSL only and instead of encrypting the HTTP_USER_AGENT in the session id and verifying it on every request, just store the HTTP_USER_AGENT string in your session db as well.
Now you only have a simple server based string compare with the ENV'HTTP_USER_AGENT'.
Or you can add a certain variation in your string compare to be more robust against browser version updates. And you could reject certain HTTP_USER_AGENT id's. (empty ones i.e.) Does not resolve the problem completley, but it adds at least a bit more complexity.
Another method could be using more sophisticated browser fingerprinting techniques and combine theyse values with the HTTP_USER_AGENT and send these values from time to time in a separate header values. But than you should encrypt the data in the session id itself.
But that makes it far more complex and raises the CPU usage for decryption on every request.
To kill the process in shell
getprocess=`ps -ef|grep servername`
#echo $getprocess
set $getprocess
pid=$2
#echo $pid
kill -9 $pid
You've started right - now you just need to fill the each student
structure in the array:
struct student
{
public int s_id;
public String s_name, c_name, dob;
}
class Program
{
static void Main(string[] args)
{
student[] arr = new student[4];
for(int i = 0; i < 4; i++)
{
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
arr[i].s_id = Int32.Parse(Console.ReadLine());
arr[i].s_name = Console.ReadLine();
arr[i].c_name = Console.ReadLine();
arr[i].s_dob = Console.ReadLine();
}
}
}
Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.
By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.
Taking the OP's Question title as deleting all cookies - "Delete Cookies in website"
I came across code from Dave Domagala on the web somewhere. I edited Dave's to allow for Google Analytics cookies too - which looped through all cookies found on the website and deleted them all. (From a developer angle - updating new code into an existing site, is a nice touch to avoid problems with users revisiting the site).
I use the below code in tandem with reading the cookies first, holding any required data - then resetting the cookies after washing everything clean with the below loop.
The code:
int limit = Request.Cookies.Count; //Get the number of cookies and
//use that as the limit.
HttpCookie aCookie; //Instantiate a cookie placeholder
string cookieName;
//Loop through the cookies
for(int i = 0; i < limit; i++)
{
cookieName = Request.Cookies[i].Name; //get the name of the current cookie
aCookie = new HttpCookie(cookieName); //create a new cookie with the same
// name as the one you're deleting
aCookie.Value = ""; //set a blank value to the cookie
aCookie.Expires = DateTime.Now.AddDays(-1); //Setting the expiration date
//in the past deletes the cookie
Response.Cookies.Add(aCookie); //Set the cookie to delete it.
}
Addition: If You Use Google Analytics
The above loop/delete will delete ALL cookies for the site, so if you use Google Analytics - it would probably be useful to hold onto the __utmz cookie as this one keeps track of where the visitor came from, what search engine was used, what link was clicked on, what keyword was used, and where they were in the world when your website was accessed.
So to keep it, wrap a simple if statement once the cookie name is known:
...
aCookie = new HttpCookie(cookieName);
if (aCookie.Name != "__utmz")
{
aCookie.Value = ""; //set a blank value to the cookie
aCookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(aCookie);
}
All title
nodes with zipcode
or book
node as parent:
Version 1:
//title[parent::zipcode|parent::book]
Version 2:
//bookstore/book/title|//bookstore/city/zipcode/title
Version 3: (results are sorted based on source data rather than the order of book then zipcode)
//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]
or - used within true/false - a Boolean operator in xpath
| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.
According to the php manual you can do this in two ways. It depends what you need to check.
If you want to check if the given key or index exists in the array use array_key_exists
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
If you want to check if a value exists in an array use in_array
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>
Asked by many, The childs in list must not have width "match_parent" if you are looking for listview click only.
Even if you set the "Focusable" to false it wont work. Set the child's Width to wrap_content
<TextView
android:id="@+id/itemchild"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...
write old function on your fields value for example
<input type="text" name="username" value="{{ old('username') }}">
Use Instead
[ngStyle]="{'background-image':' url(' + instagram?.image + ')'}"
Another option:
"My name is Milan, people know me as Milan Vasic"
.replaceAll("Milan Vasic|Milan", "Milan Vasic"))
Hadoop:
HDFS stands for Hadoop Distributed File System which uses Computational processing model Map-Reduce.
HBase:
HBase is Key-Value storage, good for reading and writing in near real time.
Hive:
Hive is used for data extraction from the HDFS using SQL-like syntax. Hive use HQL language.
Pig:
Pig is a data flow language for creating ETL. It's an scripting language.
svick's answer is (as usual) excellent.
However, I find Dataflow to be more useful when you actually have large amounts of data to transfer. Or when you need an async
-compatible queue.
In your case, a simpler solution is to just use the async
-style parallelism:
var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customerTasks = ids.Select(i =>
{
ICustomerRepo repo = new CustomerRepo();
return repo.GetCustomer(i);
});
var customers = await Task.WhenAll(customerTasks);
foreach (var customer in customers)
{
Console.WriteLine(customer.ID);
}
Console.ReadKey();
System.getenv().each{
println it
}
Or more sophisticated:
def myvariables = getBinding().getVariables()
for (v in myvariables) {
echo "${v} " + myvariables.get(v)
}
You will need to disable "Use Groovy Sandbox" for both.
I used the above examples to craft my own function. But the missing piece for me was automatically escaping magic characters.
Here is my contribution:
function split(text, delim)
-- returns an array of fields based on text and delimiter (one character only)
local result = {}
local magic = "().%+-*?[]^$"
if delim == nil then
delim = "%s"
elseif string.find(delim, magic, 1, true) then
-- escape magic
delim = "%"..delim
end
local pattern = "[^"..delim.."]+"
for w in string.gmatch(text, pattern) do
table.insert(result, w)
end
return result
end
Try this one (right):
<string name="content" formatted="false">Great application %s ? %s ? %s \\n\\nGo to download this application %s</string>
No need to use select
just use [
instead
data[,grepl("search_string", colnames(data))]
Let's try with iris
dataset
>iris[,grepl("Sepal", colnames(iris))]
Sepal.Length Sepal.Width
1 5.1 3.5
2 4.9 3.0
3 4.7 3.2
4 4.6 3.1
5 5.0 3.6
6 5.4 3.9
Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:
A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".
Hope this helps others save themselves some hair.
You want to make sure your editorconfig is not conflicting with your user or workspace settings configuration, as I just had a bit of annoyance thinking the settings files settings were not being applied when it was my editor configuration undoing those changes.
I encountered the same problem , my resolution was to rename the the folder name under the workspace folder. i.e. com.ibm.collaboration.realtime.alertmanager.embedded
was renamed to com.ibm.collaboration.realtime.alertmanager.2embeddedxx
and rebuilt my project.
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
If you have an issue where you only want to remove trailing characters, you can try this:
WHILE EXISTS
(SELECT * FROM @ReportSet WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32)
BEGIN
UPDATE @ReportSet
SET addr_3 = LEFT(addr_3,LEN(addr_3)-1)
WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32
END
This solved a problem I had with addresses where a procedure created a field with a fixed number of lines, even if those lines were empty. To save space in my SSRS report, I cut them down.
Please be VERY careful with using the registry key approach. These are machine-wide keys and forcibily migrate ALL applications to .NET 4.0.
Many products do not work if forcibily migrated and this is a testing aid and not a production quality mechanism. Visual Studio 2008 and 2010, MSBuild, turbotax, and a host of websites, SharePoint and so on should not be automigrated.
If you need to use PowerShell with 4.0, this should be done on a per-application basis with a configuration file, you should check with the PowerShell team on the precise recommendation. This is likely to break some existing PowerShell commands.
In recent version, The following works fine:
$('.selector').datetimepicker({
maxDate: new Date()
});
maxDate
accepts a Date object as parameter.
The following found in documentation:
Multiple types supported:
Date: A date object containing the minimum date.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
String: A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.
function removeHash () {
history.pushState("", document.title, window.location.pathname
+ window.location.search);
}
App.$router.replace({name:"my-route", hash: '#update'})
App.$router.replace({name:"my-route", hash: ' ', params: {a: 100} })
setTimeout(removeHash, 0)
Notes:
#
must have some value after it.setTimeout
, not $nextTick
to keep the url clean.I would go with Lev, but it's worth pointing out that if you end up with more complex searches that using re.finditer may be worth bearing in mind (but re's often cause more trouble than worth - but sometimes handy to know)
test = "ooottat"
[ (i.start(), i.end()) for i in re.finditer('o', test)]
# [(0, 1), (1, 2), (2, 3)]
[ (i.start(), i.end()) for i in re.finditer('o+', test)]
# [(0, 3)]
Select your repository from Dashboard or Repository tab.
And then just click on Download tab having icon of download. It will Let you download whole repository in zip format.
You can also try:
INSERT IGNORE
INTO table_1
SELECT *
FROM table_2
;
which allows those rows in table_1 to supersede those in table_2 that have a matching primary key, while still inserting rows with new primary keys.
Alternatively,
REPLACE
INTO table_1
SELECT *
FROM table_2
;
will update those rows already in table_1 with the corresponding row from table_2, while inserting rows with new primary keys.
Easiest way to achieve it in Android Studio is explained below:
Step 1:
Write below line in dependencies in build.gradle
:
compile 'com.android.support:cardview-v7:+'
Step 2:
Copy below code in your xml file for integrating the CardView
.
For cardCornerRadius
to work, please be sure to include below line in parent layout:
xmlns:card_view="http://schemas.android.com/apk/res-auto"
And remember to use card_view
as namespace for using cardCornerRadius
property.
For example : card_view:cardCornerRadius="4dp"
XML Code:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view_outer"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
card_view:cardBackgroundColor="@android:color/transparent"
card_view:cardCornerRadius="0dp"
card_view:cardElevation="3dp" >
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view_inner"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="@color/green"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" >
</android.support.v7.widget.CardView>
</android.support.v7.widget.CardView>
There is nothing bad or better, It just depends on the precedence of operators. Since ||
has higher precedence than or
, so ||
is mostly used.
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
What if the first character is not a letter (but a tab, a space, and a escaped double quote)? We'd better test it until we find a letter! So:
S=' \"ó foo bar\"'
N=0
until [[ ${S:$N:1} =~ [[:alpha:]] ]]; do N=$[$N+1]; done
#F=`echo ${S:$N:1} | tr [:lower:] [:upper:]`
#F=`echo ${S:$N:1} | sed -E -e 's/./\u&/'` #other option
F=`echo ${S:$N:1}
F=`echo ${F} #pure Bash solution to "upper"
echo "$F"${S:(($N+1))} #without garbage
echo '='${S:0:(($N))}"$F"${S:(($N+1))}'=' #garbage preserved
Foo bar
= \"Foo bar=
to remove all '\' from a string, simply do the following:
myString = myString.Replace("\\", "");
The best way is probably to use the list method .index.
For the objects in the list, you can do something like:
def __eq__(self, other):
return self.Value == other.Value
with any special processing you need.
You can also use a for/in statement with enumerate(arr)
Example of finding the index of an item that has value > 100.
for index, item in enumerate(arr):
if item > 100:
return index, item
font-size:35px;
So like this:
<html>
<tr>
<td style="padding-left:5px;padding-bottom:3px;">
<strong style="font-size:35px;">Datum:</strong>
<br/>
November 2010
</td>
</tr>
</html>
Although inline styles are a bad practice and you should class things. Also you should use a <strong></strong>
tag instead of <b></b>
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
Easier way is to use the getString()
function within the activity.
String myString = getString(R.string.mystring);
Reference: http://developer.android.com/guide/topics/resources/string-resource.html
I think this feature is added in a recent Android version, anyone who knows the history can comment on this.
You can just put r
in front of the string with your actual path, which denotes a raw string. For example:
data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
The default generator for Windows seems to be set to NMAKE. Try to use:
cmake -G "MinGW Makefiles"
Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.
If you are implementing your bot, keep stored a group name -> id table, and ask it with a command. Then you can also send per name.