Example for Hamcrest:
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.jupiter.api.Test
class HamcrestAssertionDemo {
@Test
fun assertWithHamcrestMatcher() {
val subClass = SubClass()
MatcherAssert.assertThat(subClass, CoreMatchers.instanceOf<Any>(BaseClass::class.java))
}
}
Example for AssertJ:
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class AssertJDemo {
@Test
fun assertWithAssertJ() {
val subClass = SubClass()
assertThat(subClass).isInstanceOf(BaseClass::class.java)
}
}
Here's a pretty terse Java 7+ solution which relies purely on vanilla JDK classes, no third party libraries required:
public static void pack(final Path folder, final Path zipFilePath) throws IOException {
try (
FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
ZipOutputStream zos = new ZipOutputStream(fos)
) {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
zos.putNextEntry(new ZipEntry(folder.relativize(file).toString()));
Files.copy(file, zos);
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
zos.putNextEntry(new ZipEntry(folder.relativize(dir).toString() + "/"));
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
}
}
It copies all files in folder
, including empty directories, and creates a zip archive at zipFilePath
.
1. dd mmm YYYY
(in addition to dd-mmm-YYYY
, dd/mmm/YYYY
, dd.mmm.YYYY
).
2. mmm in all CAPITAL LETTERS format (in addition to Title format)
dd mmm YYYY
e.g. 30 Apr 2026
or 24 DEC 2028
are popular.
Extended regex:
(^(?:(?:(?:31(?:(?:([-.\/])(?:0?[13578]|1[02])\1)|(?:([-.\/ ])(?:Jan|JAN|Mar|MAR|May|MAY|Jul|JUL|Aug|AUG|Oct|OCT|Dec|DEC)\2)))|(?:(?:29|30)(?:(?:([-.\/])(?:0?[13-9]|1[0-2])\3)|(?:([-.\/ ])(?:Jan|JAN|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)\4))))(?:(?:1[6-9]|[2-9]\d)?\d{2}))$|^(?:29(?:(?:([-.\/])(?:0?2)\5)|(?:([-.\/ ])(?:Feb|FEB)\6))(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))$|^(?:(?:0?[1-9]|1\d|2[0-8])(?:(?:([-.\/])(?:(?:0?[1-9]|(?:1[0-2])))\7)|(?:([-.\/ ])(?:Jan|JAN|Feb|FEB|Mar|MAR|May|MAY|Jul|JUL|Aug|AUG|Oct|OCT|Dec|DEC)\8))(?:(?:1[6-9]|[2-9]\d)?\d{2}))$)
Test cases included in the Regex Demo
Features (retained):
dd/mm/YYYY
, dd-mm-YYYY
, dd.mm.YYYY
(but not dd mm YYYY
)dd mmm YYYY
, dd-mmm-YYYY
, dd/mmm/YYYY
, dd.mmm.YYYY
(dd mmm YYYY
newly added. mmm can be in CAPITAL e.g. DEC or Title format e.g. Dec)Some additional minor touch-up as follows:
Included the fix by Ofir Luzon on February 14th 2019 to remove a comma that was in the regex which allowed dates like 29-0,-11 [error replicated to Alok Chaudhary's regex]
Replaced (\/|-|\.)
by ([-.\/])
to minimize the use of backslash. \/
is still used in order to support some regex flavor e.g. PCRE(PHP) although some other regex flavor e.g. Python can simply use /
inside the character class [ ]
Added a pair of parenthesis () surrounding the whole regex to make it a capturing group for the whole matching string. This is useful for people using findAll type of functions to get a matching item list (e.g. re.findall
in Python). This enable us to capture all the matching strings within a mult-line string with the following codes:
re.findall
sample codes:
match_list = re.findall(regex, source_string)
for item in match_list:
print(item[0])
Credits should go to Ofir Luzon and Alok Chaudhary who created such excellent regexes for us all!
That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.
In Windows, there should be a Node.js command prompt in your Start menu or start screen:
Which will open a command prompt window that looks like this:
From there you can switch directories using the cd
command.
Install tampermonkey and add the following UserScript with one (or more) @match
with specific page url (or a match of all pages: https://*
) e.g.:
// ==UserScript==
// @name inject-rx
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Inject rx library on the page
// @author Me
// @match https://www.some-website.com/*
// @require https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant none
// ==/UserScript==
(function() {
'use strict';
window.injectedRx = rxjs;
//Or even: window.rxjs = rxjs;
})();
Whenever you need the library on the console, or on a snippet enable the specific UserScript and refresh.
This solution prevents namespace pollution. You can use custom namespaces to avoid accidental overwrite of existing global variables on the page.
JSON, like xml and various other formats, is a tree-based serialization format. It won't love you if you have circular references in your objects, as the "tree" would be:
root B => child A => parent B => child A => parent B => ...
There are often ways of disabling navigation along a certain path; for example, with XmlSerializer
you might mark the parent property as XmlIgnore
. I don't know if this is possible with the json serializer in question, nor whether DatabaseColumn
has suitable markers (very unlikely, as it would need to reference every serialization API)
The easiest solution is to use percentages. This isn't exactly the answer you were looking for since you asked for pixel-precision, but if you just need something to have a little padding between the right edge and the image, giving something a position of 99% usually works well enough.
Code:
/* aligns image to the vertical center and horizontal right of its container with a small amount of padding between the right edge */
div.middleleft {
background: url("/images/source.jpg") 99% center no-repeat;
}
There are not a lot of clear answers on this because you are always assuming things.
This solution calculates between two dates the months between assuming you want to save the day of month for comparison, (meaning that the day of the month is considered in the calculation)
Example, if you have a date of 30 Jan 2012, 29 Feb 2012 will not be a month but 01 March 2013 will.
It's been tested pretty thoroughly, probably will clean it up later as we use it, but here:
private static int TotalMonthDifference(DateTime dtThis, DateTime dtOther)
{
int intReturn = 0;
bool sameMonth = false;
if (dtOther.Date < dtThis.Date) //used for an error catch in program, returns -1
intReturn--;
int dayOfMonth = dtThis.Day; //captures the month of day for when it adds a month and doesn't have that many days
int daysinMonth = 0; //used to caputre how many days are in the month
while (dtOther.Date > dtThis.Date) //while Other date is still under the other
{
dtThis = dtThis.AddMonths(1); //as we loop, we just keep adding a month for testing
daysinMonth = DateTime.DaysInMonth(dtThis.Year, dtThis.Month); //grabs the days in the current tested month
if (dtThis.Day != dayOfMonth) //Example 30 Jan 2013 will go to 28 Feb when a month is added, so when it goes to march it will be 28th and not 30th
{
if (daysinMonth < dayOfMonth) // uses day in month max if can't set back to day of month
dtThis.AddDays(daysinMonth - dtThis.Day);
else
dtThis.AddDays(dayOfMonth - dtThis.Day);
}
if (((dtOther.Year == dtThis.Year) && (dtOther.Month == dtThis.Month))) //If the loop puts it in the same month and year
{
if (dtOther.Day >= dayOfMonth) //check to see if it is the same day or later to add one to month
intReturn++;
sameMonth = true; //sets this to cancel out of the normal counting of month
}
if ((!sameMonth)&&(dtOther.Date > dtThis.Date))//so as long as it didn't reach the same month (or if i started in the same month, one month ahead, add a month)
intReturn++;
}
return intReturn; //return month
}
The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:
$('form').on('submit',doFormStuff);
createNewForm();
// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);
Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:
function bindItems(){
$('form').off('submit').on('submit',doFormStuff);
$('button').off('click').on('click',doButtonStuff);
}
So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.
createNewButton();
bindItems();
I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.
Here is a guide by @CTS_AE on how to use NPM with standalone node.exe: https://stackoverflow.com/a/31148216/228508
The error indicates that the two tables have the 1 or more column names that have the same column name.
Anyone with the same error who doesn't want to provide a suffix can rename the columns instead. Also make sure the index of both DataFrames match in type and value if you don't want to provide the on='mukey'
setting.
# rename example
df_a = df_a.rename(columns={'a_old': 'a_new', 'a2_old': 'a2_new'})
# set the index
df_a = df_a.set_index(['mukus'])
df_b = df_b.set_index(['mukus'])
df_a.join(df_b)
In most situations, git fetch
should do what you want, which is 'get anything new from the remote repository and put it in your local copy without merging to your local branches'. git fetch --tags
does exactly that, except that it doesn't get anything except new tags.
In that sense, git fetch --tags
is in no way a superset of git fetch
. It is in fact exactly the opposite.
git pull
, of course, is nothing but a wrapper for a git fetch <thisrefspec>; git merge
. It's recommended that you get used to doing manual git fetch
ing and git merge
ing before you make the jump to git pull
simply because it helps you understand what git pull
is doing in the first place.
That being said, the relationship is exactly the same as with git fetch
. git pull
is the superset of git pull --tags
.
The currently preferred (Exchange 2013 and 2016) API is EWS. It is purely HTTP based and can be accessed from any language, but there are .Net and Java specific libraries.
You can use EWSEditor to play with the API.
Extended MAPI. This is the native API used by Outlook. It ends up using the MSEMS
Exchange MAPI provider, which can talk to Exchange using RPC (Exchange 2013 no longer supports it) or RPC-over-HTTP (Exchange 2007 or newer) or MAPI-over-HTTP (Exchange 2013 and newer).
The API itself can only be accessed from unmanaged C++ or Delphi. You can also use Redemption (any language) - its RDO family of objects is an Extended MAPI wrapper. To use Extended MAPI, you need to install either Outlook or the standalone (Exchange) version of MAPI (on extended support, and it does not support Unicode PST and MSG files and cannot access Exchange 2016). Extended MAPI can be used in a service.
You can play with the API using OutlookSpy or MFCMAPI.
Outlook Object Model - not Exchange specific, but it allows access to all data available in Outlook on the machine where the code runs. Cannot be used in a service.
Exchange Active Sync. Microsoft no longer invests any significant resources into this protocol.
Outlook used to install CDO 1.21 library (it wraps Extended MAPI), but it had been deprecated by Microsoft and no longer receives any updates.
There used to be a third-party .Net MAPI wrapper called MAPI33, but it is no longer being developed or supported.
WebDAV - deprecated.
Collaborative Data Objects for Exchange (CDOEX) - deprecated.
Exchange OLE DB Provider (EXOLEDB) - deprecated.
I've found this works well as a conditional within page.php
that includes the WooCommerce cart and checkout screens.
!is_page(array('cart', 'checkout'))
Is there some reason why you think that:
while(in.hasNext())
{
in.next();
words++;
}
will not consume the entire input stream?
It will do so, meaning that your other two while
loops will never iterate. That's why your values for words and lines are still set to zero.
You're probably better off reading the file one character at a time, increasing the character count each time through the loop, and also detecting the character to decide whether or not to increment the other counters.
Basically, wherever you find a \n
, increase the line count - you should probably also do this if the last character in the stream wasn't \n
.
And, whenever you transition from white-space to non-white-space, increase the word count (there'll probably be some tricky edge case processing at the stream beginning but that's an implementation issue).
You're looking at something like the following pseudo-code:
# Init counters and last character
charCount = 0
wordCount = 0
lineCount = 0
lastChar = ' '
# Start loop.
currChar = getNextChar()
while currChar != EOF:
# Every character counts.
charCount++;
# Words only on whitespace transitions.
if isWhite(lastChar) && !isWhite(currChar):
wordCount++
# Lines only on newline characters.
if currChar == '\n':
lineCount++;
lastChar = currChar
currChar = getNextChar()
# Handle incomplete last line.
if lastChar != '\n':
lineCount++;
Move Your log4j.properties file into the src folder. Open Windows explorer, browse to the directory where your project resides in. Browse to bin directory and delete all the folders with in it.
Now in eclipse click project---->clean---->OK
This would force it to build the project again,all the contents delete from bin directory will be recreated.
I took while to figure this out. At times directly clicking clean doesn't work
Following will give you active connections/ queries in postgres DB-
SELECT
pid
,datname
,usename
,application_name
,client_hostname
,client_port
,backend_start
,query_start
,query
,state
FROM pg_stat_activity
WHERE state = 'active';
You may use 'idle' instead of active to get already executed connections/queries.
Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)
you can put your data directly in a url statment like
src = 'url(imageData)' ;
and to get the image data u can use the php function
$imageContent = file_get_contents("imageDir/".$imgName);
$imageData = base64_encode($imageContent);
so you can copy paste the value of imageData and paste it directly to your url and assign it to the src attribute of your image
If your text is:
Joe said, "Fred was here with his "Wife"".
This is saved in a CSV as:
"Joe said, ""Fred was here with his ""Wife""""."
(Rule is double quotes go around the whole field, and double quotes are converted to two double quotes). So a simple Optionally Enclosed By clause is needed but not sufficient. CSVs are tough due to this rule. You can sometimes use a Replace clause in the loader for that field but depending on your data this may not be enough. Often pre-processing of a CSV is needed to load in Oracle. Or save it as an XLS and use Oracle SQL Developer app to import to the table - great for one-time work, not so good for scripting.
Using alternative dplyr package:
library("dplyr") # or library("tidyverse")
df <- df %>% mutate(id = row_number())
As some websites and other article specifies, its simple have a look to this one. https://www.sqlitetutorial.net/sqlite-import-csv/
We don't need to specify the separator for csv
file, becayse csv means comma separated.
sqlite> .separator ,
no need of this line.
sqlite> create table cities(name, population);
sqlite> .mode csv
sqlite> .import c:/sqlite/city_no_header.csv cities
This will work flawlessly :)
PS: My cities.csv with header.
name,population
Abilene,115930
Akron,217074
Albany,93994
Albuquerque,448607
Alexandria,128283
Allentown,106632
Amarillo,173627
Anaheim,328014
Defining your private methods in the @implementation
block is ideal for most purposes. Clang will see these within the @implementation
, regardless of declaration order. There is no need to declare them in a class continuation (aka class extension) or named category.
In some cases, you will need to declare the method in the class continuation (e.g. if using the selector between the class continuation and the @implementation
).
static
functions are very good for particularly sensitive or speed critical private methods.
A convention for naming prefixes can help you avoid accidentally overriding private methods (I find the class name as a prefix safe).
Named categories (e.g. @interface MONObject (PrivateStuff)
) are not a particularly good idea because of potential naming collisions when loading. They're really only useful for friend or protected methods (which are very rarely a good choice). To ensure you are warned of incomplete category implementations, you should actually implement it:
@implementation MONObject (PrivateStuff)
...HERE...
@end
Here's a little annotated cheat sheet:
MONObject.h
@interface MONObject : NSObject
// public declaration required for clients' visibility/use.
@property (nonatomic, assign, readwrite) bool publicBool;
// public declaration required for clients' visibility/use.
- (void)publicMethod;
@end
MONObject.m
@interface MONObject ()
@property (nonatomic, assign, readwrite) bool privateBool;
// you can use a convention where the class name prefix is reserved
// for private methods this can reduce accidental overriding:
- (void)MONObject_privateMethod;
@end
// The potentially good thing about functions is that they are truly
// inaccessible; They may not be overridden, accidentally used,
// looked up via the objc runtime, and will often be eliminated from
// backtraces. Unlike methods, they can also be inlined. If unused
// (e.g. diagnostic omitted in release) or every use is inlined,
// they may be removed from the binary:
static void PrivateMethod(MONObject * pObject) {
pObject.privateBool = true;
}
@implementation MONObject
{
bool anIvar;
}
static void AnotherPrivateMethod(MONObject * pObject) {
if (0 == pObject) {
assert(0 && "invalid parameter");
return;
}
// if declared in the @implementation scope, you *could* access the
// private ivars directly (although you should rarely do this):
pObject->anIvar = true;
}
- (void)publicMethod
{
// declared below -- but clang can see its declaration in this
// translation:
[self privateMethod];
}
// no declaration required.
- (void)privateMethod
{
}
- (void)MONObject_privateMethod
{
}
@end
Another approach which may not be obvious: a C++ type can be both very fast and provide a much higher degree of control, while minimizing the number of exported and loaded objc methods.
I think this will cover any possible scenario for what is in O10:
=IF(ISBLANK(O10),"",IF(O10<TODAY(),IF(TODAY()-O10<>1,CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," days"),CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," day")),IF(O10=TODAY(),"Due Today","Overdue")))
For Dates that are before Today, it will tell you how many days the item is due in. If O10 = Today then it will say "Due Today". Anything past Today and it will read overdue. Lastly, if it is blank, the cell will also appear blank. Let me know what you think!
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
If Not temp_rst1 Is Nothing Then ...
Try to keep all constant at one place, In my application I have created constants folder inside initializers as follows:
and I usually keep all constant in these files.
In your case you can create file under constants folder as colors_constant.rb
colors_constant.rb
Don't forgot to restart server
This has a good general description: https://gephi.wordpress.com/tag/maven/
Let me make a few statement that can put the difference in focus:
We migrated our code base from Ant to Maven
All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.
Basic functionalities of a repository manager like Sonatype are:
There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();
Have a look at ?"%in%"
.
dt[dt$fct %in% vc,]
fct X
1 a 2
3 c 3
5 c 5
7 a 7
9 c 9
10 a 1
12 c 2
14 c 4
You could also use ?is.element
:
dt[is.element(dt$fct, vc),]
I had to use Debug.print
instead of Print
, which works in the Immediate window.
Sub SendEmail()
'Dim objHTTP As New MSXML2.XMLHTTP
'Set objHTTP = New MSXML2.XMLHTTP60
'Dim objHTTP As New MSXML2.XMLHTTP60
Dim objHTTP As New WinHttp.WinHttpRequest
'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost:8888/rest/mail/send"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
Debug.Print objHTTP.Status
Debug.Print objHTTP.ResponseText
End Sub
It depends on what you want to do with the script (or any other program you want to run).
If you just want to run the script system
is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).
If you want to either feed the shell script via its standard input or consume its standard output you can use popen
(and pclose
) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.
Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.
The system calls of interest are fork
, execve
, and waitpid
. You may want to use one of the library wrappers around execve
(type man 3 exec
for a list of them). You may also want to use one of the other wait functions (man 2 wait
has them all). Additionally you may be interested in the system calls clone
and vfork
which are related to fork.
fork
duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.
execve
replaces the current program with a new program (keeping the same process id).
waitpid
is used by a parent process to wait on a particular child process to finish.
Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.
You may also be interested in the pipe
and dup2
system calls. pipe
creates a pipe (with both an input and an output file descriptor). dup2
duplicates a file descriptor as a specific file descriptor (dup
is similar but duplicates a file descriptor to the lowest available file descriptor).
I found another way to solve it - use Table Lock. Sure, it can be unappropriate for your application - if you need to update table at same time.
See:
Try using LOCK TABLES
to lock the entire table, instead of the default action of InnoDB's MVCC row-level locking. If I'm not mistaken, the "lock table" is referring to the InnoDB internal structure storing row and version identifiers for the MVCC implementation with a bit identifying the row is being modified in a statement, and with a table of 60 million rows, probably exceeds the memory allocated to it. The LOCK TABLES
command should alleviate this problem by setting a table-level lock instead of row-level:
SET @@AUTOCOMMIT=0;
LOCK TABLES avgvol WRITE, volume READ;
INSERT INTO avgvol(date,vol)
SELECT date,avg(vol) FROM volume
GROUP BY date;
UNLOCK TABLES;
Jay Pipes, Community Relations Manager, North America, MySQL Inc.
Plenty of good ideas on this thread. I have a lot of popups in my page for handling user input. What I use, is a combination of disabling the mousewheel and hiding the scrollbar:
this.disableScrollFn= function(e) {
e.preventDefault(); e.stopPropagation()
};
document.body.style.overflow = 'hidden';
$('body').on('mousewheel', this.disableScrollFn);
Advantage of this is we stop the user from scrolling in any possible way, and without having to change css position and top properties. I'm not concerened about touch events, since touch outside would close the popup.
To disable this, upon closing the popup I do the following.
document.body.style.overflow = 'auto';
$('body').off('mousewheel', this.disableScrollFn);
Note, I store a reference to my disableScrollFn on the existing object (in my case a PopupViewModel), for that gets triggered upon closing the popup to have access to disableScrollFn.
If you used [STAThread]
to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!
Private void YourFunc(..)
{
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(delegate()
{
// Call your method YourFunc(..);
}));
}
else
{
///
}
In the layout set your input method options to search.
<EditText
android:imeOptions="actionSearch"
android:inputType="text" />
In the java add the editor action listener.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
Do you have an activity set up the be the launched activity when the application starts?
This is done in your Manifest.xml file, something like:
<activity android:name=".Main" android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The expression to use inside SELECT could be
CAST(IIF(FC.CourseId IS NOT NULL, 1, 0) AS BIT)
Many UNIX programs respect the http_proxy
environment variable, curl included. The format curl accepts is [protocol://]<host>[:port]
.
In your shell configuration:
export http_proxy http://proxy.server.com:3128
For proxying HTTPS requests, set https_proxy
as well.
Curl also allows you to set this in your .curlrc
file (_curlrc
on Windows), which you might consider more permanent:
http_proxy=http://proxy.server.com:3128
You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:
WITH tab AS (
bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
BatchID,
AccountNo,
APartyNo,
SourceRowID
)
SELECT * FROM tab
Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.
As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).
Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.
Considering if you haven't committed your changes in a while, maybe doing this will work for you.
git add files
git commit -m "Your Commit"
git push -u origin master
That worked for me, hopefully it does for you too.
I hope it will help someone else.
Question above states that query param value is needed after page has been redirected and we can assume that snapshot value (the no-observable alternative) would be sufficient.
No one here mentioned about snapshot.paramMap.get from the official documentation.
this.route.snapshot.paramMap.get('id')
So before sending it add this in sending/re-directing component:
import { Router } from '@angular/router';
then re-direct as either (documented here):
this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
or simply:
this.router.navigate(['/heroes', heroId ]);
Make sure you have added this in your routing module as documented here:
{ path: 'hero/:id', component: HeroDetailComponent }
And finally, in your component which needs to use the query param
add imports (documented here):
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
inject ActivatedRoute
( documentation also imports switchMap and also injects Router and HeroService - but they are needed for observable alternative only - they are NOT needed when you use snapshot alternative as in our case ):
constructor(
private route: ActivatedRoute
) {}
and get the value you need ( documented here):
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
}
NOTE: IF YOU ADD ROUTING-MODULE TO A FEATURE MODULE (AS SHOWN IN DOCUMENTATION) MAKE SURE THAT IN APP.MODULE.ts THAT ROUTING MODULE COMES BEFORE AppRoutingModule (or other file with root-level app routes) IN IMPORTS: [] . OTHERWISE FEATURE ROUTES WILL NOT BE FOUND (AS THEY WOULD COME AFTER { path: '**', redirectTo: '/not-found' } and you would see only not-found message).
The C style loop in @chepner's answer is in the shell function update_terminal_cwd
, and the grep -o .
solution is clever, but I was surprised not to see a solution using seq
. Here's mine:
read word
for i in $(seq 1 ${#word}); do
echo "${word:i-1:1}"
done
In Visual Studio 2013, I couldn't get "Include in Project" to work when right-clicking on a folder. What did work is expanding the folder, selecting all the files then choosing "Include in Project". It was quite tedious as you have to do each folder one by one (but at least you can do all files in each folder in one go), and it appears to store the file path (you can see this by viewing properties on the file and looking at the "Relative Path" option.)
I am hoping to use this to deploy some data files in a Visual Studio Installer project, and it seems to pick up the included files and preserve their paths.
new Guid(string)
You could also look at using a TypeConverter
.
If the "core problem" is assigning class variables using functions, an alternative is to use a metaclass (it's kind of "annoying" and "magical" and I agree that the static method should be callable inside the class, but unfortunately it isn't). This way, we can refactor the behavior into a standalone function and don't clutter the class.
class KlassMetaClass(type(object)):
@staticmethod
def _stat_func():
return 42
def __new__(cls, clsname, bases, attrs):
# Call the __new__ method from the Object metaclass
super_new = super().__new__(cls, clsname, bases, attrs)
# Modify class variable "_ANS"
super_new._ANS = cls._stat_func()
return super_new
class Klass(object, metaclass=KlassMetaClass):
"""
Class that will have class variables set pseudo-dynamically by the metaclass
"""
pass
print(Klass._ANS) # prints 42
Using this alternative "in the real world" may be problematic. I had to use it to override class variables in Django classes, but in other circumstances maybe it's better to go with one of the alternatives from the other answers.
The following helped me in Win10.
%M3_HOME%\bin;
as value for Path variable under User Variables.M3_HOME
variable under System Variables.%M3_HOME%\bin;
as value for Path variable under System Variables.mvn -version
It will work.
You have to wrap the word in a span to accomplish this.
Your Last Edittext .setOnEditorActionListener call this method automatic hit api
I was Call in LoginActivity in et_password
et_Pass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
Log.i(TAG,"Enter pressed");
Log.i(Check Internet," and Connect To Server");
}
return false;
}
});
Working Fine
It depends where exactly you want to get the information from. You have a bunch of options:
<manifest>
element will have a package
attribute.adb
, you can launch adb shell
and execute pm list packages -f
, which shows the package name for each installed apk.PackageManager
Once you've got the package name, you simply link to market://search?q=pname:<package_name>
or http://market.android.com/search?q=pname:<package_name>
. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).
That's should show the difference between the two dates in minutes. Try it in your browser:
const currDate = new Date('Tue Feb 13 2018 13:04:58 GMT+0200 (EET)')
const oldDate = new Date('Tue Feb 13 2018 12:00:58 GMT+0200 (EET)')
(currDate - oldDate) / 60000 // 64
for my projects I use my commons-version library https://github.com/raydac/commons-version
it contains two auxiliary classes - to parse version (parsed version can be compared with another version object because it is comparable one) and VersionValidator which allows to check version for some expression like !=ide-1.1.1,>idea-1.3.4-SNAPSHOT;<1.2.3
If you are trying to make more than just one folder on the root of the sdcard,
ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"
then instead of folder.mkdir()
you would use folder.mkdirs()
I've made this mistake in the past & I took forever to figure it out.
In the sys
package, you can find a lot of useful information about your installation:
import sys
print sys.executable
print sys.exec_prefix
I'm not sure what this will give on your Windows system, but on my Mac executable
points to the Python binary and exec_prefix
to the installation root.
You could also try this for inspecting your sys
module:
import sys
for k,v in sys.__dict__.items():
if not callable(v):
print "%20s: %s" % (k,repr(v))
the $ sign in the string is for definition of interpolation string that is a feature in C# to interpolate the string is a "true string" that might contain interpolated expressions
for further information this is the source of the answer and example: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
You need to subscribe to the KeyDown
event on the text box. Then something like this:
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
&& e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*'
&& e.KeyChar != '/')
{
e.Handled = true;
return;
}
e.Handled=false;
return;
}
The important thing to know is that if you changed the Handled
property to true
, it will not process the keystroke. Setting it to false
will.
You can find online tools that use a dictionary to retrieve the original message.
In some cases, the dictionary method might just be useless:
For example, here is one MD5 decrypter online tool.
If you use an operating system that uses copy-on-write fork()
semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).
The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy
or array
), place that in shared memory, wrap it with multiprocessing.Array
, and pass that to your functions. This answer shows how to do that.
If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing
provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager
proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).
The Manager
approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.
There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing
is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.
This is very late, but I thought it could be useful to someone should they reference this question. I beleive the below JS will do what is asked.
<script>
$(document).ready(function()
{
document.getElementById('select').size=3;
});
</script>
I think the query you want is this:
SELECT BrandId, SUM(ICount),
SUM(sum(ICount)) over () as TotalCount,
100.0 * SUM(ICount) / SUM(sum(Icount)) over () as Percentage
FROM Table
WHERE DateId = 20130618
group by BrandId;
This does the group by
for brand. And it calculates the "Percentage". This version should produce a number between 0 and 100.
In C, except for a few special cases, an array reference always "decays" to a pointer to the first element of the array. Therefore, it isn't possible to pass an array "by value". An array in a function call will be passed to the function as a pointer, which is analogous to passing the array by reference.
EDIT: There are three such special cases where an array does not decay to a pointer to it's first element:
sizeof a
is not the same as sizeof (&a[0])
.&a
is not the same as &(&a[0])
(and not quite the same as &a[0]
).char b[] = "foo"
is not the same as char b[] = &("foo")
.Following should do the trick:
BigDecimal d = new BigDecimal(10);
int i = d.intValue();
You could use Range.Rows
, Range.Columns
or Range.Cells
. Each of these collections contain Range
objects.
Here's how you could modify Dick's example so as to work with Rows
:
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCell In rRng.Rows
Debug.Print rCell.Address, rCell.Value
Next rCell
End Sub
And Columns
:
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCol In rRng.Columns
For Each rCell In rCol.Rows
Debug.Print rCell.Address, rCell.Value
Next rCell
Next rCol
End Sub
i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.
This worked for me:
a &= a && b()
d3dave's answer is cool. However theGreenGarbage mentioned an issue about it which I too find rather annoying. So here's one that doesn't immediately suggest something after '=' sign and when typing blank space:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.(!+-*/~,[{@#$%^&
What I did was simply remove the space and '=' chars from the array :)
Alternatively if you want suggestions when typing blank space, but not after '=' sign:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .(!+-*/~,[{@#$%^&
the one liner for python3 is :
def bytes_xor(a, b) :
return bytes(x ^ y for x, y in zip(a, b))
where a
, b
and the returned value are bytes()
instead of str()
of course
can't be easier, I love python3 :)
var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);
It is also possible to set the error action preference on individual cmdlets, not just for the whole script. This is done using the parameter ErrorAction (alisa EA) which is available on all cmdlets.
Example
try
{
Write-Host $ErrorActionPreference; #Check setting for ErrorAction - the default is normally Continue
get-item filethatdoesntexist; # Normally generates non-terminating exception so not caught
write-host "You will hit me as exception from line above is non-terminating";
get-item filethatdoesntexist -ErrorAction Stop; #Now ErrorAction parameter with value Stop causes exception to be caught
write-host "you won't reach me as exception is now caught";
}
catch
{
Write-Host "Caught the exception";
Write-Host $Error[0].Exception;
}
clean package exec:java -P Class_Containing_Main_Method
command is also an option if you have only one Main method(PSVM) in the project, with the following Maven Setup.
Don't forget to mention the class in the <properties></properties>
section of pom.xml
:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.main.class>com.test.service.MainTester</java.main.class>
</properties>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>${java.main.class}</mainClass>
</configuration>
</plugin>
STS Run Configuration along with above Maven Setup:
This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.
I will repeat this bit
$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);
Obviously you would format it better than this www.someurl.com?x=$query
And to get the data back
parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];
display PDF file into WinForms
Displaying a pdf file from Winform.
displaying a pdf on a windows form?
How to display PDF or Word's DOC/DOCX inside WinForms window?
you probably want to do this:
cd /d %~dp0
cmd.exe
this will set your current directory to the directory you have the batch file in
I wanted to give some kudos to the comment that mentioned CTRL + Z as an option. At the end of the day, it's going to depend on what system that you have Git installed on and what program is configured to open text files (e.g. less vs. vim). CTRL + Z works for vim on Windows.
If you're using Git in a Windows environment, there are some quirks. Just helps to know what they are. (i.e. Notepad vs. Nano, etc.).
try apt-file. It is difficult to remember the package name where the missing file resides. It is generic and useful for any package files.
For example:
root@ubuntu234:~/auto# apt-file search --regexp '/Python.h$'
pypy-dev: /usr/lib/pypy/include/Python.h
python2.7-dbg: /usr/include/python2.7_d/Python.h
python2.7-dev: /usr/include/python2.7/Python.h
python3.2-dbg: /usr/include/python3.2dmu/Python.h
python3.2-dev: /usr/include/python3.2mu/Python.h
root@ubuntu234:~/auto#
Now you can make an expert guess as to which one to choose from.
I just created a simple timer using the MVP pattern (however it may be overkill for that simple project). It has quit, start/pause and a stop button. Time is displayed in HH:MM:SS format. Time counting is implemented using a thread that is running several times a second and the difference between the time the timer has started and the current time.
Hello here is a simple solution,
Just go to File -> Convert to a C/C++ Autotools Project Select your project files appropriately.
Inclusions will be added to your project file
I use two different ways depending on the object.
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
Sometimes I do not want to evaluate an empty string as falsey, so then I use this case
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.
The convention for out of range in JavaScript is using RangeError
. To check the type use if / else + instanceof
starting at the most specific to the most generic
try {
throw new RangeError();
}
catch (e){
if (e instanceof RangeError){
console.log('out of range');
} else {
throw;
}
}
If you use sufficiently big list not in b
clause will do a linear search for each of the item in a
. Why not use set? Set takes iterable as parameter to create a new set object.
>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}
Newer versions of Python for Windows come with the pip package manager. (source)
pip is already installed if you're using Python 2 >=2.7.9 or Python 3 >=3.4
Use that to install packages:
cd C:\Python\Scripts\
pip.exe install <package-name>
So in your case it'd be:
pip.exe install mechanize
I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.
The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.
Google 'python += operator' leads you to http://docs.python.org/library/operator.html
Search for += once the page loads up for a more detailed answer.
I removed your document.getElementById("Save").onclick =
before your functions, because it's an event already being called on your button. I also had to call the two functions separately by the onclick event.
<!DOCTYPE html>
<html>
<head>
<script>
function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State:
<select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1(); fun();">click</td></tr></table>
</body>
</html>
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
My solution is a mix of several answers here.
I checked the build server, and Windows7/NET4.0 SDK was already installed, so I did find the path:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets`
However, on this line:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" />
$(MSBuildExtensionsPath) expands to C:\Program Files\MSBuild which does not have the path.
Therefore what I did was to create a symlink, using this command:
mklink /J "C:\Program Files\MSBuild\Microsoft\VisualStudio" "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio"
This way the $(MSBuildExtensionsPath) expands to a valid path, and no changes are needed in the app itself, only in the build server (perhaps one could create the symlink every build, to make sure this step is not lost and is "documented").
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});
How can we read data from a text file and store in a String Variable?
Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.
Is it possible to pass the filename in a method and it would return the String which is the text from the file.
Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.
Same problem, I have just purged cache
rm -rf var/cache/*
Et voila ! I don't understand what it was...
Here is a example of embedding without an iFrame:
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
<embed
src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
wmode="transparent"
type="video/mp4"
width="100%" height="100%"
allow="autoplay; encrypted-media; picture-in-picture"
allowfullscreen
title="Keyboard Cat"
>
</div>
_x000D_
compare to regular iframe "embed" code from YouTube:
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
_x000D_
and as far as HTML5 goes, use <object>
tag like so (corrected):
<object
style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
You may also pass the float value, and use:
String.format("%.2f", floatValue);
To open the back camera:-
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)
To open the front camera:-
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 24 Android version 7.0(Samsung S6)
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 27 Android version 8.0(Nexus 6P)
cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
}
else -> cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1) // Tested API 21 Android version 5.0.1(Samsung S4)
}
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)
I could not make it work for API 28 and above. Also, opening the front camera directly is not possible in some devices(depends on the manufacturer).
Here is a fast and simple solution.
Pick two random numbers in the range (0, 1), namely a
and b
. If b < a
, swap them. Your point is (b*R*cos(2*pi*a/b), b*R*sin(2*pi*a/b))
.
You can think about this solution as follows. If you took the circle, cut it, then straightened it out, you'd get a right-angled triangle. Scale that triangle down, and you'd have a triangle from (0, 0)
to (1, 0)
to (1, 1)
and back again to (0, 0)
. All of these transformations change the density uniformly. What you've done is uniformly picked a random point in the triangle and reversed the process to get a point in the circle.
The Html is:
<input id="cf_1268591" style="width:60px;line-height:16px;border:1px solid #ccc">
The Jquery is:
$("#cf_1268591").combobox({
url:"your url",
valueField:"id",
textField:"text",
panelWidth: "350",
panelHeight: "200",
});
// make after keyup with empty string
var tb = $("#cf_1268591").combobox("textbox");
tb.bind("keyup",function(e){
this.value = "";
});
Without any external tool you can simply accomplish this on Windows 7 or 8, by opening up the Resource monitor and on the CPU or Overview tab right clicking on the process and selecting Suspend Process. The Resource monitor can be started from the Performance tab of the Task manager.
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
BigInteger
must support values in the range-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.Implementation note:
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range of-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive).
From blubb answer:
You can also directly form the tuple using values from each list
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = (d1[k], d2[k])
This might be useful if you had a specific ordering for your tuples
ds = [d1, d2, d3, d4]
d = {}
for k in d1.keys():
d[k] = (d3[k], d1[k], d4[k], d2[k]) #if you wanted tuple in order of d3, d1, d4, d2
This has already been answered very well technically, but let me give a concrete example of how it's extremely useful:
Lets say you have two tables, Customer and Order. Customers have many Orders.
I want to create a view that gives me details about customers, and the most recent order they've made. With just JOINS, this would require some self-joins and aggregation which isn't pretty. But with Cross Apply, its super easy:
SELECT *
FROM Customer
CROSS APPLY (
SELECT TOP 1 *
FROM Order
WHERE Order.CustomerId = Customer.CustomerId
ORDER BY OrderDate DESC
) T
one line only
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
extended the very nice solution "with format string" from JSmyth to also support
console.log
variations (log
,debug
,info
,warn
,error
)09:05:11.518
vs. 2018-06-13T09:05:11.518Z
)console
or its functions do not exist in browsers.
var Utl = {
consoleFallback : function() {
if (console == undefined) {
console = {
log : function() {},
debug : function() {},
info : function() {},
warn : function() {},
error : function() {}
};
}
if (console.debug == undefined) { // IE workaround
console.debug = function() {
console.info( 'DEBUG: ', arguments );
}
}
},
/** based on timestamp logging: from: https://stackoverflow.com/a/13278323/1915920 */
consoleWithTimestamps : function( getDateFunc = function(){ return new Date().toJSON() } ) {
console.logCopy = console.log.bind(console)
console.log = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.logCopy.apply(this, args)
} else this.logCopy(timestamp, args)
}
}
console.debugCopy = console.debug.bind(console)
console.debug = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.debugCopy.apply(this, args)
} else this.debugCopy(timestamp, args)
}
}
console.infoCopy = console.info.bind(console)
console.info = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.infoCopy.apply(this, args)
} else this.infoCopy(timestamp, args)
}
}
console.warnCopy = console.warn.bind(console)
console.warn = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.warnCopy.apply(this, args)
} else this.warnCopy(timestamp, args)
}
}
console.errorCopy = console.error.bind(console)
console.error = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.errorCopy.apply(this, args)
} else this.errorCopy(timestamp, args)
}
}
}
} // Utl
Utl.consoleFallback()
//Utl.consoleWithTimestamps() // defaults to e.g. '2018-06-13T09:05:11.518Z'
Utl.consoleWithTimestamps( function(){ return new Date().toJSON().replace( /^.+T(.+)Z.*$/, '$1' ) } ) // e.g. '09:05:11.518'
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
The .encode
method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs
module in the standard library and codecs.open
in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv
module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:
import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
print field1, field2, field3
PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv
module level), of the form line.decode('whateverweirdcodec').encode('utf-8')
-- but probably you can just use the name of your existing encoding in the yield
line in my code above, instead of 'utf-8'
, as csv
is actually going to be just fine with ISO-8859-* encoded bytestrings.
As of December 2016, the Clone or download button is still under the <> Code
tab, however it is now to the far right of the header:
<input type="number" step="any">
This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
getResource()
directly on the class.If you need an array, separate the array columns with a comma:
SELECT * FROM (VALUES('WOMENS'),('MENS'),('CHILDRENS')) as X([Attribute])
,(VALUES(742),(318)) AS z([StoreID])
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
Help
Install New Software
---> Add
Add Repository
write the Name: ADT
(or whatever you want)https://dl-ssl.google.com/android/eclipse/
Developer Tools
and NDK Plugins
Developer Tool
onlyNext
Finish
Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.
Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!
Judging from everything you've said, it seems like the original Odómetro
string you're dealing with is encoded with ISO 8859-1, not UTF-8.
Here's why I think so:
json_encode
produced parseable output after you ran the input string through utf8_encode
, which converts from ISO 8859-1 to UTF-8.print_r
after doing utf8_encode
, but the mangled output you got is actually exactly what would happen by trying to parse UTF-8 text as ISO 8859-1 (ó is \x63\xb3
in UTF-8, but that sequence is ó
in ISO 8859-1.htmlentities
hackaround solution worked. htmlentities
needs to know what the encoding of the input string to work correctly. If you don't specify one, it assumes ISO 8859-1. (html_entity_decode
, confusingly, defaults to UTF-8, so your method had the effect of converting from ISO 8859-1 to UTF-8.)PHP will use the \uXXXX
escaping, but as you noted, this is valid JSON.
So, it seems like you need to configure your connection to Postgres so that it will give you UTF-8 strings. The PHP manual indicates you'd do this by appending options='--client_encoding=UTF8'
to the connection string. There's also the possibility that the data currently stored in the database is in the wrong encoding. (You could simply use utf8_encode
, but this will only support characters that are part of ISO 8859-1).
Finally, as another answer noted, you do need to make sure that you're declaring the proper charset, with an HTTP header or otherwise (of course, this particular issue might have just been an artifact of the environment where you did your print_r
testing).
for some one who's using Kotlin
addOnTextChanged
is not flexible enought to handle some cases (ex: detect if user press delete when edit text was empty)
setOnkeyListener
worked even soft keyboard or hardkeyboard! but just on some devices. In my case, it work on Samsung s8 but not work on Xiaomi mi8 se.
if you using kotlin, you can use crossline function doOnTextChanged
, it's the same as addOnTextChanged
but callback is triggered even edit text was empty.
NOTE: doOnTextChanged is a part of Android KTX library
This isn't exactly intuitive, but you cannot Redim(VB6 Ref) an array if you dimmed it with dimensions. Exact quote from linked page is:
The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).
In other words, instead of dim invoices(10,0)
You should use
Dim invoices()
Redim invoices(10,0)
Then when you ReDim, you'll need to use Redim Preserve (10,row)
Warning: When Redimensioning multi-dimensional arrays, if you want to preserve your values, you can only increase the last dimension. I.E. Redim Preserve (11,row)
or even (11,0)
would fail.
On the comments:
sscanf(Abcd, "%f %s", &f,&s);
Gives an Error.
This is the right way:
sscanf(Abcd, "%f %s", &f,qPrintable(s));
I tried with this method and it significantly reduced my database insert execution time.
List<string> toinsert = new List<string>();
StringBuilder insertCmd = new StringBuilder("INSERT INTO tabblename (col1, col2, col3) VALUES ");
foreach (var row in rows)
{
// the point here is to keep values quoted and avoid SQL injection
var first = row.First.Replace("'", "''")
var second = row.Second.Replace("'", "''")
var third = row.Third.Replace("'", "''")
toinsert.Add(string.Format("( '{0}', '{1}', '{2}' )", first, second, third));
}
if (toinsert.Count != 0)
{
insertCmd.Append(string.Join(",", toinsert));
insertCmd.Append(";");
}
using (MySqlCommand myCmd = new MySqlCommand(insertCmd.ToString(), SQLconnectionObject))
{
myCmd.CommandType = CommandType.Text;
myCmd.ExecuteNonQuery();
}
*Create SQL connection object and replace it where I have written SQLconnectionObject.
There's no such standard equivalent. Some IDEs - Intellij, for instance, or Eclipse - can fold depending on the code types involved (constructors, imports etc.), but there's nothing quite like #region
.
The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read
into that buffer, and write
from that buffer into your socket (you could also use send
and recv
, which are socket-specific ways of writing and reading data). The outline would look something like this:
while (1) {
// Read data into buffer. We may not have enough to fill up buffer, so we
// store how many bytes were actually read in bytes_read.
int bytes_read = read(input_file, buffer, sizeof(buffer));
if (bytes_read == 0) // We're done reading from the file
break;
if (bytes_read < 0) {
// handle errors
}
// You need a loop for the write, because not all of the data may be written
// in one call; write will return how many bytes were written. p keeps
// track of where in the buffer we are, while we decrement bytes_read
// to keep track of how many bytes are left to write.
void *p = buffer;
while (bytes_read > 0) {
int bytes_written = write(output_socket, p, bytes_read);
if (bytes_written <= 0) {
// handle errors
}
bytes_read -= bytes_written;
p += bytes_written;
}
}
Make sure to read the documentation for read
and write
carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue
statement, while others mean something is broken and you need to stop.
For sending the file to a socket, there is a system call, sendfile
that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap
(as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile
call but no analogous recvfile
.
Beware that sendfile
is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile
, but the exact interface may vary (FreeBSD, Mac OS X, Solaris).
In Linux 2.6.17, the splice
system call was introduced, and as of 2.6.23 is used internally to implement sendfile
. splice
is a more general purpose API than sendfile
. For a good description of splice
and tee
, see the rather good explanation from Linus himself. He points out how using splice
is basically just like the loop above, using read
and write
, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").
s = "I have white space".delete(' ')
And to emulate PHP's trim()
function:
s = " I have leading and trailing white space ".strip
Use datetime.datetime.strptime
:
>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5
<input type="radio" name="gender" value="male"<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>: "checked='checked'" %> >Male
<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
I use this function htmlentities($string):
$msg = "<script>alert("hello")</script> <h1> Hello World </h1>" $msg = htmlentities($msg); echo $msg;
add the following to the "floating" view
position: 'absolute'
you may also need to add a top and left value for positioning
see this example: https://rnplay.org/apps/OjzcxQ/edit
I had same issue. Resolved by firstly setting :
imageView.setMinHeight(0);
imageView.setMinimumHeight(0);
And then :
imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;
setMinHeight is defined by ImageView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.
Option 1:
Use pandas
dataframe plot (built on top of matplotlib
):
import pandas as pd
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
pd.DataFrame(data).plot(kind='density') # or pd.Series()
Option 2:
Use distplot
of seaborn
:
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.distplot(data, hist=False)
You can create a 'comment' table, with an id as primary key, then you add a text field to capture the text inserted by the user and you need another field to link the comment table to the article table (foreign key). Plus you need a field to store the user that has entered a comment, this field can be the user's email. Then you capture via GET or POST the user's email and comment and you insert everything in the DB:
"INSERT INTO comment (comment, email, approved) VALUES ('$comment', '$email', '$approved')"
This is a first hint. Of course adding a comment feature it takes a little bit. Then you should think about a form to let the admin to approve the comments and how to publish the comments in the end of articles.
If you are using $.ajax()
you can use somthing like this:
$.ajax({
url: "destination url",
success: sdialog,
error: edialog,
// shows the loader element before sending.
beforeSend: function() {
$("#imgSpinner1").show();
},
// hides the loader after completion of request, whether successfull or failor.
complete: function() {
$("#imgSpinner1").hide();
},
type: 'POST',
dataType: 'json'
});
Although the setting is named "beforeSend", as of jQuery 1.5 "beforeSend" will be called regardless of the request type. i.e. The .show()
function will be called if type: 'GET'
.
Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.
I have used the following logic in SSRS reports.
BUS_DATE = 17-09-2013
X=DATEADD(MONTH,-1,BUS_DATE) = 17-08-2013
Y=DAY(BUS_DATE)=17
first_date = DATEADD(DAY,-Y+1,X)=01-08-2013
last_date = DATEADD(DAY,-Y,BUS_DATE)=31-08-2013
You can do it by making the following CSS. you can put here the css you need to affect child class in case of hover on the root
.root:hover .child {_x000D_
_x000D_
}
_x000D_
Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:
It uses the child_process
core module:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
const { spawn } = require('child_process');
const pyProg = spawn('python', ['./../pypy.py']);
pyProg.stdout.on('data', function(data) {
console.log(data.toString());
res.write(data);
res.end('end');
});
})
app.listen(4000, () => console.log('Application listening on port 4000!'))
It doesn't require sys
module in your Python script.
Below is a more modular way of performing the task using Promise
:
const express = require('express')
const app = express()
let runPy = new Promise(function(success, nosuccess) {
const { spawn } = require('child_process');
const pyprog = spawn('python', ['./../pypy.py']);
pyprog.stdout.on('data', function(data) {
success(data);
});
pyprog.stderr.on('data', (data) => {
nosuccess(data);
});
});
app.get('/', (req, res) => {
res.write('welcome\n');
runPy.then(function(fromRunpy) {
console.log(fromRunpy.toString());
res.end(fromRunpy);
});
})
app.listen(4000, () => console.log('Application listening on port 4000!'))
Without opening Xcode:
open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app/
This is the simple example to use both of them:
import {
Directive, HostListener, HostBinding
}
from '@angular/core';
@Directive({
selector: '[Highlight]'
})
export class HighlightDirective {
@HostListener('mouseenter') mouseover() {
this.backgroundColor = 'green';
};
@HostListener('mouseleave') mouseleave() {
this.backgroundColor = 'white';
}
@HostBinding('style.backgroundColor') get setColor() {
return this.backgroundColor;
};
private backgroundColor = 'white';
constructor() {}
}
Introduction:
HostListener can bind an event to the element.
HostBinding can bind a style to the element.
this is directive, so we can use it for
Some TextSo according to the debug, we can find that this div has been binded style = "background-color:white"
Some Textwe also can find that EventListener of this div has two event: mouseenter
and mouseleave
. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.
The simplest solution is to select the second cell, and press =
. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1
) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.
To read up more on different options for referencing see - This Article.
Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:
@echo off
setlocal enabledelayedexpansion
set myvar=the list:
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%
Also consider the following restriction (MSDN):
The maximum individual environment variable size is 8192bytes.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
Building on all the other solutions posted, I made a simple little UILabel subclass that will handle vertical alignment for you when setting its alignment property. This will also update the label on orientation changes as well, will constrain the height to the text, and keep the label's width at it's original size.
.h
@interface VAlignLabel : UILabel
@property (nonatomic, assign) WBZVerticalAlignment alignment;
@end
.m
-(void)setAlignment:(WBZVerticalAlignment)alignment{
_alignment = alignment;
CGSize s = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(self.frame.size.width, 9999) lineBreakMode:NSLineBreakByWordWrapping];
switch (_alignment)
{
case wbzLabelAlignmentVerticallyTop:
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, s.height);
break;
case wbzLabelAlignmentVerticallyMiddle:
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + (self.frame.size.height - s.height)/2, self.frame.size.width, s.height);
break;
case wbzLabelAlignmentVerticallyBottom:
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + (self.frame.size.height - s.height), self.frame.size.width, s.height);
break;
default:
break;
}
}
-(void)layoutSubviews{
[self setAlignment:self.alignment];
}
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
This worked for me, first cd in the directory that you would like to change the filenames to and then run the following command:
Get-ChildItem | rename-item -NewName { "house chores-" + $_.Name }
you can fix the wrapper using absolute positioning. and the give inside div a fixed position.
.wrapper{
position:absolute;
left:10%;// or some valve in px
top:10%; // or some valve in px
}
and div inside that
.wrapper .fixed-element{
position:fixed;
width:100%;
height:100%;
margin-left:auto; // to center this div inside at center give auto margin
margin-right:auto;
}
try this It might work for you
Please check this. It is the complete Ajax request code.
$('#foo').submit(function(event) {
// Get the form data
// There are many ways to get this data using jQuery (you
// can use the class or id also)
var formData = $('#foo').serialize();
var url = 'URL of the request';
// Process the form.
$.ajax({
type : 'POST', // Define the type of HTTP verb we want to use
url : 'url/', // The URL where we want to POST
data : formData, // Our data object
dataType : 'json', // What type of data do we expect back.
beforeSend : function() {
// This will run before sending an Ajax request.
// Do whatever activity you want, like show loaded.
},
success:function(response){
var obj = eval(response);
if(obj)
{
if(obj.error==0){
alert('success');
}
else{
alert('error');
}
}
},
complete : function() {
// This will run after sending an Ajax complete
},
error:function (xhr, ajaxOptions, thrownError){
alert('error occured');
// If any error occurs in request
}
});
// Stop the form from submitting the normal way
// and refreshing the page
event.preventDefault();
});
What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.
Using Crypto++, you could do the following:
#include <sha.h>
#include <iostream>
SHA256 sha;
while ( !f.eof() ) {
char buff[4096];
int numchars = f.read(...);
sha.Update(buff, numchars);
}
char hash[size];
sha.Final(hash);
cout << hash <<endl;
I have a need for something very similar, because I can't read in multi-gigabyte files just to compute a hash. In theory I could memory map them, but I have to support 32bit platforms - that's still problematic for large files.
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
enum is used to assign value to enum elements which cannot be done in struct. So everytime instead of accessing the complete variable we can do it by the value we assign to the variables in enum. By default it starts with 0 assignment but we can assign it any value and the next variable in enum will be assigned a value the previous value +1.
The submit()
function is there to make life easier. You can use it on any element inside of form tags to submit that form.
You can also search for the submit button and use click()
.
So the only difference is click()
has to be done on the submit button and submit()
can be done on any form element.
It's up to you.
http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
Converting from dict to list is made easy in Python. Three examples:
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
The canonical way to do this with Rails 3:
Foo.includes(:bar).where("bars.id IS NOT NULL")
ActiveRecord 4.0 and above adds where.not
so you can do this:
Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })
When working with scopes between tables, I prefer to leverage merge
so that I can use existing scopes more easily.
Foo.includes(:bar).merge(Bar.where.not(id: nil))
Also, since includes
does not always choose a join strategy, you should use references
here as well, otherwise you may end up with invalid SQL.
Foo.includes(:bar)
.references(:bar)
.merge(Bar.where.not(id: nil))
I have improved munsingh's answer above by testing for the registry key in 64-bit and 32-bit registries, if needed:
::- Test for the registry location
SET VALUE=CurrentVersion
SET KEY_1="HKLM\SOFTWARE\JavaSoft\Java Development Kit"
SET KEY_2=HKLM\SOFTWARE\JavaSoft\JDK
SET REG_1=reg.exe
SET REG_2="C:\Windows\sysnative\reg.exe"
SET REG_3="C:\Windows\syswow64\reg.exe"
SET KEY=%KEY_1%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_2% is for 64-bit installations, using "C:\Windows\sysnative"
SET KEY=%KEY_1%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_3% is for 32-bit installations on a 64-bit system, using "C:\Windows\syswow64"
SET KEY=%KEY_1%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
:_set_value
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JDK_VERSION=%%b
)
SET KEY=%KEY%\%JDK_VERSION%
SET VALUE=JavaHome
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JAVAHOME=%%b
)
ECHO "%JAVAHOME%"
::- SETX JAVA_HOME "%JAVAHOME%"
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
Laravel Eloquent provides destroy()
function in which returns boolean
value. So if a record exists on the database and deleted you'll get true
otherwise false
.
Here's an example using Laravel Tinker shell.
In this case, your code should look like this:
public function destroy($id)
{
$res = User::destroy($id);
if ($res) {
return response()->json([
'status' => '1',
'msg' => 'success'
]);
} else {
return response()->json([
'status' => '0',
'msg' => 'fail'
]);
}
}
More info about Laravel Eloquent Deleting Models
1)In your client side you can send you http.post request in string like below
var IndexInfo = JSON.stringify(this.scope.IndexTree);
this.$http.post('../../../api/EvaluationProcess/InsertEvaluationProcessInputType', "'" + IndexInfo + "'" ).then((response: any) => {}
2)Then in your web api controller you can deserialize it
public ApiResponce InsertEvaluationProcessInputType([FromBody]string IndexInfo)
{
var des = (ApiReceivedListOfObjects<TempDistributedIndex>)Newtonsoft.Json.JsonConvert.DeserializeObject(DecryptedProcessInfo, typeof(ApiReceivedListOfObjects<TempDistributedIndex>));}
3)Your ApiReceivedListOfObjects class should be like below
public class ApiReceivedListOfObjects<T>
{
public List<T> element { get; set; }
}
4)make sure that your serialized string (IndexInfo here) becomes like below structure before JsonConvert.DeserializeObject command in step 2
var resp = @"
{
""element"": [
{
""A"": ""A Jones"",
""B"": ""500015763""
},
{
""A"": ""B Smith"",
""B"": ""504986213""
},
{
""A"": ""C Brown"",
""B"": ""509034361""
}
]
}";
From the SQL Server Management Studio you can right click on your database and select:
Tasks -> Generate Scripts
Then simply proceed through the wizard. Make sure to set 'Script Data' to TRUE when prompted to choose the script options.
Further reading:
sed
doesn't recognize \d
, use [[:digit:]]
instead. You will also need to escape the +
or use the -r
switch (-E
on OS X).
Note that [0-9]
works as well for Arabic-Hindu numerals.
With HTML5 specification... It is now possible to put a block-level element inside of an inline element. So now it's perfectly appropriate to put a 'div' or 'h1' inside of an 'a' element.
As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.
<a href="http://example.com/" target="_blank">Hello, world!</a>
Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create _blank
links, then they probably still can.
If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.
$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');
if you have done it that way variable string
now holds "123456"
you can also (i guess the better way) do this...
$mylabel.text("-123456");
$mylabel.text(function(i,v){
return v.replace('-','');
});
If you're just interested in the properties and data types from the database, you can use Model.inspect
.
irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
reset_password_token: string, reset_password_sent_at: datetime,
remember_created_at: datetime, sign_in_count: integer,
current_sign_in_at: datetime, last_sign_in_at: datetime,
current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
updated_at: datetime)"
Alternatively, having run rake db:create
and rake db:migrate
for your development environment, the file db/schema.rb
will contain the authoritative source for your database structure:
ActiveRecord::Schema.define(version: 20130712162401) do
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
end
I finally solved it:
In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"
Then at the DataGridView link the ContextMenuStrip
Using the code below helped me getting it work.
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);
Here is the cool part
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hti = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.ClearSelection();
MyDataGridView.Rows[hti.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
You have an error in you script tag construction, this:
<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
Should look like this:
<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.
UPDATE
But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
As a Python lover and Android programmer, I'm sad to say this is not a good way to go. There are two problems:
One problem is that there is a lot more than just a programming language to the Android development tools. A lot of the Android graphics involve XML files to configure the display, similar to HTML. The built-in java objects are integrated with this XML layout, and it's a lot easier than writing your code to go from logic to bitmap.
The other problem is that the G1 (and probably other Android devices for the near future) are not that fast. 200 MHz processors and RAM is very limited. Even in Java, you have to do a decent amount of rewriting-to-avoid-more-object-creation if you want to make your app perfectly smooth. Python is going to be too slow for a while still on mobile devices.
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
#include <stdio.h>
#include<stdarg.h>
int fun(int a, ...);
int main(int argc, char *argv[]){
fun(1,10);
fun(2,"cquestionbank");
return 0;
}
int fun(int a, ...){
va_list vl;
va_start(vl,a);
if(a==1)
printf("%d",va_arg(vl,int));
else
printf("\n%s",va_arg(vl,char *));
}
git clone URL ---> Complete project or repository will be downloaded as a seperate directory. and not just the changes git pull URL ---> fetch + merge --> It will only fetch the changes that have been done and not the entire project
Specifically, if you are dealing with a UserForm, then you might try the Repaint method. You might encounter an issue with DoEvents if you are using event triggers in your form. For instance, any keys pressed while a function is running will be sent by DoEvents The keyboard input will be processed before the screen is updated, so if you are changing cells on a spreadsheet by holding down one of the arrow keys on the keyboard, then the cell change event will keep firing before the main function finishes.
A UserForm will not be refreshed in some cases, because DoEvents will fire the events; however, Repaint will update the UserForm and the user will see the changes on the screen even when another event immediately follows the previous event.
In the UserForm code it is as simple as:
Me.Repaint
How about calling a function from within your callback instead of returning a value in sync_call()?
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {
value = result;
use_value(value);
} );
}
this worked for me on Ubuntu 20.04 with mysql 8, the weird hashing thing is because the native PASSWORD() function was removed in mysql 8 (or earlier?)
UPDATE mysql.user SET
plugin = 'mysql_native_password',
Host = '%',
authentication_string = CONCAT('*', UPPER(SHA1(UNHEX(SHA1('insert password here')))))
WHERE User = 'root';
FLUSH PRIVILEGES;
When you create a database in Microsoft SQL Server you can have multiple file groups, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.
See MSDN for the full syntax.
Simple just run the following command.
sudo dnf install *package.rpm
Enter your password and you are done.
To exclude folder from .gitignore, the following can be done.
!app/
app/*
!app/bower_components/
app/bower_components/*
!app/bower_components/highcharts/
This will ignore all files/subfolders inside bower_components
except for /highcharts
.
A simple string.Concat() is what you need.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = string.Concat(test);
If you also need to add a seperator (space, comma etc) then, string.Join() should be used.
string[] test = new string[2];
test[0] = "Red";
test[1] = "Blue";
string result = string.Join(",", test);
If you have to perform this on a string array with hundereds of elements than string.Join() is better by performace point of view. Just give a "" (blank) argument as seperator. StringBuilder can also be used for sake of performance, but it will make code a bit longer.
Without boost :
define same macro again and compiler HIMSELF will give warning.
From warning you can see location of the previous definition.
vi file of previous definition .
ambarish@axiom:~/cpp$ g++ shiftOper.cpp
shiftOper.cpp:7:1: warning: "LINUX_VERSION_CODE" redefined
shiftOper.cpp:6:1: warning: this is the location of the previous definition
#define LINUX_VERSION_CODE 265216
#define LINUX_VERSION_CODE 666
int main ()
{
}
To handle the DatGridView
s CheckedChanged
event you must first get the CellContentClick
to fire (which does not have the CheckBox
es current state!) then call CommitEdit
. This will in turn fire the CellValueChanged
event which you can use to do your work. This is an oversight by Microsoft. Do some thing like the following...
private void dataGridViewSites_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
dataGridViewSites.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
/// <summary>
/// Works with the above.
/// </summary>
private void dataGridViewSites_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
UpdateDataGridViewSite();
}
I hope this helps.
P.S. Check this article https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcelldirtystatechanged(v=vs.110).aspx
Params contains the following three groups of parameters:
match '/user/:id'
in routes.rb will set params[:id]params[:controller]
and params[:action]
is always available and contains the current controller and actionIn general, because on a relational database, the performance of code using cursors is an order of magnitude worse than set-based operations.
Just for the record, I was running into the exact same problem and none of the answers worked.
I used a headers checker tool: http://www.webconfs.com/http-header-check.php
I was testing with my IP (http://192.0.2.1/upload
) and what came back was the following:
HTTP/1.1 301 Moved Permanently =>
Date => Sat, 10 Jan 2015 04:03:35 GMT
Server => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
Location => http://192.0.2.1/upload/
Content-Length => 380
Connection => close
Content-Type => text/html; charset=iso-8859-1
There was a redirection happening and the AJAX request does not honor/follow redirects.
It turned out to be the missing slash at the end of the domain (http://192.0.2.1/upload/)
I tested again with slash at the end and I got this below. Added a slash in the script too, and it was now working.
HTTP/1.1 200 OK =>
Date => Sat, 10 Jan 2015 04:03:53 GMT
Server => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By => PHP/5.3.8
Access-Control-Allow-Origin => *
Access-Control-Allow-Methods => PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Headers => *
Content-Length => 1435
Connection => close
Content-Type => text/html
Use this tool to test if your headers are good and to troubleshoot what is happening.
Using a ternary is simple, readable, and clean:
Pre PHP 7
Assign a variable to the value of another variable if it's set, else assign null
(or whatever default value you need):
$newVariable = isset($thePotentialData) ? $thePotentialData : null;
PHP 7+
The same except using Null Coalescing Operator. There's no longer a need to call isset()
as this is built in, and no need to provide the variable to return as it's assumed to return the value of the variable being checked:
$newVariable = $thePotentialData ?? null;
Both will stop the Notices from the OP question, and both are the exact equivalent of:
if (isset($thePotentialData)) {
$newVariable = $thePotentialData;
} else {
$newVariable = null;
}
If you don't require setting a new variable then you can directly use the ternary's returned value, such as with echo
, function arguments, etc:
Echo:
echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';
Function:
$foreName = getForeName(isset($userId) ? $userId : null);
function getForeName($userId)
{
if ($userId === null) {
// Etc
}
}
The above will work just the same with arrays, including sessions etc, replacing the variable being checked with e.g.:
$_SESSION['checkMe']
or however many levels deep you need, e.g.:
$clients['personal']['address']['postcode']
Suppression:
It is possible to suppress the PHP Notices with @
or reduce your error reporting level, but it does not fix the problem, it simply stops it being reported in the error log. This means that your code still tried to use a variable that was not set, which may or may not mean something doesn't work as intended - depending on how crucial the missing value is.
You should really be checking for this issue and handling it appropriately, either serving a different message, or even just returning a null value for everything else to identify the precise state.
If you just care about the Notice not being in the error log, then as an option you could simply ignore the error log.
For others like me:
There was once an example in the SSL source in the directory demos/ssl/
with example code in C++. Now it's available only via the history:
https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl
You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.
Certificates: .pem in demos/certs/apps/
: https://github.com/openssl/openssl/tree/master/demos/certs/apps
What's the difference between an RDD's map and mapPartitions method?
The method map converts each element of the source RDD into a single element of the result RDD by applying a function. mapPartitions converts each partition of the source RDD into multiple elements of the result (possibly none).
And does flatMap behave like map or like mapPartitions?
Neither, flatMap works on a single element (as map
) and produces multiple elements of the result (as mapPartitions
).
The cleanest solution is probably to specify your divs as exact children.
Try changing this:
div.rounded div div {
background: url('bl.gif') no-repeat bottom left;
}
To this:
div.rounded > div > div {
background: url('bl.gif') no-repeat bottom left;
}
FYI this kind of code works (you can find it ugly, it is your right :) ) :
def list = null
list.each { println it }
soSomething()
In other words, this code has null/empty checks both useless:
if (members && !members.empty) {
members.each { doAnotherThing it }
}
def doAnotherThing(def member) {
// Some work
}
Use Brew is always good way to install ANT and other needs. To install type below command on terminal.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
after Brew installation , type
brew install ant
This will install Ant on your system. Also you will not need to worry about setting up the path.
Also i have documented on the same - How to Install ANT on Mac OS?
you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...
see Singleton in PHP
Nodejs is a scripting language (like Python or Ruby, and unlike PHP or C++). To run your code, you need to enter a command in the terminal / shell / command prompt. Look for an application shortcut in your operating system by one of those names.
The command to run in the terminal will be
node server.js
But you will first need to browse in the terminal to the same folder as the file server.js
. The syntax for using the terminal varies by operating system, look for its documentation.
Here is another option using sql servers count distinct:
DECLARE @T TABLE( [contract] INT, project INT, activity INT )
INSERT INTO @T VALUES( 1000, 8000, 10 )
INSERT INTO @T VALUES( 1000, 8000, 20 )
INSERT INTO @T VALUES( 1000, 8001, 10 )
INSERT INTO @T VALUES( 2000, 9000, 49 )
INSERT INTO @T VALUES( 2000, 9001, 49 )
INSERT INTO @T VALUES( 3000, 9000, 79 )
INSERT INTO @T VALUES( 3000, 9000, 78 )
SELECT DISTINCT [contract], activity FROM @T AS A WHERE
(SELECT COUNT( DISTINCT activity )
FROM @T AS B WHERE B.[contract] = A.[contract]) = 1
I just recently started learning XML. The underscore version helps me separate everything XML-related (DOM, XSD, etc.) from programming languages like Java, JavaScript (camel case). And I agree with you that using identifiers which are allowed in programming languages looks better.
Edit: Might be unrelated, but here is a link for rules and recommendations on naming XML elements which I follow when naming ids (sections "XML Naming Rules" and "Best Naming Practices").
White background is caused because of the Android starts while the app loads on memory, and it can be avoided if you just add this 2 line of code under SplashTheme.
<item name="android:windowDisablePreview">true</item>
<item name="android:windowIsTranslucent">true</item>
org.apache.commons.io.FileUtils.touch(yourFile)
doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.
I used IOException and it works just fine:
try
{
String filePath = "C:\sheet.xlsx";
FileWriter fw = new FileWriter(filePath );
}
catch (IOException e)
{
System.out.println("File is open");
}
One option is you can wrap it into another array:
Foo(new object[]{ new object[]{ (object)"1", (object)"2" } });
Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:
Foo((object) new object[]{ (object)"1", (object)"2" });
Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:
void Foo(object[] item)
{
// Somehow don't duplicate Foo(object[]) and
// Foo(params object[]) without making an infinite
// recursive call... maybe something like
// FooImpl(params object[] items) and then this
// could invoke it via:
// FooImpl(new object[] { item });
}
Paste this code to your pom.xml file. It works for me.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
Hooking .remove()
is not the best way to handle this as there are many ways to remove elements from the page (e.g. by using .html()
, .replace()
, etc).
In order to prevent various memory leak hazards, internally jQuery will try to call the function jQuery.cleanData()
for each removed element regardless of the method used to remove it.
See this answer for more details: javascript memory leaks
So, for best results, you should hook the cleanData
function, which is exactly what the jquery.event.destroyed plugin does:
http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js
Two things are very simple to understand,
Note: All Web Service is API's but not all API' is web services
If there is not ISNULL()
method, you can use this expression instead:
CASE WHEN fieldname IS NULL THEN 0 ELSE fieldname END
This works the same as ISNULL(fieldname, 0)
.
It is important to be specific about what exception you're trying to catch when using a try/except block.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.
For the following HTML document:
<html>
<body>
<a href="http://www.example.com">Example</a>
<a href="http://www.stackoverflow.com">SO</a>
</body>
</html>
The xpath query /html/body//a/@href
(or simply //a/@href
) will return:
http://www.example.com http://www.stackoverflow.com
To select a specific instance use /html/body//a[N]/@href
,
$ /html/body//a[2]/@href http://www.stackoverflow.com
To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:
$ /html/body//a[contains(@href,'example')]/@href http://www.example.com
Mixing the two:
$ /html/body//a[contains(@href,'com')][2]/@href http://www.stackoverflow.com
While size(A,2)
is correct, I find it's much more readable to first define
rows = @(x) size(x,1);
cols = @(x) size(x,2);
and then use, for example, like this:
howManyColumns_in_A = cols(A)
howManyRows_in_A = rows(A)
It might appear as a small saving, but size(.., 1)
and size(.., 2)
must be some of the most commonly used functions, and they are not optimally readable as-is.