.show() and .hide() modify the css display rule. I think you want:
$(selector).css('visibility', 'hidden'); // Hide element
$(selector).css('visibility', 'visible'); // Show element
This is what I use, which does not need you to hardcore your resource names and will look for the drawable resources first in your apps resources and then in the stock android resources if nothing was found - allowing you to use default icons and such.
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id;
id = getResources().getIdentifier(source, "drawable", getPackageName());
if (id == 0) {
// the drawable resource wasn't found in our package, maybe it is a stock android drawable?
id = getResources().getIdentifier(source, "drawable", "android");
}
if (id == 0) {
// prevent a crash if the resource still can't be found
return null;
}
else {
Drawable d = getResources().getDrawable(id);
d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
return d;
}
}
}
Which can be used as such (example):
String myHtml = "This will display an image to the right <img src='ic_menu_more' />";
myTextview.setText(Html.fromHtml(myHtml, new ImageGetter(), null);
can gridmove be of any assistance?
very handy tool on larger screens...
That work fine in Ajax call back to update select from JSON object
function UpdateList() {
var lsUrl = '@Url.Action("Action", "Controller")';
$.get(lsUrl, function (opdata) {
$.each(opdata, function (key, value) {
$('#myselect').append('<option value=' + key + '>' + value + '</option>');
});
});
}
I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.
In .net, every instance of Object, or any type derived therefrom, includes a data structure which contains information about its type. "Real" value types in .net do not contain any such information. To allow data in value types to be manipulated by routines that expect to receive types derived from object, the system automatically defines for each value type a corresponding class type with the same members and fields. Boxing creates a new instances of this class type, copying the fields from a value type instance. Unboxing copies the fields from an instance of the class type to an instance of the value type. All of the class types which are created from value types are derived from the ironically named class ValueType (which, despite its name, is actually a reference type).
It far easier to use the scripting runtime which is installed by default on Windows
Just go project Reference and check Microsoft Scripting Runtime and click OK.
Then you can use this code which is way better than the default file commands
Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
TempS = TS.ReadLine
Final = Final & TempS & vbCrLf
Loop
TS.Close
Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing
As for what is wrong with your original code here you are reading each line of the text file.
Input #iFileNo, sFileText
Then here you write it out
Write #iFileNo, sFileText
sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.
So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.
Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo
iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo
Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).
If you need to process the incoming data then you need to do something like this.
Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
C.Add sFileText
Loop
Close #iFileNo
For Each vTemp in C
Process vTemp
Next sTemp
iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo
I felt the below approach is very easy.
I have declared an interface for callback
public interface AsyncResponse {
void processFinish(Object output);
}
Then created asynchronous Task for responding all type of parallel requests
public class MyAsyncTask extends AsyncTask<Object, Object, Object> {
public AsyncResponse delegate = null;//Call back interface
public MyAsyncTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
@Override
protected Object doInBackground(Object... params) {
//My Background tasks are written here
return {resutl Object}
}
@Override
protected void onPostExecute(Object result) {
delegate.processFinish(result);
}
}
Then Called the asynchronous task when clicking a button in activity Class.
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
Button mbtnPress = (Button) findViewById(R.id.btnPress);
mbtnPress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
@Override
public void processFinish(Object output) {
Log.d("Response From Asynchronous task:", (String) output);
mbtnPress.setText((String) output);
}
});
asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });
}
});
}
}
Thanks
I found this problem while trying to install a new clang compiler. Turns out that both the Debian and the LLVM maintainers agree that the alternatives system should be used for alternatives, NOT for versioning.
The solution they propose is something like this:
PATH=/usr/lib/llvm-3.7/bin:$PATH
where /usr/lib/llvm-3.7/bin is a directory that got created by the llvm-3.7 package, and which contains all the tools with their non-suffixed names. With that, llvm-config (version 3.7) appears with its plain name in your PATH. No need to muck around with symlinks, nor to call the llvm-config-3.7 that got installed in /usr/bin.
Also, check for a package named llvm-defaults (or gcc-defaults), which might offer other way to do this (I didn't use it).
For Python 3
Remove the rb
argument and use either r
or don't pass argument (default read mode
).
with open( <path-to-file>, 'r' ) as theFile:
reader = csv.DictReader(theFile)
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
print(line)
For Python 2
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.
I see all the answers are correct. I just want to write a little different piece of code. In my opinion, you may do it without using an extra variable to save the result of the dialogBox. Take a look:
Select Case MsgBox("Your Message", MsgBoxStyle.YesNoCancel, "caption")
Case MsgBoxResult.Yes
MessageBox.Show("Yes button")
Case MsgBoxResult.Cancel
MessageBox.Show("Cancel button")
Case MsgBoxResult.No
MessageBox.Show("NO button")
End Select
switch (MessageBox.Show("Message", "caption", MessageBoxButtons.YesNoCancel))
{
case DialogResult.Yes: MessageBox.Show("Yes"); break;
case DialogResult.No: MessageBox.Show("No"); break;
case DialogResult.Cancel: MessageBox.Show("Cancel"); break;
}
Add Web Reference is the old-style, deprecated ASP.NET webservices (ASMX) technology (using only the XmlSerializer for your stuff) - if you do this, you get an ASMX client for an ASMX web service. You can do this in just about any project (Web App, Web Site, Console App, Winforms - you name it).
Add Service Reference is the new way of doing it, adding a WCF service reference, which gives you a much more advanced, much more flexible service model than just plain old ASMX stuff.
Since you're not ready to move to WCF, you can also still add the old-style web reference, if you really must: when you do a "Add Service Reference", on the dialog that comes up, click on the [Advanced] button in the button left corner:
and on the next dialog that comes up, pick the [Add Web Reference] button at the bottom.
This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.
In the top section you'll quickly spot the defines used to name these flags:
#define CONDFLAG_NONE 1<<0
#define CONDFLAG_NOCASE 1<<1
#define CONDFLAG_NOTMATCH 1<<2
#define CONDFLAG_ORNEXT 1<<3
#define CONDFLAG_NOVARY 1<<4
and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:
else if ( strcasecmp(key, "ornext") == 0
|| strcasecmp(key, "OR") == 0 ) {
cfg->flags |= CONDFLAG_ORNEXT;
}
The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):
# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
rewritecond_entry *c = &conds[i];
# execute the current Condition, see if it matches
rc = apply_rewrite_cond(c, ctx);
# does this Condition have an 'OR' flag?
if (c->flags & CONDFLAG_ORNEXT) {
if (!rc) {
/* One condition is false, but another can be still true. */
continue;
}
else {
/* skip the rest of the chained OR conditions */
while ( i < rewriteconds->nelts
&& c->flags & CONDFLAG_ORNEXT) {
c = &conds[++i];
}
}
}
else if (!rc) {
return 0;
}
}
You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) )
. If you would, for example, have these Conditions:
RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D
it would be interpreted as if ( (A OR B OR C) and D )
.
As many answers in this thread already suggest it is not possible to send a mail from a static HTML page without using PHP or JS. I just wanted to add that there a some great solutions which will take your HTTP Post request generated by your form and create a mail from it. Those solutions are especially useful in case you do not want to add JS or PHP to your website.
Those servers basically can be configured with a mail-server which is responsible for then sending the email. The receiver, subject, body etc. is received by the server from your HTTP(S) post and then stuffed into the mail you want to send. So technically speaking it is still not possible to send mails from your HTML form but the outcome is the same.
Some of these solutions can be bought as SaaS solution or you can host them by yourself. I'll just name a few but I'm sure there are plenty in case anyone is interested in the technology or the service itself.
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
Try with Shadow( Like border ) + Border
border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;
If you are tired of typing your password, create a (chmod 600) file ~/.my.cnf
, and put in it:
[client]
user = "you"
password = "your-password"
For the sake of conversation:
echo 'DROP DATABASE foo;' | mysql
one great visual tool to validate and generate XSD from XML is IntelliJ IDEA, intuitive and simple.
The solution provided by @user152949, as it was noted in commentaries, skips the first process and doesn't break when "exists" is set to true. Let me provide a fixed version:
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
bool IsProcessRunning(const TCHAR* const executableName) {
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (!Process32First(snapshot, &entry)) {
CloseHandle(snapshot);
return false;
}
do {
if (!_tcsicmp(entry.szExeFile, executableName)) {
CloseHandle(snapshot);
return true;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
return false;
}
This is simple ES-6 style answer. For capturing an "enter" key press and executing some function
<input
onPressEnter={e => (e.keyCode === 13) && someFunc()}
/>
How about instead of using an if inside the event, you unbind the event when the select class is applied? I'm guessing you add the class inside your code somewhere, so unbinding the event there would look like this:
$(element).addClass( 'selected' ).unbind( 'hover' );
The only downside is that if you ever remove the selected class from the element, you have to subscribe it to the hover event again.
Other than foreground/background term. Another way to hide running window is via vbscript, if is is still available in your system.
DIM objShell
set objShell=wscript.createObject("wscript.shell")
iReturn=objShell.Run("yourcommand.exe", 0, TRUE)
name it as sth.vbs and call it from bat, put in sheduled task, etc. PersonallyI'll disable vbs with no haste at any Windows system I manage :)
$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);
EDIT::Finally got around to removing the E_STRICT issue
Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:
java -Djava.library.path="dlls" ...
(assuming Jacob.dll is in the "dlls" folder)
Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
Call the marker.setIcon('newImage.png')
... Look here for the docs.
Are you asking about the actual way to do it? You could just create each div
, and a add a mouseover
and mouseout
listener that would change the icon and back for the markers.
I am using Spring Boot version 2.1.2 and the errorAttributes.getErrorAttributes()
signature didn't work for me (in acohen's response). I wanted a JSON type response so I did a little digging and found this method did exactly what I needed.
I got most of my information from this thread as well as this blog post.
First, I created a CustomErrorController
that Spring will look for to map any errors to.
package com.example.error;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@RestController
public class CustomErrorController implements ErrorController {
private static final String PATH = "error";
@Value("${debug}")
private boolean debug;
@Autowired
private ErrorAttributes errorAttributes;
@RequestMapping(PATH)
@ResponseBody
public CustomHttpErrorResponse error(WebRequest request, HttpServletResponse response) {
return new CustomHttpErrorResponse(response.getStatus(), getErrorAttributes(request));
}
public void setErrorAttributes(ErrorAttributes errorAttributes) {
this.errorAttributes = errorAttributes;
}
@Override
public String getErrorPath() {
return PATH;
}
private Map<String, Object> getErrorAttributes(WebRequest request) {
Map<String, Object> map = new HashMap<>();
map.putAll(this.errorAttributes.getErrorAttributes(request, this.debug));
return map;
}
}
Second, I created a CustomHttpErrorResponse
class to return the error as JSON.
package com.example.error;
import java.util.Map;
public class CustomHttpErrorResponse {
private Integer status;
private String path;
private String errorMessage;
private String timeStamp;
private String trace;
public CustomHttpErrorResponse(int status, Map<String, Object> errorAttributes) {
this.setStatus(status);
this.setPath((String) errorAttributes.get("path"));
this.setErrorMessage((String) errorAttributes.get("message"));
this.setTimeStamp(errorAttributes.get("timestamp").toString());
this.setTrace((String) errorAttributes.get("trace"));
}
// getters and setters
}
Finally, I had to turn off the Whitelabel in the application.properties
file.
server.error.whitelabel.enabled=false
This should even work for xml
requests/responses. But I haven't tested that. It did exactly what I was looking for since I was creating a RESTful API and only wanted to return JSON.
create a virtual environment, install then switch to python 3.6.5
$ conda create -n tensorflow python=3.7
$ conda activate tensorflow
$ conda install python=3.6.5
$ pip install tensorflow
activate the environment when you would want to use tensorflow
The solution to "Cannot Get /" can usually be determined if you do an "ng build" in the command line. You will find most often that one of your "imports" does not have the correct path.
You could do this:
if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
// it was an input
}
or this, which is slower, but shorter and cleaner:
if( ctrl.is('input') ) {
// it was an input
}
If you want to be more specific, you can test the type:
if( ctrl.is('input:text') ) {
// it was an input
}
In a single line, I suggest:
String input = "test string (67)";
input = input.subString(input.indexOf("(")+1, input.lastIndexOf(")"));
System.out.println(input);`
You are using ASIHTTPRequest so you need to setup your project. Read the second part here
Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:
Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable
Due to a class with an attribute IEnumerable<int>
eg:
[Serializable]
class MySessionData{
public int ID;
public IEnumerable<int> RelatedIDs; //This can be an issue
}
Originally the problem instance of MySessionData
was set from a non-serializable list:
MySessionData instance = new MySessionData(){
ID = 123,
RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};
The cause here is the concrete class that the Select<int>(...)
returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int>
to resolve it.
RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();
You can open emacs (in terminal mode, using emacs -nw
for instance), and then use Hexl mode: M-x hexl-mode
.
https://www.gnu.org/software/emacs/manual/html_node/emacs/Editing-Binary-Files.html
The easiest way to understand the difference is to think of the different possibilities. There are two objects to consider, the pointer and the object pointed to (in this case 'a' is the name of the pointer, the object pointed to is unnamed, of type char). The possibilities are:
These different possibilities can be expressed in C as follows:
I hope this illustrates the possible differences
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
I have achieved this in the past by running the "original" code in the "child" and the "spawned" code in the "parent" (that is: you reverse the usual sense of the test after fork()
). Then trap SIGCHLD in the "spawned" code...
May not be possible in your case, but cute when it works.
Note This is an improvement in @user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of @user3516549 but in some cases it was not working properly.
I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as
content://com.android.providers.media.documents/document/image%3A52530
while if user select gallery from sliding drawer instead of recent then we will get uri as
content://media/external/images/media/52530
So I have handle it in getRealPathFromURI_API19()
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
return getRealPathFromURI_BelowAPI11(context,uri)
}
}
EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question
EDIT2 Here is complete code with handling virtual files and host other than com.android.providers
I have tested this method with content://com.adobe.scan.android.documents/document/
Maybe you should better use a case
for such lists:
case "$cms" in
wordpress|meganto|typo3)
do_your_else_case
;;
*)
do_your_then_case
;;
esac
I think for long such lists this is better readable.
If you still prefer the if
you can do it with single brackets in two ways:
if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then
or
if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then
It Work for me !
private: System::Void MyButton_Delete_Click(System::Object^ sender, System::EventArgs^ e) {
// ??????? ???????(Row).
MydataGridView->Rows->RemoveAt(MydataGridView->CurrentCell->RowIndex);
}
Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)
eg -
~/myproject/mygitrepo/app/$ git diff app/TestFile.txt
should have been
~/myproject/mygitrepo/app/$ git diff TestFile.txt
As mentioned in Gillian's answer, assigning none
to content
solves the problem:
p::after {
content: none;
}
Note that in CSS3, W3C recommended to use two colons (::
) for pseudo-elements like ::before
or ::after
.
From the MDN web doc on Pseudo-elements:
Note: As a rule, double colons (
::
) should be used instead of a single colon (:
). This distinguishes pseudo-classes from pseudo-elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the sake of compatibility. Note that::selection
must always start with double colons (::
).
In simple term 2's Complement
is a way to store negative number in Computer Memory. Whereas Positive Numbers are stored as Normal Binary Number.
Let's consider this example,
Computer uses Binary Number System
to represent any number.
x = 5;
This is represented as 0101
.
x = -5;
When the computer encouters -
sign, it computes it's 2's complement and stores it.
i.e
5 = 0101 and it's 2's complement is 1011
.
Important rules computer uses to process numbers are,
1
then it must be negative
number.0
then it is a positive number
because there is no -0
in number system.(1000 is not -0
instead it is positive 8
)0
then it is 0
.positive number
.The exec function executes a system command and never returns-- use system instead of exec if you want it to return
Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.
In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.
A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.
In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.
Example:
use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;
Finally, IPC::Run from the CPAN is also worth looking at…
Use the following
1.) Choose the image you want to set in your title bar.
2.) Convert it to ".ico" format. (You can use the following link online)
http://image.online-convert.com/convert-to-ico
3.) Save the file as "favicon.ico" in the same folder as your .html file
4.) Add this inside your head tag <link rel="shortcut icon" href="favicon.ico"/>
In the case of HashMap
, it replaces the old value with the new one.
In the case of HashSet
, the item isn't inserted.
use checked
: true, false property of the checkbox.
jQuery:
if($('input[type=checkbox]').is(':checked')) {
$(this).prop('checked',true);
} else {
$(this).prop('checked',false);
}
You can use charAt() function to find out spaces in string.
public class Test {
public static void main(String args[]) {
String fav="Hi Testing 12 3";
int counter=0;
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
System.out.println("Number of spaces "+ counter);
//This will print Number of spaces 4
}
}
Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem
Also yes always add whitespace like @Peter O suggested.
Here is a two steps solution here is a hack to IE10 and 11
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
/* IE10+ specific styles go here */
}
because IE10 and IE11 Supports -ms-high-cotrast you can take the advantage of this to target this two browsers
and if you want to exclude the IE10 from this you must create a IE10 specific code as follow it's using the user agent trick you must add this Javascript
var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);
and this HTML tag
<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">
and now you can write your CSS code like this
html[data-useragent*='MSIE 10.0'] h1 {
color: blue;
}
for more information please refer to this websites,wil tutorail, Chris Tutorial
And if you want to target IE11 and later,here is what I've found:
_:-ms-fullscreen, :root .selector {}
Here is a great resource for getting more information: browserhacks.com
Presuming 17px header height
List css:
height: 100%;
padding-top: 17px;
Header css:
height: 17px;
float: left;
width: 100%;
Another option is to use the defer attribute on the script, but it's only appropriate for external scripts with a src attribute:
<script src = "exampleJsFile.js" defer> </script>
While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data
. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
when you want to brightness or darker of background-color, you can use this css code
.brighter-span {
filter: brightness(150%);
}
.darker-span {
filter: brightness(50%);
}
The easiest way that I use is this command on terminal:
docker logs elk > /home/Desktop/output.log
structure is:
docker logs <Container Name> > path/filename.log
From the docs (note: MSDN is a handy resource when you want to know what things do!):
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
Sends the CommandText to the Connection and builds a SqlDataReader.
... and from SqlDataReader ...
Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class
public class Book {
public string Title {get; set;}
public string Author {get; set;}
}
you can read the XML file line by line with a small memory footprint, like this:
public static class XmlHelper {
public static IEnumerable<Book> StreamBooks(string uri) {
using (XmlReader reader = XmlReader.Create(uri)) {
string title = null;
string author = null;
reader.MoveToContent();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Book") {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Title") {
title = reader.ReadString();
break;
}
}
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Author") {
author =reader.ReadString();
break;
}
}
yield return new Book() {Title = title, Author = author};
}
}
}
}
Example of usage:
string uri = @"c:\test.xml"; // your big XML file
foreach (var book in XmlHelper.StreamBooks(uri)) {
Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);
}
This will work if you do not have too many expressions.
Example: ng-show="form.type === 'Limited Company' || form.type === 'Limited Partnership'"
For any more expressions than this use a controller.
Mine is similar to your solution but I got it to work. Only difference is my model. I have the following models in my html input:
ng-model="new.Participant.email"
ng-model="new.Participant.confirmEmail"
and in my controller, I have this in $scope:
$scope.new = {
Participant: {}
};
and this validation line worked:
<label class="help-block" ng-show="new.Participant.email !== new.Participant.confirmEmail">Emails must match! </label>
For swift 3 purposes
theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red
I ended up doing this:
public static string ToStringNullSafe(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
public static bool Compare<T>(T a, T b)
{
int count = a.GetType().GetProperties().Count();
string aa, bb;
for (int i = 0; i < count; i++)
{
aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
if (aa != bb)
{
return false;
}
}
return true;
}
Usage:
if (Compare<ObjectType>(a, b))
Update
If you want to ignore some properties by name:
public static string ToStringNullSafe(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
public static bool Compare<T>(T a, T b, params string[] ignore)
{
int count = a.GetType().GetProperties().Count();
string aa, bb;
for (int i = 0; i < count; i++)
{
aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
if (aa != bb && ignore.Where(x => x == a.GetType().GetProperties()[i].Name).Count() == 0)
{
return false;
}
}
return true;
}
Usage:
if (MyFunction.Compare<ObjType>(a, b, "Id","AnotherProp"))
If you are using MacOS
To check the version
git --version
To Upgrade the version
brew upgrade git
For Eclipse users...
Click Run —> Run configuration —> are —> set Alternate JRE for 1.6 or 1.7
Your issue is that your selector is for an anchor element <a>
. You are treating the <a>
tag as if it represents the page which is not the case.
$('head')
will work as long as this selector is being executed by the page that needs the css.
Why not simply add the css file to the page in question. Any particular reason to attempt this dynamically from another page? I am not even familiar with a way to inject css to remote pages like this ... seems like it would be a major security hole.
ADDENDUM to your reasoning:
Then you should simply pass a parameter to the page, read it using javascript, and then do whatever is needed based on the parameter.
Even icfantv's answer to this question is already perfect, I still have more findings in my test.
As a server socket in listening status, if it only in listening status, and even it accepts request and getting data from the client side, but without any data sending action. We still could restart the server at once after it's stopped. But if any data sending action happens in the server side to the client, the same service(same port) restart will have this error: (Address already in use).
I think this is caused by the TCP/IP design principles. When the server send the data back to client, it must ensure the data sending succeed, in order to do this, the OS(Linux) need monitor the connection even the server application closed this socket. But I still believe kernel socket designer could improve this issue.
You can also use WriteConsole method to print on console.
AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);
Maybe you want str.istitle
>>> help(str.istitle)
Help on method_descriptor:
istitle(...)
S.istitle() -> bool
Return True if S is a titlecased string and there is at least one
character in S, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
>>> "Alpha_beta_Gamma".istitle()
False
>>> "Alpha_Beta_Gamma".istitle()
True
>>> "Alpha_Beta_GAmma".istitle()
False
Try editing your eclipse.ini file and add the following at the top
-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
Of course the path may be slightly different, looks like I have an older version...
I'm not sure if it will add itself automatically. If not go into
Preferences --> Java --> Installed JREs
Click Add and follow the instructions there to add it
Here's a straight forward implementation of the md5sum
command that computes and displays the MD5 of the file specified on the command-line. It needs to be linked against the OpenSSL library (gcc md5.c -o md5 -lssl
) to work. It's pure C, but you should be able to adapt it to your C++ application easily enough.
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
unsigned char result[MD5_DIGEST_LENGTH];
// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md) {
int i;
for(i=0; i <MD5_DIGEST_LENGTH; i++) {
printf("%02x",md[i]);
}
}
// Get the size of the file by its file descriptor
unsigned long get_size_by_fd(int fd) {
struct stat statbuf;
if(fstat(fd, &statbuf) < 0) exit(-1);
return statbuf.st_size;
}
int main(int argc, char *argv[]) {
int file_descript;
unsigned long file_size;
char* file_buffer;
if(argc != 2) {
printf("Must specify the file\n");
exit(-1);
}
printf("using file:\t%s\n", argv[1]);
file_descript = open(argv[1], O_RDONLY);
if(file_descript < 0) exit(-1);
file_size = get_size_by_fd(file_descript);
printf("file size:\t%lu\n", file_size);
file_buffer = mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0);
MD5((unsigned char*) file_buffer, file_size, result);
munmap(file_buffer, file_size);
print_md5_sum(result);
printf(" %s\n", argv[1]);
return 0;
}
In /etc/hosts:
your-ip-address your-host-name
example: 192.168.1.8 master
In /etc/hosts:
Delete the line with 127.0.1.1 (This will cause loopback)
In your core-site, change localhost to your-ip or your-hostname
Now, restart the cluster.
You could try this SendKeys jQuery plugin:
http://bililite.com/blog/2011/01/23/improved-sendkeys/
$(element).sendkeys(string)
inserts string at the insertion point in an input, textarea or other element with contenteditable=true. If the insertion point is not currently in the element, it remembers where the insertion point was when sendkeys was last called (if the insertion point was never in the element, it appends to the end).
You don't even need the float:left;
It seems the default behavior is to render one below the other, if it doesn't happen it's because they are inheriting some style from above.
CSS:
#wrapper{
margin-left:auto;
margin-right:auto;
height:auto;
width:auto;
}
</style>
HTML:
<div id="wrapper">
<div id="inner1">inner1</div>
<div id="inner2">inner2</div>
</div>
Carefully see your quotation, is this correct or incorrect! Sometime double quotation doesn’t work properly, it's depend on your keyboard layout.
You need to set language level, release version and add maven compiler plugin to the pom.xml
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
The only way I could get this to work (on Linux) was to follow this advice:
https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script
import hudson.model.*
// get current thread / Executor and current build
def thr = Thread.currentThread()
def build = thr?.executable
// if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)
println "param ${hardcoded_param} value : ${hardcoded_param_value}"
This is on Jenkins 1.624 running on CentOS 6.7
I'm always forgeting how to use the ?:
ternary operator. This supplemental answer is a quick reminder. It is shorthand for if-then-else
.
myVariable = (testCondition) ? someValue : anotherValue;
where
()
holds the if
?
means then
:
means else
It is the same as
if (testCondition) {
myVariable = someValue;
} else {
myVariable = anotherValue;
}
Please refer below Ajax overview:
enumerate
is what you are looking for.
You might also be interested in unpacking:
# The pattern
x, y, z = [1, 2, 3]
# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
print(x) # prints the numbers 28, 4, 1990
# and also
for index, (x, y) in enumerate(l):
print(x) # prints the numbers 28, 4, 1990
Also, there is itertools.count()
so you could do something like
import itertools
for index, el in zip(itertools.count(), [28, 4, 1990]):
print(el) # prints the numbers 28, 4, 1990
Sharing my notes which I usually maintain while reading from Internet, I hope it may be helpful to someone
Candidate keys are those keys which is candidate for primary key of a table. In simple words we can understand that such type of keys which full fill all the requirements of primary key which is not null and have unique records is a candidate for primary key. So thus type of key is known as candidate key. Every table must have at least one candidate key but at the same time can have several.
Such type of candidate key which is chosen as a primary key for table is known as primary key. Primary keys are used to identify tables. There is only one primary key per table. In SQL Server when we create primary key to any table then a clustered index is automatically created to that column.
Foreign key are those keys which is used to define relationship between two tables. When we want to implement relationship between two tables then we use concept of foreign key. It is also known as referential integrity. We can create more than one foreign key per table. Foreign key is generally a primary key from one table that appears as a field in another where the first table has a relationship to the second. In other words, if we had a table A with a primary key X that linked to a table B where X was a field in B, then X would be a foreign key in B.
If any table have more than one candidate key, then after choosing primary key from those candidate key, rest of candidate keys are known as an alternate key of that table. Like here we can take a very simple example to understand the concept of alternate key. Suppose we have a table named Employee which has two columns EmpID and EmpMail, both have not null attributes and unique value. So both columns are treated as candidate key. Now we make EmpID as a primary key to that table then EmpMail is known as alternate key.
When we create keys on more than one column then that key is known as composite key. Like here we can take an example to understand this feature. I have a table Student which has two columns Sid and SrefNo and we make primary key on these two column. Then this key is known as composite key.
A natural key is one or more existing data attributes that are unique to the business concept. For the Customer table there was two candidate keys, in this case CustomerNumber and SocialSecurityNumber. Link http://www.agiledata.org/essays/keys.html
Introduce a new column, called a surrogate key, which is a key that has no business meaning. An example of which is the AddressID column of the Address table in Figure 1. Addresses don't have an "easy" natural key because you would need to use all of the columns of the Address table to form a key for itself (you might be able to get away with just the combination of Street and ZipCode depending on your problem domain), therefore introducing a surrogate key is a much better option in this case. Link http://www.agiledata.org/essays/keys.html
A unique key is a superkey--that is, in the relational model of database organization, a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set
When more than one column is combined to form a unique key, their combined value is used to access each row and maintain uniqueness. These keys are referred to as aggregate or compound keys. Values are not combined, they are compared using their data types.
Simple key made from only one attribute.
A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a super key can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.
It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.
Assume the date as milliseconds date is 1526813885836
, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
For what you want I would've used
app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
const name = request.params.fruitName
const color = request.params.fruitColor
});
or better yet
app.get('/fruit/:fruit', function(request, response) {
const fruit = request.params.fruit
console.log(fruit)
});
where fruit is a object. So in the client app you just call
https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
and as a response you should see:
// client side response
// { name: My fruit name, color:The color of the fruit}
setting known host is better than setting fingure print value.
When you set known host, try to manually ssh (very first time, before application runs) from the box the application runs.
Short answer in bolds:
collect
is mainly to serialize
(loss of parallelism preserving all other data characteristics of the dataframe)
For example with a PrintWriter pw
you can't do direct df.foreach( r => pw.write(r) )
, must to use collect
before foreach
, df.collect.foreach(etc)
.
PS: the "loss of parallelism" is not a "total loss" because after serialization it can be distributed again to executors.
select
is mainly to select columns, similar to projection in relational algebra
(only similar in framework's context because Spark select
not deduplicate data).
So, it is also a complement of filter
in the framework's context.
Commenting explanations of other answers: I like the Jeff's classification of Spark operations in transformations (as select
) and actions (as collect
). It is also good remember that transforms (including select
) are lazily evaluated.
I found another solution here, since I ran into both post...
This is from the Myles answer:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
This worked for me.
angular.module('testApp',[]).controller('testCTRL',function($scope)_x000D_
_x000D_
{_x000D_
_x000D_
$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";_x000D_
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding."; _x000D_
});
_x000D_
div input{_x000D_
width:600px; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<head>Diff b/w model and bind</head>_x000D_
<body data-ng-app="testApp">_x000D_
<div data-ng-controller="testCTRL">_x000D_
Model-Data : <input type="text" data-ng-model="testingModel">_x000D_
<p>{{testingModel}}</p>_x000D_
<input type="text" data-ng-bind="testingBind">_x000D_
<p ng-bind="testingBind"></p>_x000D_
</div>_x000D_
</body>
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
The Function adds gaussian , salt-pepper , poisson and speckle noise in an image
Parameters
----------
image : ndarray
Input image data. Will be converted to float.
mode : str
One of the following strings, selecting the type of noise to add:
'gauss' Gaussian-distributed additive noise.
'poisson' Poisson-distributed noise generated from the data.
's&p' Replaces random pixels with 0 or 1.
'speckle' Multiplicative noise using out = image + n*image,where
n is uniform noise with specified mean & variance.
import numpy as np
import os
import cv2
def noisy(noise_typ,image):
if noise_typ == "gauss":
row,col,ch= image.shape
mean = 0
var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col,ch))
gauss = gauss.reshape(row,col,ch)
noisy = image + gauss
return noisy
elif noise_typ == "s&p":
row,col,ch = image.shape
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
elif noise_typ == "poisson":
vals = len(np.unique(image))
vals = 2 ** np.ceil(np.log2(vals))
noisy = np.random.poisson(image * vals) / float(vals)
return noisy
elif noise_typ =="speckle":
row,col,ch = image.shape
gauss = np.random.randn(row,col,ch)
gauss = gauss.reshape(row,col,ch)
noisy = image + image * gauss
return noisy
What kind of 'web' module are you talking about? Is it a simple war and has packaging type war?
If you are not using Google's web toolkit (GWT) then you don't need to provide any gwt.extraJvmArgs
Forking the compile process might be not the best idea, because it starts a second process which ignores MAVEN_OPTS
altogether, thus making analysis more difficult.
So I would try to increase the Xmx by setting the MAVEN_OPTS
export MAVEN_OPTS="-Xmx3000m"
And don't fork the compiler to a different process
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
Increasing -XX:MaxPermSize=512m
should not be required because if perm size is the reason of the problem, then I would expect the error java.lang.OutOfMemoryError: PermGen space
If that does not solve your problem, then you can create heap dumps for further analysis by adding -XX:+HeapDumpOnOutOfMemoryError
. Additionally, you can use jconsole.exe in your java bin directory to connect to the jvm while the compilation is running and see what is going on inside the jvm's heap.
Another Idea (may be a stupid one) which came up to me, do you have enough RAM inside your machine? Defining the memory size is nice, but if your host has only 4GB and then you might have the problem that Java is not able to use the defined Memory because it is already used by the OS, Java, MS-Office...
??
is there to provide a value for a nullable type when the value is null. So, if formsAuth is null, it will return new FormsAuthenticationWrapper().
Another solution to get rid of content jump on fixed modal, when removing body scroll is to normalize page width:
body {width: 100vw; overflow-x: hidden;}
Then you can play with fixed position or overflow:hidden for body when the modal is open. But it will hide horizontal scrollbars - usually they're not needed on responsive website.
Try adding the profile
attribute to your head
tag and use "image/x-icon"
for the type
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
If the above code doesn't work, try using the full icon path for the href
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">
A simple way of doing this that I found as a comment by @awardak in Brandon Rude's answer:
new Thread( new Runnable() { @Override public void run() {
// Run whatever background code you want here.
} } ).start();
I'm not sure if, or how , this is better than using AsyncTask.execute
but it seems to work for us. Any comments as to the difference would be appreciated.
Thanks, @awardak!
It's an old post but i'll leave here my javascript solution just in case someone need it.
// you only need this function_x000D_
function sticky( _el ){_x000D_
_el.parentElement.addEventListener("scroll", function(){_x000D_
_el.style.transform = "translateY("+this.scrollTop+"px)";_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
// how to make it work:_x000D_
// get the element you want to be sticky_x000D_
var el = document.querySelector("#blbl > div");_x000D_
// give the element as argument, done._x000D_
sticky(el);
_x000D_
#blbl{_x000D_
position:relative;_x000D_
height:200px; _x000D_
overflow: auto;_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
#blbl > div{_x000D_
position:absolute; _x000D_
padding:50px; _x000D_
top:10px; _x000D_
left:10px; _x000D_
background: #f00_x000D_
}
_x000D_
<div id="blbl" >_x000D_
<div><!-- sticky div --></div> _x000D_
_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
</div>
_x000D_
Notes
I used transform: translateY(@px) because it should be lightweight to compute, high-performance-animations
I only tried this function with modern browsers, it won't work for old browsers where vendors are required (and IE of course)
Use sp_helptext
before the view_name
. Example:
sp_helptext Example_1
Hence you will get the query:
CREATE VIEW dbo.Example_1
AS
SELECT a, b, c
FROM dbo.table_name JOIN blah blah blah
WHERE blah blah blah
sp_helptext will give stored procedures.
The type initializer for 'CSMessageUtility.CSDetails' threw an exception.
means that the static constructor on that class threw an Exception - so you need to look either in the static constructor of the CSDetails class, or in the initialisation of any static members of that class.
90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:
You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/
As mentioned in Jonathan's answer, FETCH_HEAD corresponds to the file .git/FETCH_HEAD
. Typically, the file will look like this:
71f026561ddb57063681109aadd0de5bac26ada9 branch 'some-branch' of <remote URL>
669980e32769626587c5f3c45334fb81e5f44c34 not-for-merge branch 'some-other-branch' of <remote URL>
b858c89278ab1469c71340eef8cf38cc4ef03fed not-for-merge branch 'yet-some-other-branch' of <remote URL>
Note how all branches but one are marked not-for-merge
. The odd one out is the branch that was checked out before the fetch. In summary: FETCH_HEAD essentially corresponds to the remote version of the branch that's currently checked out.
You can call a stored procedure using the following syntax:
$result = mysql_query('CALL getNodeChildren(2)');
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
var number = 10000;
var result = .358 * number;
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
If you want a css only solution you can use active
.crossRotate:active {
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
}
But the transformation will not persist when the activity moves. For that you need javascript (jquery click and css is the cleanest IMO).
$( ".crossRotate" ).click(function() {
if ( $( this ).css( "transform" ) == 'none' ){
$(this).css("transform","rotate(45deg)");
} else {
$(this).css("transform","" );
}
});
I think, to be completely "official", you would need to create a new migration, and put drop_table in self.up. The self.down method should then contain all the code to recreate the table in full. Presumably that code could just be taken from schema.rb at the time you create the migration.
It seems a little odd, to put in code to create a table you know you aren't going to need anymore, but that would keep all the migration code complete and "official", right?
I just did this for a table I needed to drop, but honestly didn't test the "down" and not sure why I would.
This may not be ideal, but try using "Application.OnTime" to pause execution of the remaining code until enough time has elapsed to assure that all refresh processes have finished.
What if the last table in your refresh list were a faux table consisting of only a flag to indicate that the refresh is complete? This table would be deleted at the beginning of the procedure, then, using "Application.OnTime," a Sub would run every 15 seconds or so checking to see if the faux table had been populated. If populated, cease the "Application.OnTime" checker and proceed with the rest of your procedure.
A little wonky, but it should work.
Here is my code for that:
$('#date-daily').datepicker().on('changeDate', function(e) {
//$('#other-input').val(e.format(0,"dd/mm/yyyy"));
//alert(e.date);
//alert(e.format(0,"dd/mm/yyyy"));
//console.log(e.date);
});
Just uncomment the one you prefer. The first option changes the value of other input element. The second one alerts the date with datepicker default format. The third one alerts the date with your own custom format. The last option outputs to log (default format date).
It's your choice to use the e.date , e.dates (for múltiple date input) or e.format(...).
here some more info
file_get_contents()
is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.
fopen()
with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.
You have to include one more jar.
xmlbeans-2.3.0.jar
Add this and try.
Note: It is required for the files with .xlsx formats only, not for just .xls formats.
One thing that to be remembered while solving such problems is that in JSON file, a {
indicates a JSONObject
and a [
indicates JSONArray
. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.
The Gson JsonReader documentation explains how to handle parsing of JsonObjects
and JsonArrays
:
- Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
- Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
Are your Id mappings correct? If the database is responsible for creating the Id through an identifier, you need to map your userobject to that ..
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
If you want to calculate the zscore for all of the columns, you can just use the following:
df_zscore = (df - df.mean())/df.std()
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
var injectObj = {isActive:true, timestamp:new Date()};
// function to inject key values in all object of json array
function injectKeyValueInArray (array, keyValues){
return new Promise((resolve, reject) => {
if (!array.length)
return resolve(array);
array.forEach((object) => {
for (let key in keyValues) {
object[key] = keyValues[key]
}
});
resolve(array);
})
};
//call function to inject json key value in all array object
injectKeyValueInArray(arrOfObj,injectObj).then((newArrOfObj)=>{
console.log(newArrOfObj);
});
Output like this:-
[ { name: 'eve',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'john',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'jane',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z } ]
Try,
# cat test.sh
#!/bin/bash
/bin/touch file.txt
cron as:
* * * * * /bin/sh /home/myUser/scripts/test.sh
And you can confirm this by:
# tailf /var/log/cron
ORDER_BY cast(registration_no as unsigned) ASC
explicitly converts the value to a number. Another possibility to achieve the same would be
ORDER_BY registration_no + 0 ASC
which will force an implicit conversation.
Actually you should check the table definition and change it. You can change the data type to int
like this
ALTER TABLE your_table MODIFY COLUMN registration_no int;
I had a post build command that worked just fine before I did an update on VS 2017. It turned out that the SDK tools updated and were under a new path so it couldn't find the tool I was using to sign my assemblies.
This changed from this....
call "%VS140COMNTOOLS%vsvars32"
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\x64\sn.exe" -Ra "$(TargetPath)" "$(ProjectDir)Key.snk"
To This...
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\sn.exe" -Ra "$(TargetPath)" "$(ProjectDir)Key.snk"
Very subtle but breaking change, so check your paths after an update if you see this error.
You cannot define a free function inside another in C++.
If your file is just text, the best solution is to save each worksheet as .csv and then reimport it into excel - it takes a bit more work, but I reduced a 20MB file to 43KB.
Here is an example for how to extract the href
attrbiutes of all a
tags:
import requests as rq
from bs4 import BeautifulSoup as bs
url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')
hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
# print(href.get("href"))
links = href.get("href")
all_hrefs.append(links)
print(all_hrefs)
The syntax
variable=value command
is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:
a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'
The result will be 5 for the first echo and 3 for the second.
How you'd find a line break varies between operating system encodings. Windows would be \r\n
, but Linux just uses \n
and Apple uses \r
.
I found this in JavaScript line breaks:
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
That should remove all kinds of line breaks.
just follow three steps, git branch problem will be solved.
git remote update
git fetch
git checkout --track origin/test-branch
The "{{ ... }}"-delimiter can also be used within strings:
"http://{{ app.request.host }}"
the method modify()
that you called in the last is called in global context
if you want to override modify()
you first have to inherit A
or B
.
Maybe you're trying to do this:
In this case C
inherits A
function A() {
this.modify = function() {
alert("in A");
}
}
function B() {
this.modify = function() {
alert("in B");
}
}
C = function() {
this.modify = function() {
alert("in C");
};
C.prototype.modify(); // you can call this method where you need to call modify of the parent class
}
C.prototype = new A();
You have to add the python executable in your SYSTEM PATH, do the following, My Computer > Properties > Advanced System Settings > Environment Variables
> Then under system variables I create a new Variable called "PythonPath". In this variable I have "C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-foolder-on-the-path"
.
Bytes are transparently converted to ints.
Just say
int i= rno[0];
Instead of
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;
which is not correct, use
background-repeat: no-repeat;
I think you just need;
List<string> list = new List<string>();
list.Add("hai");
There is a difference between
List<string> list;
and
List<string> list = new List<string>();
When you didn't use new
keyword in this case, your list
didn't initialized. And when you try to add it hai
, obviously you get an error.
I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat
contains:
"This is the original content"
Then you can simply write:
f = open('myfile.dat', 'w')
f.close()
This would erase all the content. Then you can write the new content to the file:
f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()
If you have control over the structure of the list, the most pythonic thing to do would probably be to change it from:
l=[1,2,3,4]
to:
l=[(1,2),(3,4)]
Then, your loop would be:
for i,j in l:
print i, j
Thought i'd add my solution that i've been using.
If you're using the System.Web.Script.Serialization.JavaScriptSerializer()
then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset()
to get it back to your correct time.
String.prototype.toDateFromAspNet = function() {
var dte = eval("new " + this.replace(/\//g, '') + ";");
dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
return dte;
}
now you'll just call
"/Date(1245398693390)/".toDateFromAspNet();
Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}
edit 2018-09-13: added some precisions about this pre-flight request and how to avoid it at the end of this reponse.
OPTIONS
requests are what we call pre-flight
requests in Cross-origin resource sharing (CORS)
.
They are necessary when you're making requests across different origins in specific situations.
This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.
Your server should not ignore but handle these requests whenever you're attempting to do cross origin requests.
A good resource can be found here http://enable-cors.org/
A way to handle these to get comfortable is to ensure that for any path with OPTIONS
method the server sends a response with this header
Access-Control-Allow-Origin: *
This will tell the browser that the server is willing to answer requests from any origin.
For more information on how to add CORS support to your server see the following flowchart
http://www.html5rocks.com/static/images/cors_server_flowchart.png
edit 2018-09-13
CORS OPTIONS
request is triggered only in somes cases, as explained in MDN docs:
Some requests don’t trigger a CORS preflight. Those are called “simple requests” in this article, though the Fetch spec (which defines CORS) doesn’t use that term. A request that doesn’t trigger a CORS preflight—a so-called “simple request”—is one that meets all the following conditions:
The only allowed methods are:
- GET
- HEAD
- POST
Apart from the headers set automatically by the user agent (for example, Connection, User-Agent, or any of the other headers with names defined in the Fetch spec as a “forbidden header name”), the only headers which are allowed to be manually set are those which the Fetch spec defines as being a “CORS-safelisted request-header”, which are:
- Accept
- Accept-Language
- Content-Language
- Content-Type (but note the additional requirements below)
- DPR
- Downlink
- Save-Data
- Viewport-Width
- Width
The only allowed values for the Content-Type header are:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.
No ReadableStream object is used in the request.
If you use the database information_schema, you can use this mysql code (the where part makes the query not show tables that have a null value for rows):
SELECT TABLE_NAME, TABLE_ROWS
FROM `TABLES`
WHERE `TABLE_ROWS` >=0
It's unfortunate that you don't have Boost however if your STL implementation has the extensions then you can compose mem_fun_ref and select2nd to create a single functor suitable for use with for_each. The code would look something like this:
#include <algorithm>
#include <map>
#include <ext/functional> // GNU-specific extension for functor classes missing from standard STL
using namespace __gnu_cxx; // for compose1 and select2nd
class MyClass
{
public:
void Method() const;
};
std::map<int, MyClass> Map;
int main(void)
{
std::for_each(Map.begin(), Map.end(), compose1(std::mem_fun_ref(&MyClass::Method), select2nd<std::map<int, MyClass>::value_type>()));
}
Note that if you don't have access to compose1 (or the unary_compose template) and select2nd, they are fairly easy to write.
TL;DR:
Using slicing:
>>> import numpy as np
>>>
>>> arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
>>>
>>> arr[0,0]
1
>>> arr[1,1]
7
>>> arr[1,0]
6
>>> arr[1,-1]
10
>>> arr[1,-2]
9
In Long:
Hopefully this helps in your understanding:
>>> import numpy as np
>>> np.array([ [1,2,3], [4,5,6] ])
array([[1, 2, 3],
[4, 5, 6]])
>>> x = np.array([ [1,2,3], [4,5,6] ])
>>> x[1][2] # 2nd row, 3rd column
6
>>> x[1,2] # Similarly
6
But to appreciate why slicing is useful, in more dimensions:
>>> np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
>>> x = np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
>>> x[1][0][2] # 2nd matrix, 1st row, 3rd column
9
>>> x[1,0,2] # Similarly
9
>>> x[1][0:2][2] # 2nd matrix, 1st row, 3rd column
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 2
>>> x[1, 0:2, 2] # 2nd matrix, 1st and 2nd row, 3rd column
array([ 9, 12])
>>> x[1, 0:2, 1:3] # 2nd matrix, 1st and 2nd row, 2nd and 3rd column
array([[ 8, 9],
[11, 12]])
It seems to me that simply: ls -lt mydirectory
does the job...
Late to the party, but the top voted answers all seemed like hacks to me.
All I did was remove the following from my app.config in the test project. Worked.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
A combination of list comprehensions and str
joins can do the job:
inf = float('inf')
A = [[0,1,4,inf,3],
[1,0,2,inf,4],
[4,2,0,1,5],
[inf,inf,1,0,3],
[3,4,5,3,0]]
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in A]))
yields
0 1 4 inf 3
1 0 2 inf 4
4 2 0 1 5
inf inf 1 0 3
3 4 5 3 0
Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:
for i in range(n):
for j in range(n):
print '{:4}'.format(A[i][j]),
print
The more Pythonic cousin would be:
for row in A:
for val in row:
print '{:4}'.format(val),
print
However, this uses 30 print statements, whereas my original answer uses just one.
According to uber-JAR Documentation Approaches: There are three common methods for constructing an uber-JAR:
Unshaded Unpack all JAR files, then repack them into a single JAR. Tools: Maven Assembly Plugin, Classworlds Uberjar
Shaded Same as unshaded, but rename (i.e., "shade") all packages of all dependencies. Tools: Maven Shade Plugin
JAR of JARs The final JAR file contains the other JAR files embedded within. Tools: Eclipse JAR File Exporter, One-JAR.
You should only use ’
if your intention is to make either a closed single quotation mark or an apostrophe. Both of these punctuation marks are curved in shape in most fonts. If your intent is to make a foot mark, go the other route. A foot mark is always a straight vertical mark.
It’s a matter of typography. One way is correct; the other is not.
I actually managed to trigger a fancyBox link only from an external JS file using the "live" event:
First, add the live click event on your future dynamic anchor:
$('a.pub').live('click', function() {
$(this).fancybox(... fancybox parameters ...);
})
Then, append the anchor to the body:
$('body').append('<a class="iframe pub" href="your-url.html"></a>');
Then trigger the fancyBox by "clicking" the anchor:
$('a.pub').click();
The fancyBox link is now "almost" ready. Why "almost" ? Because it looks like you need to add some delay before trigger the second click, otherwise the script is not ready.
It's a quick and dirty delay using some animation on our anchor but it works well:
$('a.pub').slideDown('fast', function() {
$('a.pub').click();
});
Here you go, your fancyBox should appears onload!
HTH
Here's what singleton is: http://en.wikipedia.org/wiki/Singleton_pattern
I don't know C#, but it's actually the same thing in all languages, only implementation differs.
You should generally avoid singleton when it's possible, but in some situations it's very convenient.
Sorry for my English ;)
The best resource I found to implement MVC on Android is this post:
I followed the same design for one of my projects, and it worked great. I am a beginner on Android, so I can't say that this is the best solution.
I made one modification: I instantiated the model and the controller for each activity in the application class so that these are not recreated when the landscape-portrait mode changes.
You should be using @RequestParam
instead of @ModelAttribute
, e.g.
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
@RequestParam String someAttr) {
}
You can even omit @RequestParam
altogether if you choose, and Spring will assume that's what it is:
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
String someAttr) {
}
I think you want to change the setting called "DropDownStyle" to be "DropDownList".
I answered a similar question here
As @Syden said, the mixins will work. Another option is using SASS map-get
like this..
@media (min-width: map-get($grid-breakpoints, sm)){
.something {
padding: 10px;
}
}
@media (min-width: map-get($grid-breakpoints, md)){
.something {
padding: 20px;
}
}
http://www.codeply.com/go/0TU586QNlV
Have a look at java.io.File.list()
and FilenameFilter
.
Instead of that macro, might I suggest this one:
template<typename T, int N>
inline size_t array_size(T(&)[N])
{
return N;
}
#define ARRAY_SIZE(X) (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)
1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant.
2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays.
So, we use the defined-ness of the function to make the macro "safe"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.
The issue is with this line
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.
Hence replace this with
xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text
SELECT col1,
col2
FROM
(SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
(SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;
Props to @Nick-Harrison for his answer:
$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});
I was wondering what the parseInt() is for there? I've simplified it to this with no problems...
$("input[data-val-length-max]").each(function (index, element) {
element.setAttribute("maxlength", element.getAttribute("data-val-length-max"))
});
I would have commented on Nicks answer but don't have enough rep yet.
Simple solution, not much smart:
Temporarily block a part of a script:
if false; then
while you respect syntax a bit, please
do write here (almost) whatever you want.
but when you are
done # write
fi
A bit sophisticated version:
time_of_debug=false # Let's set this variable at the beginning of a script
if $time_of_debug; then # in a middle of the script
echo I keep this code aside until there is the time of debug!
fi
I have created an approximation of what I think you are looking for just using the Collections Framework in Java. Frankly, I think it is probably overkill as @Mike Deck points out. For such a small set of items to compare and process I think arrays would be a better choice from a procedural standpoint but here is my pseudo-coded (because I'm lazy) solution. I have an assumption that the Foo class is comparable based on it's unique id and not all of the data in it's contents:
Collection<Foo> oldSet = ...;
Collection<Foo> newSet = ...;
private Collection difference(Collection a, Collection b) {
Collection result = a.clone();
result.removeAll(b)
return result;
}
private Collection intersection(Collection a, Collection b) {
Collection result = a.clone();
result.retainAll(b)
return result;
}
public doWork() {
// if foo is in(*) oldSet but not newSet, call doRemove(foo)
Collection removed = difference(oldSet, newSet);
if (!removed.isEmpty()) {
loop removed {
Foo foo = removedIter.next();
doRemove(foo);
}
}
//else if foo is not in oldSet but in newSet, call doAdd(foo)
Collection added = difference(newSet, oldSet);
if (!added.isEmpty()) {
loop added {
Foo foo = addedIter.next();
doAdd(foo);
}
}
// else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)
Collection matched = intersection(oldSet, newSet);
Comparator comp = new Comparator() {
int compare(Object o1, Object o2) {
Foo f1, f2;
if (o1 instanceof Foo) f1 = (Foo)o1;
if (o2 instanceof Foo) f2 = (Foo)o2;
return f1.activated == f2.activated ? f1.startdate.compareTo(f2.startdate) == 0 ? ... : f1.startdate.compareTo(f2.startdate) : f1.activated ? 1 : 0;
}
boolean equals(Object o) {
// equal to this Comparator..not used
}
}
loop matched {
Foo foo = matchedIter.next();
Foo oldFoo = oldSet.get(foo);
Foo newFoo = newSet.get(foo);
if (comp.compareTo(oldFoo, newFoo ) != 0) {
doUpdate(oldFoo, newFoo);
} else {
//else if !foo.activated && foo.startDate >= now, call doStart(foo)
if (!foo.activated && foo.startDate >= now) doStart(foo);
// else if foo.activated && foo.endDate <= now, call doEnd(foo)
if (foo.activated && foo.endDate <= now) doEnd(foo);
}
}
}
As far as your questions: If I convert oldSet and newSet into HashMap (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? I think that you would probably make the code more readable by using a Map BUT...you would probably use more memory and time during the conversion.
Would iterating the two sets and perform the appropriate operation be more efficient and concise? Yes, this would be the best of both worlds especially if you followed @Mike Sharek 's advice of Rolling your own List with the specialized methods or following something like the Visitor Design pattern to run through your collection and process each item.
Try this...
SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
I was also facing same issue while installing typescript. I just initialized an package.josn file by the following command
npm init -y
And then i installed my typescript
npm install -g -typescript
I was also facing this issue. You might have more than JAVA versions installed. Make sure that JAVA_HOME variable is set to the correct version.
Having a default clause when it's not really needed is Defensive programming This usually leads to code that is overly complex because of too much error handling code. This error handling and detection code harms the readability of the code, makes maintenance harder, and eventually leads to more bugs than it solves.
So I believe that if the default shouldn't be reached - you don't have to add it.
Note that "shouldn't be reached" means that if it reached it's a bug in the software - you do need to test values that may contain unwanted values because of user input, etc.
Difference Between Abstraction and Encapsulation.
I think you should be able to select a disabled button using the following:
button[disabled=disabled], button:disabled {
// your css rules
}
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
There are some ways to get versionCode
and versionName
programmatically.
Get version from PackageManager
. This is the best way for most cases.
try {
String versionName = packageManager.getPackageInfo(packageName, 0).versionName;
int versionCode = packageManager.getPackageInfo(packageName, 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Get it from generated BuildConfig.java
. But notice, that if you'll access this values in library it will return library version, not apps one, that uses this library. So use only in non-library projects!
String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;
There are some details, except of using second way in library project. In new Android Gradle plugin (3.0.0+) some functionalities removed. So, for now, i.e. setting different version for different flavors not working correct.
Incorrect way:
applicationVariants.all { variant ->
println('variantApp: ' + variant.getName())
def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
variant.mergedFlavor.versionCode = versionCode
variant.mergedFlavor.versionName = versionName
}
Code above will correctly set values in BuildConfig
, but from PackageManager
you'll receive 0
and null
if you didn't set version in default
configuration. So your app will have 0
version code on device.
There is a workaround - set version for output apk
file manually:
applicationVariants.all { variant ->
println('variantApp: ' + variant.getName())
def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
variant.outputs.all { output ->
output.versionCodeOverride = versionCode
output.versionNameOverride = versionName
}
}
CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?
I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).
However the refused message is likely a server side problem, (usually port closed).
The expression
"" + i
leads to string conversion of i
at runtime. The overall type of the expression is String
. i
is first converted to an Integer
object (new Integer(i)
), then String.valueOf(Object obj)
is called. So it is equivalent to
"" + String.valueOf(new Integer(i));
Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i))
which will produce the very same result.
The advantage of ""+i
is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.
(Reference: JLS 15.8.1)
If you're on Windows you just probably change filename to lower/upper case like File.txt - file.txt
So check what file you have in git and rename it to what you want:
git status
Then I need file.txt -> but git status gaves me File.txt so just rename it
git mv File.txt file.txt
And problem is solved.
click here for good explaination!
All you need to know about relative file paths:
Starting with "/" returns to the root directory and starts there
Starting with "../" moves one directory backward and starts there
Starting with "../../" moves two directories backward and starts there (and so on...)
To move forward, just start with the first subdirectory and keep moving forward
There's a handy function, oidvectortypes
, that makes this a lot easier.
SELECT format('%I.%I(%s)', ns.nspname, p.proname, oidvectortypes(p.proargtypes))
FROM pg_proc p INNER JOIN pg_namespace ns ON (p.pronamespace = ns.oid)
WHERE ns.nspname = 'my_namespace';
Credit to Leo Hsu and Regina Obe at Postgres Online for pointing out oidvectortypes
. I wrote similar functions before, but used complex nested expressions that this function gets rid of the need for.
(edit in 2016)
Summarizing typical report options:
-- Compact:
SELECT format('%I.%I(%s)', ns.nspname, p.proname, oidvectortypes(p.proargtypes))
-- With result data type:
SELECT format(
'%I.%I(%s)=%s',
ns.nspname, p.proname, oidvectortypes(p.proargtypes),
pg_get_function_result(p.oid)
)
-- With complete argument description:
SELECT format('%I.%I(%s)', ns.nspname, p.proname, pg_get_function_arguments(p.oid))
-- ... and mixing it.
-- All with the same FROM clause:
FROM pg_proc p INNER JOIN pg_namespace ns ON (p.pronamespace = ns.oid)
WHERE ns.nspname = 'my_namespace';
NOTICE: use p.proname||'_'||p.oid AS specific_name
to obtain unique names, or to JOIN with information_schema
tables — see routines
and parameters
at @RuddZwolinski's answer.
The function's OID (see pg_catalog.pg_proc
) and the function's specific_name (see information_schema.routines
) are the main reference options to functions. Below, some useful functions in reporting and other contexts.
--- --- --- --- ---
--- Useful overloads:
CREATE FUNCTION oidvectortypes(p_oid int) RETURNS text AS $$
SELECT oidvectortypes(proargtypes) FROM pg_proc WHERE oid=$1;
$$ LANGUAGE SQL IMMUTABLE;
CREATE FUNCTION oidvectortypes(p_specific_name text) RETURNS text AS $$
-- Extract OID from specific_name and use it in oidvectortypes(oid).
SELECT oidvectortypes(proargtypes)
FROM pg_proc WHERE oid=regexp_replace($1, '^.+?([^_]+)$', '\1')::int;
$$ LANGUAGE SQL IMMUTABLE;
CREATE FUNCTION pg_get_function_arguments(p_specific_name text) RETURNS text AS $$
-- Extract OID from specific_name and use it in pg_get_function_arguments.
SELECT pg_get_function_arguments(regexp_replace($1, '^.+?([^_]+)$', '\1')::int)
$$ LANGUAGE SQL IMMUTABLE;
--- --- --- --- ---
--- User customization:
CREATE FUNCTION pg_get_function_arguments2(p_specific_name text) RETURNS text AS $$
-- Example of "special layout" version.
SELECT trim(array_agg( op||'-'||dt )::text,'{}')
FROM (
SELECT data_type::text as dt, ordinal_position as op
FROM information_schema.parameters
WHERE specific_name = p_specific_name
ORDER BY ordinal_position
) t
$$ LANGUAGE SQL IMMUTABLE;
I checked the line 35 of xampp/apache/conf/httpd.conf and it was:
ServerRoot "/xampp/apache"
Which doesn't exist. ...
Create the directory, or change the path to the directory that contains your hypertext documents.
Another short solution:
from datetime import date
def diff_dates(date1, date2):
return abs(date2-date1).days
def main():
d1 = date(2013,1,1)
d2 = date(2013,9,13)
result1 = diff_dates(d2, d1)
print '{} days between {} and {}'.format(result1, d1, d2)
print ("Happy programmer's day!")
main()
To refresh your site's favicon you can force browsers to download a new version using the link tag and a querystring on your filename. This is especially helpful in production environments to make sure your users get the update.
<link rel="icon" href="http://www.yoursite.com/favicon.ico?v=2" />
That is the textarea
's job - for multiline text input. The input
won't do it; it wasn't designed to do it.
So use a textarea
. Besides their visual differences, they are accessed via JavaScript the same way (use value
property).
You can prevent newlines being entered via the input
event and simply using a replace(/\n/g, '')
.
Using Math.round()
will round the float to the nearest integer.
JSON.stringify
returns a String
. So, for example:
var data = [
{ id: 1, name: "bob" },
{ id: 2, name: "john" },
{ id: 3, name: "jake" },
];
JSON.stringify(data)
will return the equivalent of:
"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"
as a String
value.
So when you have
<% for(var i=0; i<JSON.stringify(data).length; i++) {%>
what that ends up looking like is:
<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>
which is probably not what you want. What you probably do want is something like this:
<table>
<% for(var i=0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</table>
This will output the following table (using the example data
from above):
<table>
<tr>
<td>1</td>
<td>bob</td>
</tr>
<tr>
<td>2</td>
<td>john</td>
</tr>
<tr>
<td>3</td>
<td>jake</td>
</tr>
</table>
I've written a very simple router abstraction on top of History.js, called StateRouter.js. It's in very early stages of development, but I am using it as the routing solution in a single-page application I'm writing. Like you, I found History.js very hard to grasp, especially as I'm quite new to JavaScript, until I understood that you really need (or should have) a routing abstraction on top of it, as it solves a low-level problem.
This simple example code should demonstrate how it's used:
var router = new staterouter.Router();
// Configure routes
router
.route('/', getHome)
.route('/persons', getPersons)
.route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();
Here's a little fiddle I've concocted in order to demonstrate its usage.
You need to access the dataset
property:
document.getElementById("the-span").addEventListener("click", function() {
var json = JSON.stringify({
id: parseInt(this.dataset.typeid),
subject: this.dataset.type,
points: parseInt(this.dataset.points),
user: "Luïs"
});
});
Result:
// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
NestedScrollView
as the name suggests is used when there is a need for a scrolling view inside another scrolling view. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll.
This is where NestedScrollView
comes in.
If the other answers aren't working for you, there's also a homepage
field in package.json
. After running npm run build
you should get a message like the following:
The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:
"homepage" : "http://myname.github.io/myapp",
You would just add it as one of the root fields in package.json
, e.g.
{
// ...
"scripts": {
// ...
},
"homepage": "https://example.com"
}
When it's successfully set, either via homepage
or PUBLIC_URL
, you should instead get a message like this:
The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.
Wrap your function in $(document).ready(function() { })
, or more simply, $(function() {
. In CoffeeScript, this would look like
$ ->
$('#myModal').on 'show.bs.modal', (event)->
Without it, the JavaScript is executing before the document loads, and #myModal
is not part of the DOM yet. Here is the Bootstrap reference.
Also you can setup extJs writer
with encode
: true
and it will send data regularly (and, hence, you will be able to retrieve data via $_POST
and $_GET
).
... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)
UPDATE
Also docs say that:
The encode option should only be set to true when a root is defined
So, probably, writer
's root
config is required.
I'm making a guess here, but your start
invocation probably looks like this:
start "\Foo\Bar\Path with spaces in it\program.exe"
This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.
If you use start
with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:
start "" "\Foo\Bar\Path with spaces in it\program.exe"
This is because start
interprets the first quoted argument it finds as the window title for a new console window.
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
For the record: The following snippet can help you to get details about input, textarea, select, button, a tags through a temp title when hover them.
$( 'body' ).on( 'mouseover', 'input, textarea, select, button, a', function() {
var $tag = $( this );
var $form = $tag.closest( 'form' );
var title = this.title;
var id = this.id;
var name = this.name;
var value = this.value;
var type = this.type;
var cls = this.className;
var tagName = this.tagName;
var options = [];
var hidden = [];
var formDetails = '';
if ( $form.length ) {
$form.find( ':input[type="hidden"]' ).each( function( index, el ) {
hidden.push( "\t" + el.name + ' = ' + el.value );
} );
var formName = $form.prop( 'name' );
var formTitle = $form.prop( 'title' );
var formId = $form.prop( 'id' );
var formClass = $form.prop( 'class' );
formDetails +=
"\n\nFORM NAME: " + formName +
"\nFORM TITLE: " + formTitle +
"\nFORM ID: " + formId +
"\nFORM CLASS: " + formClass +
"\nFORM HIDDEN INPUT:\n" + hidden.join( "\n" );
}
var tempTitle =
"TAG: " + tagName +
"\nTITLE: " + title +
"\nID: " + id +
"\nCLASS: " + cls;
if ( 'SELECT' === tagName ) {
$tag.find( 'option' ).each( function( index, el ) {
options.push( el.value );
} );
tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type +
"\nSELECT OPTIONS:\n\t" + options;
} else if ( 'A' === tagName ) {
tempTitle +=
"\nHTML: " + $tag.html();
} else {
tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type;
}
tempTitle += formDetails;
$tag.prop( 'title', tempTitle );
$tag.on( 'mouseout', function() {
$tag.prop( 'title', title );
} )
} );
Here is one for DOS or Unix new line:
void chomp( string &s)
{
int pos;
if((pos=s.find('\n')) != string::npos)
s.erase(pos);
}
It should be well noted that the use of live()
in jQuery has been deprecated since version 1.7
and has been removed in jQuery 1.9
. Instead, the use of on()
is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
document.body
and passing $selector as the second argument to on()
, elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body
rather than $selector
directly, which means $selector
can be added, removed and added again and will never load the event bound to it.off()
before on()
, this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.$(function() {...})
, this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready()
does not get fired for AJAX requests, while $(function() {...})
does.Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
If you have names of the element and not id we can achieve the undefined check on all text elements (for example) as below and fill them with a default value say 0.0:
var aFieldsCannotBeNull=['ast_chkacc_bwr','ast_savacc_bwr'];
jQuery.each(aFieldsCannotBeNull,function(nShowIndex,sShowKey) {
var $_oField = jQuery("input[name='"+sShowKey+"']");
if($_oField.val().trim().length === 0){
$_oField.val('0.0')
}
})
Why would you want to override variables when you could easily reassign them in the subClasses.
I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.
public interface ExtensibleService{
void init();
}
public class WeightyLogicService implements ExtensibleService{
private String directoryPath="c:\hello";
public void doLogic(){
//never forget to call init() before invocation or build safeguards
init();
//some logic goes here
}
public void init(){}
}
public class WeightyLogicService_myAdaptation extends WeightyLogicService {
@Override
public void init(){
directoryPath="c:\my_hello";
}
}
Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask
to schedule a task to set a stopExecution
flag, and also .interrupt()
your thread.
With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).
Try this:
-1 * numeric_limits<double>::max()
Reference: numeric_limits
This class is specialized for each of the fundamental types, with its members returning or set to the different values that define the properties that type has in the specific platform in which it compiles.
I found a very clean solution that allows separate logic and GUI:
in your razor .cshtml page try this:
<body id="myId" data-my-variable="myValue">
...your page code here
</body>
in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):
$("#myId").data("my-variable")
As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code a little bit later on the same thread, I use this:
new android.os.Handler(Looper.getMainLooper()).postDelayed(
new Runnable() {
public void run() {
Log.i("tag", "This'll run 300 milliseconds later");
}
},
300);
.. this is pretty much equivalent to
setTimeout(
function() {
console.log("This will run 300 milliseconds later");
},
300);
Based on Documentation
Amending the message of older or multiple commit messages
git rebase -i HEAD~3
The above displays a list of the last 3 commits on the current branch, change 3 to something else if you want more. The list will look similar to the following:
pick e499d89 Delete CNAME
pick 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.
Replace pick with reword before each commit message you want to change. Let say you change the second commit in the list, your file will look like the following:
pick e499d89 Delete CNAME
reword 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.
Save and close the commit list file, this will pop up a new editer for you to change your commit message, change the commit message and save.
Finaly Force-push the amended commits.
git push --force
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
Replace
import { Router, Route, Link, browserHistory } from 'react-router';
With
import { BrowserRouter as Router, Route } from 'react-router-dom';
It will start working. It is because react-router-dom exports BrowserRouter
public void Empty(System.IO.DirectoryInfo directory)
{
try
{
logger.DebugFormat("Empty directory {0}", directory.FullName);
foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
catch (Exception ex)
{
ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture));
throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex);
}
}
another way of doing this is
int minLavel = Convert.ToInt32(dt.Select("AccountLevel=min(AccountLevel)")[0][0]);
I am not sure on the performace part but this does give the correct output
Try the following:
echo a#b#c | awk -F"#" '{$1 = ""; $NF = ""; print}' OFS=""
the non-regex way:
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf("["),input.indexOf("]"));
alternatively, for slightly better performance/memory usage (thanks Hosam):
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf('['),input.lastIndexOf(']'));