I did some analysis on the codebase I'm currently working on (40,000 lines of JavaScript).
I found only 22 break
statements, of those:
switch
statements (we only have 3 switch statements in total!).for
loops - a code that I immediately classified as to be refactored into separate functions and replaced with return
statement.break
inside while
loop... I ran git blame
to see who wrote this crap!So according to my statistics: If break
is used outside of switch
, it is a code smell.
I also searched for continue
statements. Found none.
It's a double-edged sword. It is sometimes very useful, but often dangerous.
When is it good? When you want 10 cases all processed the same way...
switch (c) {
case 1:
case 2:
... Do some of the work ...
/* FALLTHROUGH */
case 17:
... Do something ...
break;
case 5:
case 43:
... Do something else ...
break;
}
The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.
TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)
function arrayIndexExists(array, index){
if ( typeof index !== 'number' && index === parseInt(index).toString()) {
index = parseInt(index);
} else {
return false;//to avoid checking typeof again
}
return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}
The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.
Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)
Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.
This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);
var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"
This shows that associative keys are not used to access elements in the array, but for properties of the object.
foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3
This shows that checking typeof doesn't allow you to see if an element has been set.
var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined
This shows the exception I mentioned above and why you can't just use parseInt();
If you want to use associative arrays, you are better off using simple objects as other answers have recommended.
Since there's a chance that your excel files are coming from different computers/people; there's a chance that the formatting is messy; so be extra cautious.
I just imported data from 50 odd excels where the dates were entered in DD/MM/YYYY
or DD-MM-YYYY
, but most of the Excel files stored them as MM/DD/YYYY
(Probably because the PCs were setup with en-us
instead of en-gb
or en-in
).
Even more irritating was the fact that dates above 13/MM/YYYY
were in DD/MM/YYYY
format still. So there was variations within the Excel files.
The most reliable solution I figured out was to manually set the Date column on each excel file to to be Plain Text -- then use this code to parse it:
if date_str_from_excel:
try:
return datetime.strptime(date_str_from_excel, '%d/%m/%Y')
except ValueError:
print("Unable to parse date")
Make sure you have SQLCMD enabled by clicking on the Query > SQLCMD mode option in the management studio.
Suppose you have four .sql files (script1.sql,script2.sql,script3.sql,script4.sql
) in a folder c:\scripts
.
Create a main script file (Main.sql) with the following:
:r c:\Scripts\script1.sql
:r c:\Scripts\script2.sql
:r c:\Scripts\script3.sql
:r c:\Scripts\script4.sql
Save the Main.sql in c:\scripts itself.
Create a batch file named ExecuteScripts.bat
with the following:
SQLCMD -E -d<YourDatabaseName> -ic:\Scripts\Main.sql
PAUSE
Remember to replace <YourDatabaseName>
with the database you want to execute your scripts. For example, if the database is "Employee", the command would be the following:
SQLCMD -E -dEmployee -ic:\Scripts\Main.sql
PAUSE
Execute the batch file by double clicking the same.
To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class
//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
// handle click
});
but if you wish to apply click event to your button at once in a method.
you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener
.
In other to use Question #3 properly
You can do it by specifying alternating class names on the rows. I prefer using row0
and row1
, which means you can easily add them in, if the list is being built programmatically:
for ($i = 0; $i < 10; ++$i) {
echo '<tr class="row' . ($i % 2) . '">...</tr>';
}
Another way would be to use javascript. jQuery is being used in this example:
$('table tr:odd').addClass('row1');
Edit: I don't know why I gave examples using table rows... replace tr
with li
and table
with ul
and it applies to your example
The other way around, if you have problems ADDING the lines to your panel dont forget to add the to your TABLE. By default (http://getbootstrap.com/components/#panels), it is suppose to add the line but It helped me to add the tag so now the row lines are shown.
The following example "probably" wont display the lines between rows:
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Panel heading</div>
<!-- Table -->
<table class="table">
<tr><td> Hi 1! </td></tr>
<tr><td> Hi 2! </td></tr>
</table>
</div>
The following example WILL display the lines between rows:
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Panel heading</div>
<!-- Table -->
<table class="table">
<thead></thead>
<tr><td> Hi 1! </td></tr>
<tr><td> Hi 2! </td></tr>
</table>
</div>
If you have installed both Wampmanager and also Bitnami's wampstack on your Windows box (like I had done), make sure Bitnami has not been set to automatically start its wampstackApache and wampstackMySQL services at startup.
To check/fix this, click: Start-->Run and then type services.msc and click Ok.
Select Services in the list on the left and sort the services on Name. Scroll to the "w's". If wampstackApache and/or wampstackMySQL services are already started, right-click and stop both. Then Restart All Services from the Wampmanager W icon in the windows desktop services tray. The W should go green.
If this was your problem you can change the default startup behavior to manual start wampstackApache and wampstackMySQL in their Properties tabs.
Enable:
private void enableEditText() {
mEditText.setFocusableInTouchMode(true);
mEditText.setFocusable(true);
mEditText.setEnabled(true);
}
Disable:
private void disableEditText() {
mEditText.setEnabled(false);
mEditText.setFocusable(false);
mEditText.setFocusableInTouchMode(false);
}
Just as an FYI, here is my working code:
src_dir = "C:\\temp\\CSV\\"
target_dir = "C:\\temp\\output2\\"
keyword = "KEYWORD"
for f in os.listdir(src_dir):
file_name = os.path.join(src_dir, f)
out_file = os.path.join(target_dir, f)
with open(file_name, "r+") as fi, open(out_file, "w") as fo:
for line in fi:
if keyword not in line:
fo.write(line)
Thanks again to everyone for all the great feedback!
Using the command line is an option, and would remove the need for an Eclipse Plugin. First, create a directory to hold the project.
mkdir myGitRepo
cd myGitRepo
Clone the desired repository in the directory you just created.
git clone https://github.com/JonasHelming/gitTutorial.git
Then open Eclipse and select the directory you created (myGitRepo) as the Eclipse Workspace.
Don't worry that the Project Explorer is empty, Eclipse can't recognize the source files yet.
Lastly, create a new Java project with the exact same name as the project you pulled. In this case, it was 'gitTutorial'.
File -> New -> Java Project
At this point, the project's sub directories should contain the files pulled from Github. Take a look at the following post in my blog for a more detailed explanation.
http://brianredd.com/application/pull-java-project-from-github
%pip install fedex #fedex = package name
in 2019.
In older versions of conda:
import sys
!{sys.executable} -m pip install fedex #fedex = package name
*note - you do need to import sys
I had a special requirement wherein I already had a dataframe but given a certain condition I had to return an empty dataframe so I returned df.limit(0)
instead.
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
I have used the answer of @Dan Eastwell and it works very well. The code is similar to his code but with some additions.
.granddata {
position: relative;
margin-left :0.5%;
margin-right :0.5%;
}
.granddata:after {
content : "";
display: block;
position: absolute;
top: 0;
left: 0;
background-image: url("/Images/blabla.jpg");
width: 100%;
height: 100%;
opacity: 0.2;
z-index: -1;
background-repeat: no-repeat;
background-position: center;
background-attachment:fixed;
}
Here is the shortest solution (One Liner) ES6:
Math.max(...values.map(o => o.y));
Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0
HTML Date Picker You can refer this.
CREATE TABLE User (
user_id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
userImage LONGBLOB NOT NULL,
Favorite VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);
and
CREATE TABLE Event (
EventID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (EventID),
EventName VARCHAR(100) NOT NULL,
EventLocation VARCHAR(100) NOT NULL,
EventPriceRange VARCHAR(100) NOT NULL,
EventDate Date NOT NULL,
EventTime Time NOT NULL,
EventDescription VARCHAR(255) NOT NULL,
EventCategory VARCHAR(255) NOT NULL,
EventImage LONGBLOB NOT NULL,
index(EventID),
FOREIGN KEY (EventID) REFERENCES User(user_id)
);
Better way is:
Date date = ...;
Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate()
Advantages of this version:
works regardless the input is an instance of java.util.Date
or it's a subclass of java.sql.Date
(unlike @JodaStephen's way). This is common with JDBC-originated data. java.sql.Date.toInstant()
always throws an exception.
it's the same for JDK8 and JDK7 with JSR-310 backport
I personally use an utility class (but it is not backport-compatible):
/**
* Utilities for conversion between the old and new JDK date types
* (between {@code java.util.Date} and {@code java.time.*}).
*
* <p>
* All methods are null-safe.
*/
public class DateConvertUtils {
/**
* Calls {@link #asLocalDate(Date, ZoneId)} with the system default time zone.
*/
public static LocalDate asLocalDate(java.util.Date date) {
return asLocalDate(date, ZoneId.systemDefault());
}
/**
* Creates {@link LocalDate} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static LocalDate asLocalDate(java.util.Date date, ZoneId zone) {
if (date == null)
return null;
if (date instanceof java.sql.Date)
return ((java.sql.Date) date).toLocalDate();
else
return Instant.ofEpochMilli(date.getTime()).atZone(zone).toLocalDate();
}
/**
* Calls {@link #asLocalDateTime(Date, ZoneId)} with the system default time zone.
*/
public static LocalDateTime asLocalDateTime(java.util.Date date) {
return asLocalDateTime(date, ZoneId.systemDefault());
}
/**
* Creates {@link LocalDateTime} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static LocalDateTime asLocalDateTime(java.util.Date date, ZoneId zone) {
if (date == null)
return null;
if (date instanceof java.sql.Timestamp)
return ((java.sql.Timestamp) date).toLocalDateTime();
else
return Instant.ofEpochMilli(date.getTime()).atZone(zone).toLocalDateTime();
}
/**
* Calls {@link #asUtilDate(Object, ZoneId)} with the system default time zone.
*/
public static java.util.Date asUtilDate(Object date) {
return asUtilDate(date, ZoneId.systemDefault());
}
/**
* Creates a {@link java.util.Date} from various date objects. Is null-safe. Currently supports:<ul>
* <li>{@link java.util.Date}
* <li>{@link java.sql.Date}
* <li>{@link java.sql.Timestamp}
* <li>{@link java.time.LocalDate}
* <li>{@link java.time.LocalDateTime}
* <li>{@link java.time.ZonedDateTime}
* <li>{@link java.time.Instant}
* </ul>
*
* @param zone Time zone, used only if the input object is LocalDate or LocalDateTime.
*
* @return {@link java.util.Date} (exactly this class, not a subclass, such as java.sql.Date)
*/
public static java.util.Date asUtilDate(Object date, ZoneId zone) {
if (date == null)
return null;
if (date instanceof java.sql.Date || date instanceof java.sql.Timestamp)
return new java.util.Date(((java.util.Date) date).getTime());
if (date instanceof java.util.Date)
return (java.util.Date) date;
if (date instanceof LocalDate)
return java.util.Date.from(((LocalDate) date).atStartOfDay(zone).toInstant());
if (date instanceof LocalDateTime)
return java.util.Date.from(((LocalDateTime) date).atZone(zone).toInstant());
if (date instanceof ZonedDateTime)
return java.util.Date.from(((ZonedDateTime) date).toInstant());
if (date instanceof Instant)
return java.util.Date.from((Instant) date);
throw new UnsupportedOperationException("Don't know hot to convert " + date.getClass().getName() + " to java.util.Date");
}
/**
* Creates an {@link Instant} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static Instant asInstant(Date date) {
if (date == null)
return null;
else
return Instant.ofEpochMilli(date.getTime());
}
/**
* Calls {@link #asZonedDateTime(Date, ZoneId)} with the system default time zone.
*/
public static ZonedDateTime asZonedDateTime(Date date) {
return asZonedDateTime(date, ZoneId.systemDefault());
}
/**
* Creates {@link ZonedDateTime} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static ZonedDateTime asZonedDateTime(Date date, ZoneId zone) {
if (date == null)
return null;
else
return asInstant(date).atZone(zone);
}
}
The asLocalDate()
method here is null-safe, uses toLocalDate()
, if input is java.sql.Date
(it may be overriden by the JDBC driver to avoid timezone problems or unnecessary calculations), otherwise uses the abovementioned method.
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
I beleive I'm little late here. But I think this would help for the new peeps! If you're using smtp.gmail.com , then you have to do the following:
Turn on the less secure apps
You'll get the security mail in your gmail inbox, Click Yes,it's me in that.
// I would make it a little bit more simple
var products = new List<List<product>> {item1, item2, item3 }.SelectMany(id => id).ToList();
This way it is a multi dimensional List and the .SelectMany() will flatten it into a IEnumerable of product then I use the .ToList() method after.
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\
. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version
(Determine installed PowerShell version) shows it's 2.0.
Another option is type $PSVersionTable
at the command prompt. If you are running v2.0, the output will be:
Name Value
---- -----
CLRVersion 2.0.50727.4927
BuildVersion 6.1.7600.16385
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
If you're running version 1.0, the variable doesn't exist and there will be no output.
Localization PowerShell version 1.0, 2.0, 3.0, 4.0:
//arraylist/Pojo you can Pass using bundle like this
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
intent.putExtra("BUNDLE",args);
startActivity(intent);
Get SecondActivity like this
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");
//Happy coding
Assuming you have the menuStrip
object and the menu is only one level deep, use:
ToolStripMenuItem item = menuStrip.Items
.OfType<ToolStripMenuItem>()
.SelectMany(it => it.DropDownItems.OfType<ToolStripMenuItem>())
.SingleOrDefault(n => n.Name == "MyMenu");
For deeper menu levels add more SelectMany operators in the statement.
if you want to search all menu items in the strip then use
ToolStripMenuItem item = menuStrip.Items
.Find("MyMenu",true)
.OfType<ToolStripMenuItem>()
.Single();
However, make sure each menu has a different name to avoid exception thrown by key duplicates.
To avoid exceptions you could use FirstOrDefault
instead of SingleOrDefault
/ Single
, or just return a sequence if you might have Name
duplicates.
Here's how
String details = "Hello \"world\"!";
details = details.replace("\"","\\\"");
System.out.println(details); // Hello \"world\"!
Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\"")
. You must reassign the variable details
to the resulting string.
Using
details = details.replaceAll("\"",""e;");
instead, results in
Hello "e;world"e;!
TL;DR - Just create a tag in the source repository against the commit you want to clone up to and use the tag in the fetch command. You can delete the tag from the original repo later to clean up.
Well, its 2014 and it looks like Charles Bailey's accepted answer from 2010 is well and truly outdated by now and most (all?) of the other answers involve cloning, which many people are hoping to avoid.
The following solution achieves what the OP and many others are looking for, which is a way to create a copy of a repository, including history, but only up to a certain commit.
Here are the commands I used with git version 2.1.2 to clone a local repo (ie. a repository in another directory) up to a certain point:
# in the source repository, create a tag against the commit you want to check out
git tag -m "Temporary tag" tmptag <sha1>
# create a new directory and change into that directory
cd somewhere_else;mkdir newdir;cd newdir
# ...and create a new repository
git init
# add the source repository as a remote (this can be a URL or a directory)
git remote add origin /path/to/original/repo
# fetch the tag, which will include the entire repo and history up to that point
git fetch origin refs/tags/tmptag
# reset the head of the repository
git reset --hard FETCH_HEAD
# you can now change back to the original repository and remove the temporary tag
cd original_repo
git tag -d tmptag
Hopefully this solution keeps working for a few more years! :-)
I came up with an ultra-simple solution:
import datetime
def calcEpochSec(dt):
epochZero = datetime.datetime(1970,1,1,tzinfo = dt.tzinfo)
return (dt - epochZero).total_seconds()
It works with both timezone-aware and timezone-naive datetime values. And no additional libraries or database workarounds are required.
Use QString::fromUtf16((ushort *)Data.data())
, as shown in the following code example:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// QByteArray to QString
// =====================
const char c_test[10] = {'t', '\0', 'e', '\0', 's', '\0', 't', '\0', '\0', '\0'};
QByteArray qba_test(QByteArray::fromRawData(c_test, 10));
qDebug().nospace().noquote() << "qba_test[" << qba_test << "]"; // Should see: qba_test[t
QString qstr_test = QString::fromUtf16((ushort *)qba_test.data());
qDebug().nospace().noquote() << "qstr_test[" << qstr_test << "]"; // Should see: qstr_test[test]
return a.exec();
}
This is an alternative solution to the one using QTextCodec. The code has been tested using Qt 5.4.
After upgrading to macOS v10.15 (Catalina), and upgrading all my vEnv modules, pip3 stopped working (gave error: "TypeError: 'module' object is not callable").
I found question 58386953 which led to here and solution.
sudo python3 -m pip uninstall pip
(this is necessary, but it did not fix problem, because it removed the base Python pip, but it didn't touch my vEnv pip)sudo easy_install pip
(reinstalling pip in base Python, not in vEnv)vEnv/bin
and type "source activate" to get into vEnvrm pip pip3 pip3.6
(it seems to be the only way to get rid of the bogus pip's in vEnv)I can think of two things:
First, try loading the image with:
string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));
Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".
Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx
The answer is in the error message. In the past you or a process did a sudo pip
and that caused some of the directories under /Library/Python/2.7/site-packages/...
to have permissions that make it unaccessable to your current user.
Then you did a pip install whatever
which relies on the other thing.
So to fix it, visit the /Library/Python/2.7/site-packages/... and find the directory with the root or not-your-user permissions and either remove then reinstall those packages, or just force ownership to the user to whom ought to have access.
You can brute force it like this:
Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
Dim i
For i = LBound(arr) To UBound(arr)
If arr(i) = stringToBeFound Then
IsInArray = True
Exit Function
End If
Next i
IsInArray = False
End Function
Use like
IsInArray("example", Array("example", "someother text", "more things", "and another"))
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
Perform the move directly in the repository.
This should do the work on any Javascript environment (NodeJS included).
const text = `
<html lang="en">
<head>
<style type="text/css">*{color:red}</style>
<script>alert('hello')</script>
</head>
<body><b>This is some text</b><br/><body>
</html>`;
// Remove style tags and content
text.replace(/<style[^>]*>.*<\/style>/gm, '')
// Remove script tags and content
.replace(/<script[^>]*>.*<\/script>/gm, '')
// Remove all opening, closing and orphan HTML tags
.replace(/<[^>]+>/gm, '')
// Remove leading spaces and repeated CR/LF
.replace(/([\r\n]+ +)+/gm, '');
I really wanted to avoid hard resets, this is what I came up with.
A -> B -> C -> D -> HEAD
To go back to A (which is 4 steps back):
git pull # Get latest changes
git reset --soft HEAD~4 # Set back 4 steps
git stash # Stash the reset
git pull # Go back to head
git stash pop # Pop the reset
git commit -m "Revert" # Commit the changes
<EditText
android:id="@+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/search_hint"
android:inputType="text"
android:imeOptions="actionSend" />
You can then listen for presses on the action button by defining a TextView.OnEditorActionListener for the EditText element. In your listener, respond to the appropriate IME action ID defined in the EditorInfo class, such as IME_ACTION_SEND. For example:
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
sendMessage();
handled = true;
}
return handled;
}
});
Source: https://developer.android.com/training/keyboard-input/style.html
None of these worked for me. I'm using Mac OS 10.10.5 and Workbench 6.3. What worked for me is Database->Migration Wizard... Flow the steps very carefully
A variation when using xpath in Java using count():
int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
// body node missing
}
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
Example
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
$('#mySelectOption').val('Please Select');
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
The easiest way is to use lubridate:
library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)
This function automatically returns objects of class POSIXct
and will work with either factors or characters.
The best I've seen so far is HtmlCleaner:
HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.
With HtmlCleaner you can locate any element using XPath.
For other html parsers see this SO question.
This is worked with me
if (evt.xa.which == 3)
{
alert("Right mouse clicked");
}
This question is quite old, but recently V8 has added Generators which can accomplish what the OP requested. Generators are generally easiest to use for async interactions with the assistance of a library such as suspend or gen-run.
Here's an example using suspend:
suspend(function* () {
console.log('Welcome to My Console,');
yield setTimeout(suspend.resume(), 10000); // 10 seconds pass..
console.log('Blah blah blah blah extra-blah');
})();
Related reading (by way of shameless self promotion): What's the Big Deal with Generators?.
You can use different types of redirect method in laravel -
return redirect()->intended('http://heera.it');
OR
return redirect()->to('http://heera.it');
OR
use Illuminate\Support\Facades\Redirect;
return Redirect::to('/')->with(['type' => 'error','message' => 'Your message'])->withInput(Input::except('password'));
OR
return redirect('/')->with(Auth::logout());
OR
return redirect()->route('user.profile', ['step' => $step, 'id' => $id]);
For cookies that I am explicitly setting, I switched to use SimpleCookie provided by Apache Shiro. It does not inherit from javax.servlet.http.Cookie so it takes a bit more juggling to get everything to work correctly however it does provide a property set HttpOnly and it works with Servlet 2.5.
For setting a cookie on a response, rather than doing response.addCookie(cookie)
you need to do cookie.saveTo(request, response)
.
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
Another possibility is to use regular expressions which is what Perl is famous for:
if ($mystring =~ /s1\.domain\.com/) {
print qq("$mystring" contains "s1.domain.com"\n);
}
The backslashes are needed because a .
can match any character. You can get around this by using the \Q
and \E
operators.
my $substring = "s1.domain.com";
if ($mystring =~ /\Q$substring\E/) {
print qq("$mystring" contains "$substring"\n);
}
Or, you can do as eugene y stated and use the index function.
Just a word of warning: Index returns a -1
when it can't find a match instead of an undef
or 0
.
Thus, this is an error:
my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
print qq("$mystring" doesn't contains "$substring"\n";
}
This will be wrong if s1.domain.com
is at the beginning of your string. I've personally been burned on this more than once.
You can also use pygooglechart, which uses the Google Chart API. This isn't something you'd always want to use, but if you want a small number of good, simple, charts, and are always online, and especially if you're displaying in a browser anyway, it's a good choice.
Felipsmartins is correct.
It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.
Which means you can do this:
curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'
Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.
I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.
curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros
This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)
Hope it helps.
Got the same error here!
It seems the Intellij cannot verify if the class implementation is a @Service or @Component.
Solve it just changing from Error to Warning(Pressing Alt + Enter).
When animating height (from 0 to auto), using transform: scaleY(0);
is another useful approach to hide the element, instead of display: none;
:
.section {
overflow: hidden;
transition: transform 0.3s ease-out;
height: auto;
transform: scaleY(1);
transform-origin: top;
&.hidden {
transform: scaleY(0);
}
}
$msg="You Enter Wrong Username OR Password"; $responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";
For someone using Android Studio 4.0 or above on MacOS 10.15.1 or above. Using command line blow:
# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/Google/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*
Difference
Library/Preferences/Google/AndroidStudio*
Library/Logs/Google/AndroidStudio*
Library/Caches/Google/AndroidStudio*
What's even cooler is the fact that you can use an inline Table-Valued Function to select which (and how many via TOP
) row(s) to update. That is:
UPDATE MyTable
SET Column1=@Value1
FROM tvfSelectLatestRowOfMyTableMatchingCriteria(@Param1,@Param2,@Param3)
For the table valued function you have something interesting to select the row to update like:
CREATE FUNCTION tvfSelectLatestRowOfMyTableMatchingCriteria
(
@Param1 INT,
@Param2 INT,
@Param3 INT
)
RETURNS TABLE AS RETURN
(
SELECT TOP(1) MyTable.*
FROM MyTable
JOIN MyOtherTable
ON ...
JOIN WhoKnowsWhatElse
ON ...
WHERE MyTable.SomeColumn=@Param1 AND ...
ORDER BY MyTable.SomeDate DESC
)
..., and there lies (in my humble opinion) the true power of updating only top selected rows deterministically while at the same time simplifying the syntax of the UPDATE
statement.
I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above.
Change the below parameter in the eclipse.ini (which is in the same directory as eclipse.exe) to match one of your current Java version. Note that I also changed the maximum memory allowed for the eclipse process (which is run in a JVM). If you having multiple Java versions installed this can be happen. The below trick word for me.
-Xmx512m
-Dosgi.requiredJavaVersion=1.6
I cahanged this to,
-Xmx1024m
-Dosgi.requiredJavaVersion=1.7
Then It worked...
I found yet another reason for this message. I was programming Scala. The solution was:
Now the debugging should work. Notice that I have installed the Scala IDE plugin, this option may not be available if you don't have it.
You can use a post-commit hook.
Put the post-commit hook script in the hooks
folder, create a wget_folder
in your C:\ drive, and put the wget.exe
file in this folder.
Add the following code in the file called post-commit.bat
SET REPOS=%1
SET REV=%2
FOR /f "tokens=*" %%a IN (
'svnlook uuid %REPOS%'
) DO (
SET UUID=%%a
)
FOR /f "tokens=*" %%b IN (
'svnlook changed --revision %REV% %REPOS%'
) DO (
SET POST=%%b
)
echo %REPOS% ----- 1>&2
echo %REV% -- 1>&2
echo %UUID% --1>&2
echo %POST% --1>&2
C:\wget_folder\wget ^
--header="Content-Type:text/plain" ^
--post-data="%POST%" ^
--output-document="-" ^
--timeout=2 ^
http://localhost:9090/job/Test/build/%UUID%/notifyCommit?rev=%REV%
where Test = name of the job
echo
is used to see the value and you can also add exit 2
at the end to know about the issue and whether the post-commit hook script is running or not.
As of pandas 0.17.0, DataFrame.sort()
is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values
As such, the answer to your question would now be
df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)
Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.
In my case, I am using another function.
Function
function openTab() {
window.open('https://play.google.com/store/apps/details?id=com.drishya');
}
<Link onClick={openTab}></Link>
You can do this:
def deleteContent(pfile):
fn=pfile.name
pfile.close()
return open(fn,'w')
The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:
For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next
If you do not want the symbols like colon to be inserted put an if condition in the loop.
Just searched for the docs, and found this:
Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:
{# returns true #}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
If your WS-RS needs raise an error why not just use the WebApplicationException?
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("{id}")
public MyEntity getFoo(@PathParam("id") long id, @QueryParam("lang")long idLanguage) {
if (idLanguage== 0){
// No URL parameter idLanguage was sent
ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
builder.entity("Missing idLanguage parameter on request");
Response response = builder.build();
throw new WebApplicationException(response);
}
... //other stuff to return my entity
return myEntity;
}
Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax
with dataType: 'jsonp'
meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}
.
This method is more kind of a proxy actually attached in window
object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Summary
Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.
If you have reqested with query string
?callback=my_callback_method
then, your server must response data wrapped like this:
my_callback_method({your json serialized data});
A reset will normally change everything, but you can use git stash
to pick what you want to keep. As you mentioned, stash
doesn't accept a path directly, but it can still be used to keep a specific path with the --keep-index
flag. In your example, you would stash the b directory, then reset everything else.
# How to make files a/* reappear without changing b and without recreating a/c?
git add b #add the directory you want to keep
git stash --keep-index #stash anything that isn't added
git reset #unstage the b directory
git stash drop #clean up the stash (optional)
This gets you to a point where the last part of your script will output this:
After checkout:
# On branch master
# Changes not staged for commit:
#
# modified: b/a/ba
#
no changes added to commit (use "git add" and/or "git commit -a")
a/a/aa
a/b/ab
b/a/ba
I believe this was the target result (b remains modified, a/* files are back, a/c is not recreated).
This approach has the added benefit of being very flexible; you can get as fine-grained as you want adding specific files, but not other ones, in a directory.
I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.
Google for "Gideros Mobile"
@reannual's answer works well, but there's an issue with it: os.popen
is now deprecated. The subprocess
module should be used instead, so here's a version of @reannual's code that uses subprocess
and directly answers the question (by giving the column width directly as an int
:
import subprocess
columns = int(subprocess.check_output(['stty', 'size']).split()[1])
Tested on OS X 10.9
The problem is that you do not have bzip2 installed. The tar program relies upon this external program to do compression. For installing bzip2, it depends on the system you are using. For example, with Ubuntu that would be on Ubuntu
sudo apt-get install bzip2
The GNU tar program does not know how to compress an existing file such as user-logs.tar (bzip2 does that). The tar program can use external compression programs gzip, bzip2, xz by opening a pipe to those programs, sending a tar archive via the pipe to the compression utility, which compresses the data which it reads from tar and writes the result to the filename which the tar program specifies.
Alternatively, the tar and compression utility could be the same program. BSD tar does its compression using lib archive (they're not really distinct except in name).
With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.
So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.
In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.
Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.
The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.
You can also use \openany
, \openright
and \openleft
commands:
\documentclass{memoir}
\begin{document}
\openany
\appendix
\openright
\appendixpage
This is the appendix.
\end{document}
I believe Twitter Bootstrap has a class called clearfix
that you can use to clear the floating.
<ul class="nav nav-tabs span2 clearfix">
For Ubuntu xampp,
Go to /opt/lampp/etc/extra/
and open httpd-xampp.conf file and add below lines to get remote access,
Order allow,deny
Require all granted
Allow from all
in /opt/lampp/phpmyadmin section.
And restart lampp using, /opt/lampp/lampp restart
you need javascript and some client side calculations: http://jsfiddle.net/omegaiori/NERE8/2/
you will need jquery to effectively achieve what you want. this function is very simple but very effective:
(function () {
var heights = $("#wrapper").outerHeight(true);
var outerHeights = $("#first").outerHeight(true);
jQuery('#second').css('height', (heights - outerHeights) + "px");
})();
first it detects the wrapper height, as it is set to 100% it's different everytime (it depends on what screen you are landing).
in the second step it gives the #second
div the appropriate height subtracting from the wrapper height the #first
div height. the result is the available height left in the wrapper div
Warning: This might inflate executable file size a little bit and cost a little runtime performance. IMO, this would be better if golang has such feature like macro or function decorator.
If you want to mock functions without changing its API, the easiest way is to change the implementation a little bit:
func getPage(url string) string {
if GetPageMock != nil {
return GetPageMock()
}
// getPage real implementation goes here!
}
func downloader() {
if GetPageMock != nil {
return GetPageMock()
}
// getPage real implementation goes here!
}
var GetPageMock func(url string) string = nil
var DownloaderMock func() = nil
This way we can actually mock one function out of the others. For more convenient we can provide such mocking boilerplate:
// download.go
func getPage(url string) string {
if m.GetPageMock != nil {
return m.GetPageMock()
}
// getPage real implementation goes here!
}
func downloader() {
if m.GetPageMock != nil {
return m.GetPageMock()
}
// getPage real implementation goes here!
}
type MockHandler struct {
GetPage func(url string) string
Downloader func()
}
var m *MockHandler = new(MockHandler)
func Mock(handler *MockHandler) {
m = handler
}
In test file:
// download_test.go
func GetPageMock(url string) string {
// ...
}
func TestDownloader(t *testing.T) {
Mock(&MockHandler{
GetPage: GetPageMock,
})
// Test implementation goes here!
Mock(new(MockHandler)) // Reset mocked functions
}
I have this:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False
I prefer Serializable
= no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable
does not matter.
I would also always provide a helper method for a Fragment
or Activity
, this way you always know, what data has to be passed. Here an example for your ListMusicFragment
:
private static final String EXTRA_MUSIC_LIST = "music_list";
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(EXTRA_MUSIC_LIST, music);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(...) {
...
Bundle bundle = intent.getArguments();
List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
...
}
Extending Piotr's answer, if you also need a way to figure what to put in requirements.in
, you can first use pip-chill
to find the minimal set of required packages you have. By combining these tools, you can show the dependency reason why each package is installed. The full cycle looks like this:
$ python3 -m venv venv
$ . venv/bin/activate
(venv)$ pip install --upgrade pip
(venv)$ pip install pip-tools pip-chill
(venv)$ pip-chill --no-version > requirements.in
(venv)$ pip-compile requirements.in
(venv)$ pip-sync
You need to checkout the repository onto your local machine. Then you can change that folder on your local machine.
git commit -am "added files"
That command will commit all files to the repo.
git push origin master
that will push all changes in your master branch (which I assume is the one you're using) to the remote repository origin (in this case github)
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
Discovery is far easier in REST. We have WADL documents (similar to WSDL in traditional webservices) that will help you to advertise your service to the world. You can use UDDI discoveries as well. With traditional HTTP POST and GET people may not know your message request and response schemas to call you.
To run a URL simply use command below easy yess CPanel 100%
/usr/bin/php -q /home/CpanelUsername/public_html/RootFolder/cronjob/fetch.php
I hope this help.
In case anyone wants an alternative method...
If it is the last subdirectory in the path, you can use this one-liner:
cd "c:\directory\subdirectory\filename.exe\..\.." && dir /ad /b /s
This would return the following:
c:\directory\subdirectory
The .... drops back to the previous directory. /ad shows only directories /b is a bare format listing /s includes all subdirectories. This is used to get the full path of the directory to print.
This code works for me:
import groovy.io.FileType
def list = []
def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:
list.each {
println it.path
}
You can use Apache commons lang ReflectionToStringBuilder
You can either specify the attributes you want to test one by one, or better, exclude those you don't want:
String s = new ReflectionToStringBuilder(o, ToStringStyle.SHORT_PREFIX_STYLE)
.setExcludeFieldNames(new String[] { "foo", "bar" }).toString()
You then compare the two strings as normal. For the point about reflection being slow, I assume this is only for testing, so shouldn't be so important.
I actually found the suggestion from Rick Strahl's Web Log fixed my issue perfectly (as I still had the odd issue with ng-cloak blinking raw {{code}} at times, especially while running Firebug):
The nuclear option: Hiding the Content manually
Using the explicit CSS is the best choice, so the following shouldn’t ever be necessary. But I’ll mention it here as it gives some insight how you can hide/show content manually on load for other frameworks or in your own markup based templates.
Before I figured out that I could explicitly embed the CSS style into the page, I had tried to figure out why ng-cloak wasn’t doing its job. After wasting an hour getting nowhere I finally decided to just manually hide and show the container. The idea is simple – initially hide the container, then show it once Angular has done its initial processing and removal of the template markup from the page.
You can manually hide the content and make it visible after Angular has gotten control. To do this I used:
<div id="mainContainer" class="mainContainer boxshadow"
ng-app="app" style="display:none">
Notice the display: none style that explicitly hides the element initially on the page.
Then once Angular has run its initialization and effectively processed the template markup on the page you can show the content. For Angular this ‘ready’ event is the app.run() function:
app.run( function ($rootScope, $location, cellService) {
$("#mainContainer").show();
…
});
This effectively removes the display:none style and the content displays. By the time app.run() fires the DOM is ready to displayed with filled data or at least empty data – Angular has gotten control.
Another solution:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule implementation="org.jacoco.maven.RuleConfiguration">
<excludes>
<exclude>com.mypackage1</exclude
<exclude>com.mypackage2</exclude>
</excludes>
<element>PACKAGE</element>
<limits>
<limit implementation="org.jacoco.report.check.Limit">
<counter>COMPLEXITY</counter>
<value>COVEREDRATIO</value>
<minimum>0.85</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
Please note that, we are using "<element>PACKAGE</element>"
in the configuration which then helps us to exclude at package level.
Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.
From there you can change the binding options for both the client and the services, one of these options will be for time-outs.
With me, in the project directory run the following commands.
For react native old version (you will see index.android.js in root):
mkdir -p android/app/src/main/assets && rm -rf android/app/build && react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && cd android && ./gradlew clean assembleRelease && cd ../
For react native new version (you just see index.js in root):
mkdir -p android/app/src/main/assets && rm -rf android/app/build && react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && cd android && ./gradlew clean assembleRelease && cd ../
The apk file will be generated at:
In jinja2 templates (which flask uses), use
href="{{ url_for('static', filename='mainpage.css')}}"
The static
files are usually in the static
folder, though, unless configured otherwise.
Try this please. I checked it and it's working:
SELECT *
FROM Table
WHERE ARIDNR IN (
SELECT ARIDNR
FROM Table
GROUP BY ARIDNR
HAVING COUNT(distinct LIEFNR) > 1
)
It's not an answer, but...
To get datetime
components individually, better use datetime.timetuple:
time = datetime.now()
time.timetuple()
#-> time.struct_time(
# tm_year=2014, tm_mon=9, tm_mday=7,
# tm_hour=2, tm_min=38, tm_sec=5,
# tm_wday=6, tm_yday=250, tm_isdst=-1
#)
It's now easy to get the parts:
ts = time.timetuple()
ts.tm_year
ts.tm_mon
ts.tm_mday
ts.tm_hour
ts.tm_min
ts.tm_sec
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
There is actually a clever way to do this that is useful for any list of tuples where the size of each tuple is 2: you can convert your list into a single dictionary.
For example,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1
C# code can be split between lines on pretty much any syntatic construct without a need for a '_' style construct.
For example
foo.
Bar(
42
, "again");
I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
use
~/.bash_profile
or
~/.MacOSX/environment.plist
(see Runtime Configuration Guidelines)
Just adding 1 more scenario which may give the same error:
If you try to assign values to multiple variables, then also you will receive same error. For e.g.
In C (and many other languages), this is possible:
int a=2, b=3;
In Python:
a=2, b=5
will give error:
can't assign to literal
EDIT:
As per Arne's comment below, you can do this in Python for single line assignments in a slightly different way:
a, b = 2, 5
Try using Response.SetCookie()
, because Response.Cookies.Add()
can cause multiple cookies to be added, whereas SetCookie
will update an existing cookie.
The last changed time comes with the assumption that the web server provides accurate information. Dynamically generated pages will likely return the time the page was viewed. However, static pages are expected to reflect actual file modification time.
This is propagated through the HTTP header Last-Modified
. The Javascript trick by AZIRAR is clever and will display this value. Also, in Firefox going to Tools->Page Info will also display in the "Modified" field.
In my case i created below queries but in the first query if id
1 is already exists and age is already there, after that if you create first query without age
than the value of age
will be none
REPLACE into table SET `id` = 1, `name` = 'A', `age` = 19
for avoiding above issue create query like below
INSERT INTO table SET `id` = '1', `name` = 'A', `age` = 19 ON DUPLICATE KEY UPDATE `id` = "1", `name` = "A",`age` = 19
may it will help you ...
I did this in MySql and it updated multiple columns in a single record, so try this if you are using MySql as your server:
"UPDATE creditor_tb SET credit_amount='" & CDbl(cur_amount) & "'
, totalamount_to_pay='" & current_total & "',
WHERE credit_id='" & lbcreditId.Text & "'".
However, I was coding in vb.net using MySql server, but you can take it to your favorite programming language as far as you are using MySql as your server.
I am pretty sure it won't be possible with older versions of IE. Before the accept-charset
attribute was devised, there was no way for form
elements to specify which character encoding they accepted, and the best that browsers could do is assume the encoding of the page the form is in will do.
It is a bit sad that you need to know which encoding was used -- nowadays we would expect our web frameworks to take care of such details invisibly and expose the text data to the application as Unicode strings, already decoded...
You should be able to do something like this:
http://maps.google.com/maps?q=24.197611,120.780512
Some more info on the query parameters available at this location
Here's another link to an SO thread
Also, if you don't have the gradlew file in your current directory:
You can install gradle with homebrew with the following command:
$ brew install gradle
As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):
$ gradle test
I'm running oracle xpress edition 11.2 on windows 8 and I had the same error when trying to connect to DB using sqldeveloper.
I've edited listener.ora as per Brandt answer above and even restarted my machine the issue wasn't fixed.
I've done the following: go to control panel -> administrative tools -> services you will find a service called "OracleServiceXE" not running.
I started it and tried to connect again, issue resolved.
Search Tables:
SELECT c.name AS 'ColumnName'
,t.name AS 'TableName'
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyName%'
ORDER BY TableName
,ColumnName;
Search Tables and Views:
SELECT COLUMN_NAME AS 'ColumnName'
,TABLE_NAME AS 'TableName'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%MyName%'
ORDER BY TableName
,ColumnName;
This worked for me, maybe someone will find out this helpful:
TextView textField = (TextView) findViewById(R.id.textview1);
textField.setText("First line of text" + System.getProperty("line.separator") + "Linija 2");
Try this code, I used the following code for cloning and removing the cloned element, i have also used new class (newClass) which can be added automatically with the newly cloned html
for cloning..
$(".tr_clone_add").live('click', function() {
var $tr = $(this).closest('.tr_clone');
var newClass='newClass';
var $clone = $tr.clone().addClass(newClass);
$clone.find(':text').val('');
$tr.after($clone);
});
for removing the clone element.
$(".tr_clone_remove").live('click', function() { //Once remove button is clicked
$(".newClass:last").remove(); //Remove field html
x--; //Decrement field counter
});
html is as followinng
<tr class="tr_clone">
<!-- <td>1</td>-->
<td><input type="text" class="span12"></td>
<td><input type="text" class="span12"></td>
<td><input type="text" class="span12"></td>
<td><input type="text" class="span12"></td>
<td><input type="text" class="span10" readonly>
<span><a href="javascript:void(0);" class="tr_clone_add" title="Add field"><span><i class="icon-plus-sign"></i></span></a> <a href="javascript:void(0);" class="tr_clone_remove" title="Remove field"><span style="color: #D63939;"><i class="icon-remove-sign"></i></span></a> </span> </td> </tr>
Well, I guess the question is, what do you mean by 'roll back'? If you can't reset
because it's public and you want to keep the commit history intact, do you mean you just want your working copy to reflect a specific commit? Use git checkout
and the commit hash.
Edit: As was pointed out in the comments, using git checkout
without specifying a branch will leave you in a "no branch" state. Use git checkout <commit> -b <branchname>
to checkout into a branch, or git checkout <commit> .
to checkout into the current branch.
The presence of the n
option attached to the -k5
causes the global -r
option to be ignored for that field. You have to specify both n
and r
at the same level (globally or locally).
sort -t $'\t' -k5,5rn
or
sort -rn -t $'\t' -k5,5
I also faced this issue while integrating with jenkins server, I was used the root user for jenkin job, the issue was fixed when I changed the user to other user. I am not sure why this error occurs for the root user.
You can do it like this,
<input type="text" name="name" value="<?php echo $name;?>" />
But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />
If you don't want to add an extra extension the following code should work with jQuery.
$('a[href=#target]').
click(function(){
var target = $('a[name=target]');
if (target.length)
{
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 1000);
return false;
}
});
fun TextView.addImage(atText: String, @DrawableRes imgSrc: Int, imgWidth: Int, imgHeight: Int) {
val ssb = SpannableStringBuilder(this.text)
val drawable = ContextCompat.getDrawable(this.context, imgSrc) ?: return
drawable.mutate()
drawable.setBounds(0, 0,
imgWidth,
imgHeight)
val start = text.indexOf(atText)
ssb.setSpan(VerticalImageSpan(drawable), start, start + atText.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
this.setText(ssb, TextView.BufferType.SPANNABLE)
}
VerticalImageSpan
class from great answer
https://stackoverflow.com/a/38788432/5381331
Using
val textView = findViewById<TextView>(R.id.textview)
textView.setText("Send an [email-icon] to [email protected].")
textView.addImage("[email-icon]", R.drawable.ic_email,
resources.getDimensionPixelOffset(R.dimen.dp_30),
resources.getDimensionPixelOffset(R.dimen.dp_30))
Result
Note
Why VerticalImageSpan
class?
ImageSpan.ALIGN_CENTER
attribute requires API 29.
Also, after the test, I see that ImageSpan.ALIGN_CENTER
only work if the image smaller than the text, if the image bigger than the text then only image is in center, text not center, it align on bottom of image
What works for me is that, I created a new folder that doesn't contain any other files, and selected that new folder I created and put the clone there.
I hope this helps
I actually used the answer from How do I run a node.js app as a background service? combined with what dwrz said above. In my case, I was creating a Discord bot that needed to be able to run when I was not around.
With this service in place, I initially got the same error that the initial poster did, which brought me here. I was missing the #!/usr/bin/env node
at the top of my executed node.js script.
Since then, no problems, although I intend to see what else can be extended to the service itself.
Try this Code
var app = angular.module('myapp', []);
app.controller('testController', function ($scope, $http) {
$scope.init = function(){
alert($scope.testInput);
};});
<body ng-app="myapp">_x000D_
<div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >_x000D_
</div>_x000D_
</body>
_x000D_
There is an open issue in Mockito's GitHub about this exact problem.
I have found a simple workaround that does not force you to use annotations in your tests:
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
public final class MockitoCaptorExtensions {
public static <T> ArgumentCaptor<T> captorFor(final CaptorTypeReference<T> argumentTypeReference) {
return new CaptorContainer<T>().captor;
}
public static <T> ArgumentCaptor<T> captorFor(final Class<T> argumentClass) {
return ArgumentCaptor.forClass(argumentClass);
}
public interface CaptorTypeReference<T> {
static <T> CaptorTypeReference<T> genericType() {
return new CaptorTypeReference<T>() {
};
}
default T nullOfGenericType() {
return null;
}
}
private static final class CaptorContainer<T> {
@Captor
private ArgumentCaptor<T> captor;
private CaptorContainer() {
MockitoAnnotations.initMocks(this);
}
}
}
What happens here is that we create a new class with the @Captor
annotation and inject the captor into it. Then we just extract the captor and return it from our static method.
In your test you can use it like so:
ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(genericType());
Or with syntax that resembles Jackson's TypeReference
:
ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(
new CaptorTypeReference<Supplier<Set<List<Object>>>>() {
}
);
It works, because Mockito doesn't actually need any type information (unlike serializers, for example).
By utilizing string operations of JS one can do as follows;
0b1111011.toString(2).split(/0|(?=.)/).length // returns 6
or
0b1111011.toString(2).replace("0","").length // returns 6
I used:
Get-Content c:\FileToAppend_*.log | Out-File -FilePath C:\DestinationFile.log
-Encoding ASCII -Append
This appended fine. I added the ASCII encoding to remove the nul characters Notepad++ was showing without the explicit encoding.
Note: the commit 5e1361c from brian m. carlson (bk2204
) (for git 1.9/2.0 Q1 2014) deals with a special case in term of log decoration with tags:
log: properly handle decorations with chained tags
git log
did not correctly handle decorations when a tag object referenced another tag object that was no longer a ref, such as when the second tag was deleted.
The commit would not be decorated correctly becauseparse_object
had not been called on the second tag and therefore its tagged field had not been filled in, resulting in none of the tags being associated with the relevant commit.Call
parse_object
to fill in this field if it is absent so that the chain of tags can be dereferenced and the commit can be properly decorated.
Include tests as well to prevent future regressions.
Example:
git tag -a tag1 -m tag1 &&
git tag -a tag2 -m tag2 tag1 &&
git tag -d tag1 &&
git commit --amend -m shorter &&
git log --no-walk --tags --pretty="%H %d" --decorate=full
With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.
import { Router } from 'react-router';
export default class Foo extends Component {
static get contextTypes() {
return {
router: React.PropTypes.object.isRequired,
};
}
handleClick() {
this.context.router.push('/some-path');
}
}
I know about this problem. After add ssh key, add you ssh key to ssh agent too (from official docs)
ssh-agent -s
ssh-add ~/.ssh/id_rsa
After it all work fine, git can view proper key, before couldn't.
Note : Everything up here is correct,just replace sort --> sort_values() So, it becomes:
import pandas as pd
df = pd.read_csv('data.csv')
df.sort_values(ascending=False,inplace=True)
Refer to the official website here.
jquery:
$("div").fadeTo(1000 , 1);
css
div {
background: url("../images/example.jpg") no-repeat center;
opacity:0;
Height:100%;
}
html
<div></div>
You can do it by manually edit code first migration:
public override void Up()
{
AddColumn("dbo.Events", "Active", c => c.Boolean(nullable: false, defaultValue: true));
}
I don't understand what the meaning of ordering with the same column ASC
and DESC
in the same ORDER BY
, but this how you can do it: naam DESC, naam ASC
like so:
ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC
I would use this solution since window property may be changed during the app life cycle. So assigning "overrideUserInterfaceStyle = .light" needs to be repeated. UIWindow.appearance() enables us to set default value that will be used for newly created UIWindow objects.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13.0, *) {
UIWindow.appearance().overrideUserInterfaceStyle = .light
}
return true
}
}
Use of Glide library worked for me. Rotation is taken cared of automatically.
Bitmap bitmap = Glide.with(myContext).asBitmap().load(imageFilePath).submit(SIZE_ORIGINAL, SIZE_ORIGINAL).get();
Then you save that bitmap to a file in JPEG format, for example.
If you just want to load into an ImageView
instead of saving to a file:
Glide.with(myContext).load(imageFilePath).into(myImageView)
Here are a few simple examples to see the difference in action:
See the list of numbers here:
nums = [1, 9, -3, 4, 8, 5, 7, 14]
When calling sorted
on this list, sorted
will make a copy of the list. (Meaning your original list will remain unchanged.)
Let's see.
sorted(nums)
returns
[-3, 1, 4, 5, 7, 8, 9, 14]
Looking at the nums
again
nums
We see the original list (unaltered and NOT sorted.). sorted
did not change the original list
[1, 2, -3, 4, 8, 5, 7, 14]
Taking the same nums
list and applying the sort
function on it, will change the actual list.
Let's see.
Starting with our nums
list to make sure, the content is still the same.
nums
[-3, 1, 4, 5, 7, 8, 9, 14]
nums.sort()
Now the original nums list is changed and looking at nums we see our original list has changed and is now sorted.
nums
[-3, 1, 2, 4, 5, 7, 8, 14]
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.
The recommended way to do this would be with String.Format
:
string name = "Scott";
string output = String.Format("Hello {0}", name);
However, I wrote a small open-source library called SmartFormat that extends String.Format
so that it can use named placeholders (via reflection). So, you could do:
string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".
Hope you like it!
using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;
as Name = Fname + " " + LName;
See my below code which is working as expected; hope this is useful;
Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}
no need to declare the 'contact'
There is a possibility to find the PHP version of other domain by checking "X-Powered-By" response header in the browser through developer tools as other already mentioned it. If it is not exposed through the php.ini configuration there is no way you can get it unless you have access to the server.
ConcurrentLinkedQueue
uses a lock-free queue (based off the newer CAS instruction).
Just add a class of required to the select
<select id="select" class="required">
Something like this:
JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
Best way to do that:
In the Headers, add the following key-values:
Content-Type to applications/json
Accept to applications/json
Under body, click raw
and dropdown type to application/json
Also PFA for the same
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines
can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber()
after close()
.
That would be:
set "PATH=%PATH%;C:\Program Files\Java\jdk1.6.0_18\bin"
You can also append ;C:\Program Files\Java\jdk1.6.0_18\bin
to the PATH in the user environment dialog. That would allow you to use javac and other java tools directly form any cmd shell without setting the path first. The user environment dialog used to be somewhere in the system properties in XP, I have no idea where it is in Windows 7.
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
On SQL Server 2008 R2, I had a mismatch in table columns that caused the Rollback error. It went away when I fixed my sqlcmd table variable populated by the insert-exec statement to match that returned by the stored proc. It was missing org_code. In a windows cmd file, it loads result of stored procedure and selects it.
set SQLTXT= declare @resets as table (org_id nvarchar(9), org_code char(4), ^
tin(char9), old_strt_dt char(10), strt_dt char(10)); ^
insert @resets exec rsp_reset; ^
select * from @resets;
sqlcmd -U user -P pass -d database -S server -Q "%SQLTXT%" -o "OrgReport.txt"
There's a better way to do this in modern browsers using the vh
and vw
units.
vh is the viewport height.
So you can try something like this:
<style>
canvas {
border: solid 2px purple;
background-color: green;
width: 100%;
height: 80vh;
}
</style>
This will distort the aspect ration.
You can keep the aspect ratio by using the same unit for each. Here's an example with a 2:1 aspect ratio:
<style>
canvas {
width: 40vh;
height: 80vh;
}
</style>
You could also use to localStorage feature of HTML5 to store your test value and then access it at any other point in your website by using the localStorage.getItem()
method. To see how this works you should look at the w3schools explanation or the explanation from the Opera Developer website. Hope this helps.
If you are running cmake
to generate SomeLib
yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG
mode of the find_packages() command, you'll see that the User Package Registry is one of elements.
Brief how-to
Associate the targets of SomeLib
that you need outside of that external project by adding them to an export set in the CMakeLists.txt
files where they are created:
add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)
Create a XXXConfig.cmake
file for SomeLib
in its ${CMAKE_CURRENT_BUILD_DIR}
and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt
associated with SomeLib
:
export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake
Issue your find_package(SomeLib REQUIRED)
commmand in the CMakeLists.txt
file of the project that depends on SomeLib
without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH
.
When it might be the right approach
This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.
But if you're never actually installing SomeLib
in your workflow, calling EXPORT(PACKAGE <name>)
allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib
, you probably know your platform, CMAKE_MODULE_PATH
, etc, so @user2288008's excellent answer will have you covered.
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
Trying Node-6.4.0 ( process.versions.v8 = '5.0.71.60') and Node Chakracore-v7.0.0-pre8 and then Chrome-52 (V8=5.2.361.49), I've noticed that named parameters are almost implemented, but that order has still precedence. I can't find what the ECMA standard says.
>function f(a=1, b=2){ console.log(`a=${a} + b=${b} = ${a+b}`) }
> f()
a=1 + b=2 = 3
> f(a=5)
a=5 + b=2 = 7
> f(a=7, b=10)
a=7 + b=10 = 17
But order is required!! Is it the standard behaviour?
> f(b=10)
a=10 + b=2 = 12
Use Long.parseLong()
Long.parseLong("0", 10) // returns 0L
Long.parseLong("473", 10) // returns 473L
Long.parseLong("-0", 10) // returns 0L
Long.parseLong("-FF", 16) // returns -255L
Long.parseLong("1100110", 2) // returns 102L
Long.parseLong("99", 8) // throws a NumberFormatException
Long.parseLong("Hazelnut", 10) // throws a NumberFormatException
Long.parseLong("Hazelnut", 36) // returns 1356099454469L
Long.parseLong("999") // returns 999L
public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));
I think those can help for beginner: Naming convention of variables in c
I don't think it is very important to find the location of Svcutil.exe. You can use Visual Studio Command prompt to execute directly without its absolute path,
Syntax:
svcutil.exe /language:[vb|cs] /out:[YourClassName].[cs|vb] /config:[YourAppConfigFile.config] [YourServiceAddress]
example:
svcutil.exe /language:cs /out:MyClientClass.cs /config:app.config http://localhost:8370/MyService/
You can do something such as:
>>> print(''.join(map(str,range(1,11))))
12345678910
You don't actually declare things, but this is how you create an array in Python:
from array import array
intarray = array('i')
For more info see the array module: http://docs.python.org/library/array.html
Now possible you don't want an array, but a list, but others have answered that already. :)
when new allocates an array, depending on the compiler (i use gnu c++), the word in front of the array contains information about the number of bytes allocated.
The test code:
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
int arraySz;
char *a;
unsigned int *q;
for (arraySz = 5; arraySz <= 64; arraySz++) {
printf ("%02d - ", arraySz);
a = new char[arraySz];
unsigned char *p = (unsigned char *) a;
q = (unsigned int *) (a - 4);
printf ("%02d\n", (*q));
delete[] (a);
}
}
on my machine dumps out:
05 - 19
06 - 19
07 - 19
08 - 19
09 - 19
10 - 19
11 - 19
12 - 19
13 - 27
14 - 27
15 - 27
16 - 27
17 - 27
18 - 27
19 - 27
20 - 27
21 - 35
22 - 35
23 - 35
24 - 35
25 - 35
26 - 35
27 - 35
28 - 35
29 - 43
30 - 43
31 - 43
32 - 43
33 - 43
34 - 43
35 - 43
36 - 43
37 - 51
38 - 51
39 - 51
40 - 51
41 - 51
42 - 51
43 - 51
44 - 51
45 - 59
46 - 59
47 - 59
48 - 59
49 - 59
50 - 59
51 - 59
52 - 59
53 - 67
54 - 67
55 - 67
56 - 67
57 - 67
58 - 67
59 - 67
60 - 67
61 - 75
62 - 75
63 - 75
64 - 75
I would not recommend this solution (vector is better), but if you are really desperate, you could find a relationship and be able to conclude the number of bytes allocated from the heap.
imread
is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use imageio.imread
instead.
import imageio
im = imageio.imread('astronaut.png')
im.shape # im is a numpy array
(512, 512, 3)
imageio.imwrite('imageio:astronaut-gray.jpg', im[:, :, 0])
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
I added read
shell statement at the end. This keeps the main process of the container - startup shell script - running.
Depending on which event you actually want to use (textbox change
, or button click
), you can try this:
HTML:
<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>
JS:
function changeBackground(obj) {
document.getElementById("coltext").style.color = obj.value;
}
DEMO: http://jsfiddle.net/6pLUh/
One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange
allows you to change the color based on the input.
@ is used as a prefix denoting stored procedure and function parameter names, and also variable names
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}
#Convert dictionary to list (array)
keys = list(animals)
#Printing 1st dictionary key by index
print(keys[0])
#Done :)
CoundDownLatch enables you to make a thread wait till all other threads are done with their execution.
Pseudo code can be:
// Main thread starts
// Create CountDownLatch for N threads
// Create and start N threads
// Main thread waits on latch
// N threads completes there tasks are returns
// Main thread resume execution
The syntax of set item is
localStorage.setItem(key,value);
The syntax of get item is
localStorage.getItem(key);
An example of this is:
localStorage.setItem('email','[email protected]');
let mail = localStorage.getItem("email");
if(mail){
console.log('your email id is', mail);
}
}
here is another way to do it by calling Auth::logout() in route
Route::get('/logout', function(){
Auth::logout();
return Redirect::to('login');
});
When you see them spelled out in requirements they tend to include:
Inner and outer joins are a must but i rarely ever see it mentioned in requirements. And it's surprising how many so-called db professionals cannot get their head around a simple outer join.
Beside the oci.dll there are a few .jar files. This gave me the idea to install Java. Then everything worked.
Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:
CREATE PROCEDURE ExecuteMyHugeQuery
@SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
-- Now, if the length is greater than some arbitrary value
-- Let's say 2000 for this example
-- Let's chunk it
-- Let's also assume we won't allow anything larger than 8000 total
DECLARE @len INT
SELECT @len = LEN(@SQL)
IF (@len > 8000)
BEGIN
RAISERROR ('The query cannot be larger than 8000 characters total.',
16,
1);
END
-- Let's declare our possible chunks
DECLARE @Chunk1 VARCHAR(2000),
@Chunk2 VARCHAR(2000),
@Chunk3 VARCHAR(2000),
@Chunk4 VARCHAR(2000)
SELECT @Chunk1 = '',
@Chunk2 = '',
@Chunk3 = '',
@Chunk4 = ''
IF (@len > 2000)
BEGIN
-- Let's set the right chunks
-- We already know we need two chunks so let's set the first
SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)
-- Let's see if we need three chunks
IF (@len > 4000)
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)
-- Let's see if we need four chunks
IF (@len > 6000)
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
END
ELSE
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
END
END
ELSE
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
END
END
-- Alright, now that we've broken it down, let's execute it
EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END
Sometimes it doesn't get login with username = root
and password
, then you can change the default settings or the reset settings.
Open config.inc.php
file in the phpmyadmin folder
Instead of
$cfg['Servers'][$i]['AllowNoPassword'] = false;
change it to:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Do not specify any password and put the user name as it was before, which means root
.
E.g.
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
This worked for me after i had edited my config.inc.php
file.
The easiest way to do it, that I have found.. Apply the System.Xml.Serialization.XmlArray
attribute to it.
[System.Xml.Serialization.XmlArray] //This is the part that makes it work
List<object> serializableList = new List<object>();
XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());
serializableList.Add(PersonList);
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
xmlSerializer.Serialize(streamWriter, serializableList);
}
The serializer will pick up on it being an array and serialize the list's items as child nodes.
The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).
It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.
Regardless of the version, for your example, the <update>
is:
{ $set: { lastLookedAt: Date.now() / 1000 } }
However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {}
will match any document. In the Mongo shell, or with any MongoDB client:
db.foo.updateMany( {}, <update> )
{}
is the condition (the empty condition matches any document)db.foo.update( {}, <update>, { multi: true } )
{}
is the condition (the empty condition matches any document){multi: true}
is the "update multiple documents" optiondb.foo.update( {}, <update>, false, true )
{}
is the condition (the empty condition matches any document)false
is for the "upsert" parametertrue
is for the "multi" parameter (update multiple records)Using ios_base::sync_with_stdio(false);
is sufficient to decouple the C
and C++
streams. You can find a discussion of this in Standard C++ IOStreams and Locales, by Langer and Kreft. They note that how this works is implementation-defined.
The cin.tie(NULL)
call seems to be requesting a decoupling between the activities on cin
and cout
. I can't explain why using this with the other optimization should cause a crash. As noted, the link you supplied is bad, so no speculation here.
Why would we want to check if an array is empty
? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append
is a frequent novice error.
Using a list in if alist:
hinges on its boolean value:
In [102]: bool([])
Out[102]: False
In [103]: bool([1])
Out[103]: True
But trying to do the same with an array produces (in version 1.18):
In [104]: bool(np.array([]))
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value
of an empty array is ambiguous. Returning False, but in
future this will result in an error. Use `array.size > 0` to
check that an array is not empty.
#!/usr/bin/python3
Out[104]: False
In [105]: bool(np.array([1]))
Out[105]: True
and bool(np.array([1,2])
produces the infamous ambiguity error.
The accepted answer suggests size
:
In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0
But I (and most others) check the shape
more than the size
:
In [13]: x.shape
Out[13]: (0,)
Another thing in its favor is that it 'maps' on to an empty
list:
In [14]: x.tolist()
Out[14]: []
But there are other other arrays with 0 size
, that aren't 'empty' in that last sense:
In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True
np.array([[],[]])
is also size 0, but shape (2,0) and len
2.
While the concept of an empty
list is well defined, an empty array
is not well defined. One empty list is equal to another. The same can't be said for a size 0
array.
The answer really depends on
Anything after the "vmargs" is taken to be vm arguments. Just make sure it's before that, which is the last piece in eclipse.ini.
Using MySQL I usually do it that way:
SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;
Or in the same idea, if you need to output the date/hour:
SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM your_table
GROUP BY my_date
order by your_date_column desc;
If you specify an index on your date column, MySQL should be able to use it to speed up things a little.
This is a guess :)
Is it because the ID is a string? What happens if you change it to int?
I mean:
public int Id { get; set; }
If you want to allow Html tags only for few textbox in mvc
You can do one thing
in controller
[ValidateInput(false)]
public ActionResult CreateNewHtml() //view
{
return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult CreateNewHtml(cbs obj)//view cbs is database class
{
repo.AddHtml(obj);
return View();
}
Because I deal with both relative and absolute URLs, I updated veritas's solution like the code below.
You can try yourself here: https://ideone.com/PvpZ4J
function removeQueryStringFromUrl($url) {
if (substr($url,0,4) == "http") {
$urlPartsArray = parse_url($url);
$outputUrl = $urlPartsArray['scheme'] . '://' . $urlPartsArray['host'] . ( isset($urlPartsArray['path']) ? $urlPartsArray['path'] : '' );
} else {
$URLexploded = explode("?", $url, 2);
$outputUrl = $URLexploded[0];
}
return $outputUrl;
}
You can do this using jQuery's .scrollTop()
and .offset()
method
Check out my sample and this jsFiddle Demonstration
$(function() {
$(document).scrollTop( $("#header").offset().top );
});
Yes, you can call setId(value)
in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value)
. Note that it is valid to call setId()
with the same value for different sibling views, but findViewById()
will return only the first one.
I found these two links very helpful while I was trying to learn socket.io:
As already pointed out by @snishalaka, you can increase the number of inotify watchers.
However, I think the default number is high enough and is only reached when processes are not cleaned up properly. Hence, I simply restarted my computer as proposed on a related github issue and the error message was gone.
One additional implementation, which uses Newtonsoft.Json binary JSON and does not require marking everything with the [Serializable] attribute. Only one drawback is that an object has to be wrapped in anonymous class, so byte array obtained with binary serialization can be different from this one.
public static byte[] ConvertToBytes(object obj)
{
using (var ms = new MemoryStream())
{
using (var writer = new BsonWriter(ms))
{
var serializer = new JsonSerializer();
serializer.Serialize(writer, new { Value = obj });
return ms.ToArray();
}
}
}
Anonymous class is used because BSON should start with a class or array. I have not tried to deserialize byte[] back to object and not sure if it works, but have tested the speed of conversion to byte[] and it completely satisfies my needs.
You can use enumerate
and remove the values whose index matches the indices you want to remove:
indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]
Facebook now supports hiding the count, use this in the markup:
data-layout="button"
I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.
In this code we add multiple styles in an element:
let_x000D_
element = document.querySelector('span')_x000D_
, cssStyle = (el, styles) => {_x000D_
for (var property in styles) {_x000D_
el.style[property] = styles[property];_x000D_
}_x000D_
}_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
Just expanding Jeroen's answer with the tips in comments:
var content = new StringContent(
JsonConvert.SerializeObject(user),
Encoding.UTF8,
MediaTypeNames.Application.Json);
var response = await client.PostAsync("api/AgentCollection", content);
In VB its normally Dir
to find the directory of the file. If it's not blank then it exists and then use Kill
to get rid of the file.
test = Dir(Filename)
If Not test = "" Then
Kill (Filename)
End If
try it it is working fine
<%:Html.ActionLink("Details","Details","Product", new {id=item.dateID },null)%>
This isn't strictly an answer to your question about installing .gem
packages, but you can specify all kinds of locations on a gem-by-gem basis by editing your Gemfile.
:path
attribute will install the gem from that path on your local machine.gem "foreman", path: "/Users/pje/my_foreman_fork"
:git
attribute will install the gem from a remote git repository.gem "foreman", git: "git://github.com/pje/foreman.git"
# ...or at a specific SHA-1 ref
gem "foreman", git: "git://github.com/pje/foreman.git", ref: "bf648a070c"
# ...or branch
gem "foreman", git: "git://github.com/pje/foreman.git", branch: "jruby"
# ...or tag
gem "foreman", git: "git://github.com/pje/foreman.git", tag: "v0.45.0"
(As @JHurrah mentioned in his comment.)
Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>
, etc - since this is used (in the absence of a custom IEqualityComparer<T>
) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called).
The GetHashCode() method should reflect the Equals
logic; the rules are:
Equals(...) == true
) then they must return the same value for GetHashCode()
GetHashCode()
is equal, it is not necessary for them to be the same; this is a collision, and Equals
will be called to see if it is a real equality or not.In this case, it looks like "return FooId;
" is a suitable GetHashCode()
implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that new Foo(3,5)
has a different hash-code to new Foo(5,3)
):
unchecked // only needed if you're compiling with arithmetic checks enabled
{ // (the default compiler behaviour is *disabled*, so most folks won't need this)
int hash = 13;
hash = (hash * 7) + field1.GetHashCode();
hash = (hash * 7) + field2.GetHashCode();
...
return hash;
}
Oh - for convenience, you might also consider providing ==
and !=
operators when overriding Equals
and GetHashCode
.
A demonstration of what happens when you get this wrong is here.