If you already have it as a DateTime
, use:
string x = dt.ToString("yyyy-MM-dd");
See the MSDN documentation for more details. You can specify CultureInfo.InvariantCulture
to enforce the use of Western digits etc. This is more important if you're using MMM for the month name and similar things, but it wouldn't be a bad idea to make it explicit:
string x = dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
If you have a string to start with, you'll need to parse it and then reformat... of course, that means you need to know the format of the original string.
Here is a simple example of adding an image to a JFrame
:
frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));
<input size="45" type="text" name="name">
The "size" specifies the visible width in characters of the element input.
You can also use the height and width from css.
<input type="text" name="name" style="height:100px; width:300px;">
From official documentation, FailedPreconditionError
This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.
In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1
. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading
Basically to initialize the variable you have 3 options:
tf.global_variables_initializer()
tf.variables_initializer(list_of_vars)
. Notice that you can use this function to mimic global_variable_initializer: tf.variable_initializers(tf.global_variables())
var_name.initializer
I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables
and check is_variable_initialized
.
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
You're trying to change the value in the list, but all you're doing is changing the reference of x. Doing the following only changes x, not anything in the collection:
x = Integer.valueOf(9);
Additionally, Integer
is immutable, meaning you can't change the value inside the Integer object (which would require a different method to do anyway). This means you need to replace the whole object. There is no way to do this with an Iterator
(without adding your own layer of boxing). Do the following instead:
a.set(0, 9);
I agree that it is not possible in general.
The only thing CSS3 can do (which helped in my case) is to select elements that have no children:
table td:empty
{
background-color: white;
}
Or have any children (including text):
table td:not(:empty)
{
background-color: white;
}
Don`t forget to use DataGrid.Columns, all columns must be inside that collection. In my project I format date a little bit differently:
<tk:DataGrid>
<tk:DataGrid.Columns>
<tk:DataGridTextColumn Binding="{Binding StartDate, StringFormat=\{0:dd.MM.yy HH:mm:ss\}}" />
</tk:DataGrid.Columns>
</tk:DataGrid>
With AutoGenerateColumns you won`t be able to contol formatting as DataGird will add its own columns.
When a static constructor throws an exception, it is wrapped inside a TypeInitializationException
. You need to check the exception object's InnerException
property to see the actual exception.
In a staging / production environment (where you don't have Visual Studio installed), you'll need to either:
AppDomain.UnhandledException
event, and put your logging/tracing code there. Use System.Diagnostics.Debug.WriteLine
for tracing, or a logger (log4net, ETW). DbgView (a Sysinternals tool) can be used to view the Debug.WriteLine trace.If the condition isn't satisfied, an AssertionError
will be thrown.
Assertions have to be enabled, though; otherwise the assert
expression does nothing. See:
http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable
.offset()
will return the offset position of an element as a simple object, eg:
var position = $(element).offset(); // position = { left: 42, top: 567 }
You can use this return value to position other elements at the same spot:
$(anotherElement).css(position)
I was frustrated with all of the other answers to this question, because none of them highlight the space character in a useful way. Showing spaces as characters would particularly help for whitespace-formatted languages, where mixing tabs and spaces is harmful.
My solution is to show tabs and underline multiple spaces. It borrows from mrucci's answer and this tutorial. Because it uses syntax highlighting, it's persistent:
set list listchars=tab:\|\
highlight Whitespace cterm=underline gui=underline ctermbg=NONE guibg=NONE ctermfg=yellow guifg=yellow
autocmd ColorScheme * highlight Whitespace gui=underline ctermbg=NONE guibg=NONE ctermfg=yellow guifg=yellow
match Whitespace / \+/
Using this, tabs are displayed as |
and spaces as _
, which makes it very easy to tell when I'm mixing code styles.
The only downside I've found is that this snippet doesn't adjust background color to match the context (like in a comment).
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator. https://www.php.net/manual/en/language.operators.arithmetic.php
wrong use of + operator:
"<label for='content'>Content:</label>"+
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
"</div>";
use . for concatenation
$output = "<div class='from-group'>".
"<label for='content'>Content:</label>".
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
"</div>";
I also ran into this situation and figured out how to do it using FrameLayout. The following output is produced by the code given below.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/contactbook_icon"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="140"
android:textSize="12dp"
android:textColor="#FFFFFF"
android:layout_gravity="bottom|right"
android:layout_margin="15dp" />
</FrameLayout>
Change the margin value to adjust the text position over the image. Removing margin might make the text to go out of the view sometimes.
Normally i use a class for this:
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
Now you can use a loop to fill a list and ToArray
if you really need an array:
ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
FROM some table";
using (var command = new SqlCommand(sql, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
allRecords = list.ToArray();
}
}
Note that i've presumed that the first column is a string
and the second an integer
. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY
methods.
Try:
select id, game, min(point) from t
group by id
Was missing the use of calc
in the answers, which is a cleaner solution.
#logo {
position: absolute;
left: calc(50% - 25px);
height: 50px;
width: 50px;
background: red;
}
Works in most modern browsers: http://caniuse.com/calc
Maybe it's too soon to use it without a fallback, but I thought maybe for future visitors it would be helpful.
Here's a possible partial answer, because it only allows selecting the test scripts, not individual tests within those scripts.
And it also limited by my using legacy compatibility mode vs unittest
scripts, so not guaranteeing it would work with native pytest.
Here goes:
subset_tests_directory
.ln -s tests_directory/foo.py
ln -s tests_directory/bar.py
be careful about imports which implicitly assume files are in test_directory
. I had to fix several of those by running python foo.py
, from within subset_tests_directory
and correcting as needed.
Once the test scripts execute correctly, just cd subset_tests_directory
and pytest
there. Pytest will only pick up the scripts it sees.
Another possibility is symlinking within your current test directory, say as ln -s foo.py subset_foo.py
then pytest subset*.py
. That would avoid needing to adjust your imports, but it would clutter things up until you removed the symlinks. Worked for me as well.
I don't know if I would say heredoc is laziness. One can say that doing anything is laziness, as there are always more cumbersome ways to do anything.
For example, in certain situations you may want to output text, with embedded variables without having to fetch from a file and run a template replace. Heredoc allows you to forgo having to escape quotes, so the text you see is the text you output. Clearly there are some negatives, for example, you can't indent your heredoc, and that can get frustrating in certain situation, especially if your a stickler for unified syntax, which I am.
You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.
Resolved - to the original ask:
I've seen this before. Easiest way to fix (don't need all those data conversion steps as ALL of the meta data is available from the source connection):
Delete the OLE DB Source & OLE DB Destinations Make sure Delayed Validation is FALSE (you can set it to True later) Recreate the OLE DB Source with your query, etc. Verify in the Advanced Editor that all of the output data column types are correct Recreate your OLE DB Destination, map, create new table (or remap to existing) and you'll see that SSIS got all the data types correct (same as source).
So much easier that the stuff above.
I update my Hibernate JPA to 2.1 and It works.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
Try this:
<input type="number" max="???" min="???" step="0.5" id="myInput"/>
$("#myInput").attr({
"max" : 10,
"min" : 2
});
Note:This will set max and min value only to single input
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
I fixed this problem with next fix (maybe it will help someone):
Just check if the parent folders of your project folder have names with spaces or other forbidden characters. If yes - remove it.
"C:\Users\someuser\Test Projects\testProj" - on this case "Test Projects" should be "TestProjects".
In addtion to align-self
you can also consider auto margin which will do almost the same thing
.container {_x000D_
background: red;_x000D_
height: 200px;_x000D_
flex-direction: column;_x000D_
padding: 10px;_x000D_
display: flex;_x000D_
}_x000D_
a {_x000D_
margin-right:auto;_x000D_
padding: 10px 40px;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
<a href="#">Test</a>_x000D_
</div>
_x000D_
Below is the code that works well but my values overlap in sheet "Final" everytime the condition of <=11
meets in sheet "Calculator"
I would like you to kindly support me to modify the code so that the cursor should move to next blank cell and values keeps on adding up like a list.
Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Calculator")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Final")
For i = 2 To ws1.Range("A65536").End(xlUp).Row
If ws1.Cells(i, 4) <= 11 Then
ws2.Cells(i, 1).Value = Left(Worksheets("Calculator").Cells(i, 1).Value, Len(Worksheets("Calculator").Cells(i, 1).Value) - 0)
ws2.Cells(i, 2) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:D"), 4, False)
ws2.Cells(i, 3) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:E"), 5, False)
ws2.Cells(i, 4) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:B"), 2, False)
ws2.Cells(i, 5) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:C"), 3, False)
End If
Next i
Try this formula (it will return value from A1
as is if it's not a date):
=TEXT(A1,"mm-yyyy")
Or this formula (it's more strict, it will return #VALUE
error if A1
is not date):
=TEXT(MONTH(A1),"00")&"-"&YEAR(A1)
Quotes, but I prefer them on the just the value:
url: "http://www.example.com/"
Putting them across the whole line looks like it might cause problems.
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
Drifting a bit, but it would be relatively easy to autofill the US City/State or CA City/Provence when the user enters her postal code using a lookup table.
Here's how you could do it if you could force people to bend to your will:
User enters: postal (zip) code
You fill: state, city (province, for Canada)
User starts to enter: streetname
You: autofill
You display: a range of allowed address numbers
User: enters the number
Done.
Here's how it is natural for people to do it:
User enters: address number
You: do nothing
User starts to enter: street name
You: autofill, drawing from a massive list of every street in the country
User enters: city
You: autofill
User enters: state/provence
You: is it worth autofilling a few chars?
You: autofill postal (zip) code, if you can (because some codes straddle cities).
Now you know why people charge $$$ to do this. :)
For the street address, consider there are two parts: numeric and streetname. If you have the zip code, then you can narrow down the available streets, but most people enter the numeric part first, which is backwa
public static string FractionPart(this double instance)
{
var result = string.Empty;
var ic = CultureInfo.InvariantCulture;
var splits = instance.ToString(ic).Split(new[] { ic.NumberFormat.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);
if (splits.Count() > 1)
{
result = splits[1];
}
return result;
}
There is a standard and it is specified in the various standards documents (ISO, ANSI and whatnot).
Wikipedia has a great page explaining the various types and the max they may store: Integer in Computer Science.
However even with a standard C++ compiler you can find out relatively easily using the following code snippet:
#include <iostream>
#include <limits>
int main() {
// Change the template parameter to the various different types.
std::cout << std::numeric_limits<int>::max() << std::endl;
}
Documentation for std::numeric_limits can be found at Roguewave. It includes a plethora of other commands you can call to find out the various limits. This can be used with any arbitrary type that conveys size, for example std::streamsize.
John's answer contains the best description, as those are guaranteed to hold. No matter what platform you are on, there is another good page that goes into more detail as to how many bits each type MUST contain: int types, which are defined in the standard.
I hope this helps!
Create a function that checks whether the object is empty:
$scope.isEmpty = function(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
};
Then, you can check like so in your html:
ng-show="!isEmpty(card)"
You could say
$name ne ""
instead of
length $name > 0
Either of the following SQL will return all schema in Oracle DB.
select owner FROM all_tables group by owner;
select distinct owner FROM all_tables;
import csv
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
with open('file.txt') as f:
reader = csv.DictReader(f) # read rows into a dictionary format
for row in reader: # read a row as {column1: value1, column2: value2,...}
for (k,v) in row.items(): # go over each column name and value
columns[k].append(v) # append the value into the appropriate list
# based on column name k
print(columns['name'])
print(columns['phone'])
print(columns['street'])
With a file like
name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.
Will output
>>>
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']
Or alternatively if you want numerical indexing for the columns:
with open('file.txt') as f:
reader = csv.reader(f)
reader.next()
for row in reader:
for (i,v) in enumerate(row):
columns[i].append(v)
print(columns[0])
>>>
['Bob', 'James', 'Smithers']
To change the deliminator add delimiter=" "
to the appropriate instantiation, i.e reader = csv.reader(f,delimiter=" ")
You can simply use shape method
df[df['LastName'] == 'Smith'].shape
Output
(1,1)
Which indicates 1 row and 1 column. This way you can get the idea of whole datasets
Let me explain the above code
DataframeName[DataframeName['Column_name'] == 'Value to match in column']
I tried everything said here without any luck, but found a workaround.
After running this command (and failing) : bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
Go to the temporary directory the tool made (given in the output of the last command), then execute python setup.py bdist_wheel
. The .whl
file is in the dist
folder.
It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST. Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.
The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in RFC 2617.
(123456789).toString(10).split("")
^^ this will return an array of strings
(123456789).toString(10).split("").map(function(t){return parseInt(t)})
^^ this will return an array of ints
adding to scotty's answer:
Option 1: Either include this in your JS file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
Option 2: or just use the URL to download 'angular-route.min.js' to your local.
and then (whatever option you choose) add this 'ngRoute' as dependency.
explained:
var app = angular.module('myapp', ['ngRoute']);
Cheers!!!
Another solution might look like this,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
which avoids using an extra variable.
Visual Studio 2017 version 15.8 made it possible to use the PackageReferencesyntax to reference NuGet packages in Visual Studio Extensibility (VSIX) projects. This makes it much simpler to reason about NuGet packages and opens the door for having a complete meta package containing the entire VSSDK.
Installing below NuGet package will solve the EmbedInteropTypes Issue.
Install-Package Microsoft.VisualStudio.SDK.EmbedInteropTypes
I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path
But the main issue was not here. The problem was with these 2 lines of code
strFile = Dir(strPath & "*.csv")
Which should have written as
strFile = Dir(strPath & "\*.csv")
and
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Which should have written as
With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _
var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);
I am using JPA (OpenJPA implementation from Apache which is based on the KODO JDO codebase which is 5+ years old and extremely fast/reliable). IMHO anyone who tells you to bypass the specs is giving you bad advice. I put the time in and was definitely rewarded. With either JDO or JPA you can change vendors with minimal changes (JPA has orm mapping so we are talking less than a day to possibly change vendors). If you have 100+ tables like I do this is huge. Plus you get built0in caching with cluster-wise cache evictions and its all good. SQL/Jdbc is fine for high performance queries but transparent persistence is far superior for writing your algorithms and data input routines. I only have about 16 SQL queries in my whole system (50k+ lines of code).
Methods for finding a square root are recursive. Useful for calculating distances in the real world.
Didn't have +clipboard so I came up with this alternative solution using xsel:
Add to your ~/.vimrc:
vnoremap <C-C> :w !xsel -b<CR><CR>
try this, calling the activity in the constructor
public class WebService {
private Activity activity;
public WebService(Activity _activity){
activity=_activity;
helper=new Helper(activity);
}
}
You can use modern Java to solve this problem. Please use the code below:
static int findIndexOf(int V, int[] arr) {
return IntStream.range(0, arr.length)
.filter(i->arr[i]==V)
.findFirst()
.getAsInt();
}
NOTE: the answer that says to use the ZZ
command doesn't work for me on my Mavericks system, but this is probably due to something in my vim configuration because if I start with a pristine .vimrc
, the accepted answer works. My answer might work for you if the other solution doesn't.
On MacOS X, according to the crontab manpage, the crontab temporary file that gets created with crontab -e
needs to be edited in-place. Vim doesn't edit in-place by default (but it might do some special case to support crontab -e
), so if your $EDITOR
environment variable is set to vi
(the default) or vim
, editing the crontab will always fail.
To get Vim to edit the file in-place, you need to do:
:setlocal nowritebackup
That should enable you to update the crontab when you do crontab -e
with the :wq
or ZZ
commands.
You can add an autocommand in your .vimrc to make this automatically work when editing crontabs:
autocmd FileType crontab setlocal nowritebackup
Another way is to add the setlocal nowritebackup
to ~/.vim/after/ftplugin/crontab.vim
, which will be loaded by Vim automatically when you're editing a crontab file if you have the Filetype plugin enabled. You can also check for the OS if you're using your vim files across multiple platforms:
""In ~/.vim/after/ftplugin/crontab.vim
if has("mac")
setlocal nowritebackup
endif
I'd like to add to this the enormously simple, but oh so easily made mistake of writing:
this.state.something = 'changed';
... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:
this.setState({something: 'changed'});
React only triggers a re-render if you use setState
to update the state.
I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js
Yes. std::exception
is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent document on good style for exceptions and error handling. It's worth a read.
For git repositories, to download the latest commit, you can use:
https://bitbucket.org/owner/repository/get/HEAD.zip
For mercurial repositories:
Try This
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
if (input.checked) {
alert("checked");
} else {
alert("You didn't check it.");
}
}
input.onchange = check;
check();
}
</script>
Here is code
DatabaseMyHandler.class
public class DatabaseMyHandler extends SQLiteOpenHelper {
private SQLiteDatabase myDataBase;
private Context context = null;
private static String TABLE_NAME = "customer";
public static final String DATABASE_NAME = "Student.db";
public final static String DATABASE_PATH = "/data/data/com.pkgname/databases/";
public static final int DATABASE_VERSION = 2;
public DatabaseMyHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
try {
createDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
myDataBase = sqLiteDatabase;
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
//Check database already exists or not
private boolean checkDatabaseExists() {
boolean checkDB = false;
try {
String PATH = DATABASE_PATH + DATABASE_NAME;
File dbFile = new File(PATH);
checkDB = dbFile.exists();
} catch (SQLiteException e) {
}
return checkDB;
}
//Create a empty database on the system
public void createDatabase() throws IOException {
boolean dbExist = checkDatabaseExists();
if (dbExist) {
Log.v("DB Exists", "db exists");
}
boolean dbExist1 = checkDatabaseExists();
if (!dbExist1) {
this.getWritableDatabase();
try {
this.close();
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
//Copies your database from your local assets-folder to the just created empty database in the system folder
private void copyDataBase() throws IOException {
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
InputStream myInput = context.getAssets().open(DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
//Open Database
public void openDatabase() throws SQLException {
String PATH = DATABASE_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(PATH, null, SQLiteDatabase.OPEN_READWRITE);
}
//for insert data into database
public void insertCustomer(String customer_id, String email_id, String password, String description, int balance_amount) {
try {
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("customer_id", customer_id);
contentValues.put("email_id", email_id);
contentValues.put("password", password);
contentValues.put("description", description);
contentValues.put("balance_amount", balance_amount);
db.insert(TABLE_NAME, null, contentValues);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<ModelCreateCustomer> getLoginIdDetail(String email_id, String password) {
ArrayList<ModelCreateCustomer> result = new ArrayList<ModelCreateCustomer>();
//boolean flag = false;
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE email_id='" + email_id + "' AND password='" + password + "'";
try {
openDatabase();
Cursor cursor = myDataBase.rawQuery(selectQuery, null);
//cursor.moveToFirst();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
ModelCreateCustomer model = new ModelCreateCustomer();
model.setId(cursor.getInt(cursor.getColumnIndex("id")));
model.setCustomerId(cursor.getString(cursor.getColumnIndex("customer_id")));
model.setCustomerEmailId(cursor.getString(cursor.getColumnIndex("email_id")));
model.setCustomerPassword(cursor.getString(cursor.getColumnIndex("password")));
model.setCustomerDesription(cursor.getString(cursor.getColumnIndex("description")));
model.setCustomerBalanceAmount(cursor.getInt(cursor.getColumnIndex("balance_amount")));
result.add(model);
}
while (cursor.moveToNext());
}
Toast.makeText(context, "Login Successfully", Toast.LENGTH_SHORT).show();
}
// Log.e("Count", "" + cursor.getCount());
cursor.close();
myDataBase.close();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public void updateCustomer(String id, String email_id, String description, int balance_amount) {
try {
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("email_id", email_id);
contentValues.put("description", description);
contentValues.put("balance_amount", balance_amount);
db.update(TABLE_NAME, contentValues, "id=" + id, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Customer.class
public class Customer extends AppCompatActivity{
private DatabaseMyHandler mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
mydb = new DatabaseMyHandler(CreateCustomerActivity.this);
mydb.insertCustomer("1", "[email protected]", "123", "test", 100);
}
}
I ran into a case where I got that error message and had
Foo foo(Bar());
and was basically trying to pass in a temporary Bar object to the Foo constructor. Turns out the compiler was translating this to
Foo foo(Bar(*)());
that is, a function declaration whose name is foo that returns a Foo that takes in an argument -- a function pointer returning a Bar with 0 arguments. When passing in temporaries like this, better to use Bar{}
instead of Bar()
to eliminate ambiguity.
For basic, non-nested hashes, Rails/ActiveSupport has Object#to_query
.
>> {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
>> CGI.unescape({:a => "a", :b => ["c", "d", "e"]}.to_query)
=> "a=a&b[]=c&b[]=d&b[]=e"
http://api.rubyonrails.org/classes/Object.html#method-i-to_query
Do the following..
Right-click on your project--> select properties-----> select Java Compilers
You wills see this window
Now check the checkbox ---> enable project specific settings.
Now set the compiler compliance level to 1.6
Apply then Ok
now clean your project and you are good to go
I think this should do the work:
File dir = new File(dirname);
String[] files = dir.list();
This way you have files and dirs. Now use recursion and do the same for dirs (File
class has isDirectory()
method).
As stated earlier by Jamie Dixon, a floated <div>
is taken out of normal flow. All content that is still within normal flow will ignore it completely and not make space for it.
Try putting a different colored border border:solid 1px orange;
around each of your <div>
elements to see what they're doing. You might start by removing the floats and putting some dummy text inside the div. Then style them one at a time to get the desired layout.
date
command didnt provide milli seconds on OS X, so used an alias from python
millis(){ python -c "import time; print(int(time.time()*1000))"; }
OR
alias millis='python -c "import time; print(int(time.time()*1000))"'
EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.
$ time date +%s%N
1597103627N
date +%s%N 0.00s user 0.00s system 63% cpu 0.006 total
Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date
).
On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date
)
$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))" 0.03s user 0.01s system 83% cpu 0.053 total
I figured awk
is lightweight than python
, so awk
takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):
$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}' 0.00s user 0.00s system 74% cpu 0.010 total
I had something simular: I have an attribute picture in my model, this contains the location of the file in the Storage folder. The image must be returned base64 encoded
//Add extra attribute
protected $attributes = ['picture_data'];
//Make it available in the json response
protected $appends = ['picture_data'];
//implement the attribute
public function getPictureDataAttribute()
{
$file = Storage::get($this->picture);
$type = Storage::mimeType($this->picture);
return "data:" . $type . ";base64," . base64_encode($file);
}
From Excel Macro Security - www.excelfunctions.net:
Macro Security in Excel 2007, 2010 & 2013:
.....
The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :
'Disable all macros without notification'
This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Disable all macros with notification'
This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.
'Disable all macros except digitally signed macros'
This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Enable all macros'
This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.
If you trust the macros and are ok with enabling them, select this option:
'Enable all macros'
and this dialog box should not show up for macros.
As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.
Cause they're not equal, ie: they're different arrays with equal elements inside.
Try using Arrays.equals()
or Arrays.deepEquals()
.
You can give it a property display block; so it will behave like a div and have its own line
CSS:
.feature_desc {
display: block;
....
}
@Lauren?iu Dascalu's answer explains how / why you get a ClassCastException.
Your exception message looks rather suspicious to me, but it might help you to know that "[Lcom.rsa.authagent.authapi.realmstat.AUTHw" means that the actual type of the object that you were trying to cast was com.rsa.authagent.authapi.realmstat.AUTHw[]
; i.e. it was an array object.
Normally, the next steps to solving a problem like this are:
You can check the socket.connected
property:
var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
console.log('check 2', socket.connected);
});
It's updated dynamically, if the connection is lost it'll be set to false
until the client picks up the connection again. So easy to check for with setInterval
or something like that.
Another solution would be to catch disconnect
events and track the status yourself.
I had the same error, but in my case, it was because I had too many containers running (about 220).
Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling
codes if you want to use.
If you are a linux user Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
Call the following component like so:
<BackButton history={this.props.history} />
And here is the component:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class BackButton extends Component {
constructor() {
super(...arguments)
this.goBack = this.goBack.bind(this)
}
render() {
return (
<button
onClick={this.goBack}>
Back
</button>
)
}
goBack() {
this.props.history.goBack()
}
}
BackButton.propTypes = {
history: PropTypes.object,
}
export default BackButton
I'm using:
"react": "15.6.1"
"react-router": "4.2.0"
There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.
And then you can copy for example the file "test.txt" from a remote host to the local host
scp [email protected]:test.txt /local/dir
@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.
In UNIX, absolute paths must start with '/'.
This is browser specific behavior and is a way for making filling up forms more convenient to users (like reloading the page when an error has been encountered and not losing what they just typed). So there is no sure way to disable this across browsers short of setting the default values on page load using javascript.
Firefox though seems to disable this feature when you specify the header:
Cache-Control: no-store
See this question.
QUESTION:
What does =>
mean?
ANSWER:
=>
Is the symbol we humans decided to use to separate "Key" => "Value"
pairs in Associative Arrays.
ELABORATING:
To understand this, we have to know what Associative Arrays are. The first thing that comes up when a conventional programmer thinks of an array (in PHP) would be something similar to:
$myArray1 = array(2016, "hello", 33);//option 1
$myArray2 = [2016, "hello", 33];//option 2
$myArray3 = [];//option 3
$myArray3[] = 2016;
$myArray3[] = "hello";
$myArray3[] = 33;
Where as, if we wanted to call the array in some later part of the code, we could do:
echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello
So far so good. However, as humans, we might find it hard to remember that index [0]
of the array is the value of the year 2016, index [1]
of the array is a greetings, and index [2]
of the array is a simple integer value. The alternative we would then have is to use what is called an Associative Array. An Associative array has a few differences from a Sequential Array
(which is what the previous cases were since they increment the index used in a predetermined sequence, by incrementing by 1 for each following value).
Differences (between a sequential and associative array):
Durring the declaration of an Associative Array, you don't only include the value
of what you want to put in the array, but you also put the index value (called the key
) which you want to use when calling the array in later parts of the code. The following syntax is used during it's declaration: "key" => "value"
.
When using the Associative Array, the key
value would then be placed inside the index of the array to retrieve the desired value
.
For instance:
$myArray1 = array(
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33);//option 1
$myArray2 = [
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33];//option 2
$myArray3 = [];//option 3
$myArray3["Year"] = 2016;
$myArray3["Greetings"] = "hello";
$myArray3["Integer_value"] = 33;
And now, to receive the same output as before, the key
value would be used in the arrays index:
echo $myArray1["Greetings"];// output: hello
echo $myArray2["Greetings"];// output: hello
echo $myArray3["Greetings"];// output: hello
FINAL POINT:
So from the above example, it is pretty easy to see that the =>
symbol is used to express the relationship of an Associative Array between each of the key
and value
pairs in an array DURING the initiation of the values within the array.
I am a VIMer. I can do some rare Hex edits with:
:%!xxd
to switch into hex mode
:%!xxd -r
to exit from hex mode
But I strongly recommend ht
apt-cache show ht
Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>
Homepage: http://hte.sourceforge.net/
Note: The package is called ht
, whereas the executable is named hte
after the package was installed.
As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.
It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:
Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931
And in Java 8 Hotspot, Permanent Generation has been completely removed.
Have you attempted the Asp:Table?
<asp:Table ID="myTable" runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell>Name</asp:TableCell>
<asp:TableCell>Task</asp:TableCell>
<asp:TableCell>Hours</asp:TableCell>
</asp:TableRow>
</asp:Table>
You can then add rows as you need to in the script by creating them and adding them to myTable.Rows
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = "blah blah blah";
row.Cells.Add(cell1);
myTable.Rows.Add(row);
Given your question description though, I'd say you'd be better off using a GridView or Repeater as mentioned by @Kirk Woll.
EDIT - Also, if you want to learn without buying books here are a few sites you absolutely need to become familiar with:
Scott Guthrie's Blog
4 Guys from Rolla
MSDN
Code Project Asp.Net
You can download from below link. ftp://ftp.comtrol.com/dev_mstr/sdk/other/1800136.tar.gz After downloading just extract the image and install.
Check out ALL_TRIGGERS:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#i1592586
What is the package name of your class? If there is no package name, then most likely the solution is:
java -cp FileManagement Main
This is my powershell newbie way of doing this
if ((Test-Path ".\Desktop\checkfile.txt") -ne "True") {
Write-Host "Damn it"
} else {
Write-Host "Yay"
}
Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way
var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";
for (var key in foo) {
console.log(key);
}
Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.
EDIT:
In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -
You need to use an older version of the data connectivity driver (2007 Office System Driver: Data Connectivity Components) and select Excel version 2007-2010 in the connection manager configuration window. I assume the newest data connectivity driver for Office 2016 is corrupt
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
In Spring Web 4.3.6 I also see
public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables)
That means you don't have to create an ugly map
So if you have this url
http://my-url/action?param1={param1}¶m2={param2}
You can either do
restTemplate.getForObject(url, Response.class, param1, param2)
or
restTemplate.getForObject(url, Response.class, param [])
r = list(qs[:1])
if r:
return r[0]
return None
Also you can use LINQ's Select Method:
var source = new[] { "Line 1", "Line 2" };
var result = source.Select(s => s + " roxxors");
Read more here Enumerable.Select Method
Composition to the rescue!
Given the reason, rather than invoking actions across controllers one should design controllers to seperate shared and custom parts of the code. This will help to avoid both - code duplication and breaking MVC pattern.
Although that can be done in a number of ways, using concerns (composition) is a good practice.
# controllers/a_controller.rb
class AController < ApplicationController
include Createable
private def redirect_url
'one/url'
end
end
# controllers/b_controller.rb
class BController < ApplicationController
include Createable
private def redirect_url
'another/url'
end
end
# controllers/concerns/createable.rb
module Createable
def create
do_usefull_things
redirect_to redirect_url
end
end
Hope that helps.
If you are developing and testing in Firefox, there's a plug-in called "ReloadEvery" is available, which allows you to reload the page at the specified intervals.
Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:
<form action="postpage.php" method="POST" id="postForm" >
<div id="flash_success"></div>
name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />
<input type="submit" name="btn" value="Submit" />
</form>
<script>
var options = {
target: '#flash_success', // your response show in this ID
beforeSubmit: callValidationFunction,
success: YourResponseFunction
};
// bind to the form's submit event
jQuery('#postForm').submit(function() {
jQuery(this).ajaxSubmit(options);
return false;
});
});
function callValidationFunction()
{
// validation code for your form HERE
}
function YourResponseFunction(responseText, statusText, xhr, $form)
{
if(responseText=='success')
{
$('#flash_success').html('Your Success Message Here!!!');
$('body,html').animate({scrollTop: 0}, 800);
}else
{
$('#flash_success').html('Error Msg Here');
}
}
</script>
Globally install Composer on OS X 10.11 El Capitan
This command will NOT work in OS X 10.11:
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/bin --filename=composer
Instead, let's write to the /usr/local/bin path for the user:
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
Now we can access the composer command globally, just like before.
floor a;
floor b;
a = -0.340515;
so what to do?
b = 65565 +a;
a = 65565 -b;
or
if(a < 0){
a = 65565-(65565+a);}
SELECT
SUBSTRING( '[email protected]', charindex('@','[email protected]',1) + 1, charindex('.','[email protected]',1) - charindex('@','[email protected]',1) - 1 )
Sometimes it can be tricky to use raw html. Mostly because of XSS vulnerability. If that is a concern, but you still want to use raw html, you can encode the scary parts.
@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")
Results in
(<b><script>console.log('insert')</script>Hello</b>)
Great and exhaustive answerby @Kev!
Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location>
tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.
Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut
is in minutes, while the request executionTimeout
is in seconds!
And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).
<configuration>
...
<compilation debug="false" ...>
... other stuff ..
<location path="~/Admin/SomePage.aspx">
<system.web>
<sessionState timeout="240" />
<httpRuntime executionTimeout="14400" />
</system.web>
</location>
...
</configuration>
Change to,
import {MaterialModule} from '@angular/material'
;
I just had the same issue and solved it by changing
src: url("Roboto-Medium-webfont.eot?#iefix")
to
src: url("Roboto-Medium-webfont.eot?#iefix") format('embedded-opentype')
The modern way:
pip install -U requests[socks]
then
import requests
resp = requests.get('http://go.to',
proxies=dict(http='socks5://user:pass@host:port',
https='socks5://user:pass@host:port'))
just remove "520_"
utf8mb4_unicode_520_ci
? utf8mb4_unicode_ci
How about this way?
package main
import (
"fmt"
"errors"
)
type Item struct {
Value int
Name string
}
var items []Item = []Item{{Value:0, Name:"zero"},
{Value:1, Name:"one"},
{Value:2, Name:"two"}}
func main() {
var err error
v := Get(3, &err).Value
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
}
func Get(value int, err *error) Item {
if value > (len(items) - 1) {
*err = errors.New("error")
return Item{}
} else {
return items[value]
}
}
What I sometimes do is I create another dictionary just to be able whatever I feel I need to access as string. Then I iterate over multiple dictionaries matching keys to build e.g. a table with first column as description.
dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
dict_values = {'key1': 0, 'key2': 1}
for key, value in dict_names.items():
print('{0} {1}'.format(dict_names[key], dict_values[key])
You can easily do for a huge amount of dictionaries to match data (I like the fact that with dictionary you can always refer to something well known as the key name)
yes I use dictionaries to store results of functions so I don't need to run these functions everytime I call them just only once and then access the results anytime.
EDIT: in my example the key name does not really matter (I personally like using the same key names as it is easier to go pick a single value from any of my matching dictionaries), just make sure the number of keys in each dictionary is the same
How about this:
public static long nextLong(@NonNull Random r, long min, long max) {
if (min > max)
throw new IllegalArgumentException("min>max");
if (min == max)
return min;
long n = r.nextLong();
//abs (use instead of Math.abs, which might return min value) :
n = n == Long.MIN_VALUE ? 0 : n < 0 ? -n : n;
//limit to range:
n = n % (max - min);
return min + n;
}
?
This code works for both IE 7 and the latest version of Mozilla although the default setting in mozilla doesnt allow to close a window through javascript.
Here is the code:
function F11() { window.open('','_parent',''); window.open("login.aspx", "", "channelmode"); window.close(); }
To change the default setting :
1.type"about:config " in your firefox address bar and enter;
2.make sure your "dom.allow_scripts_to_close_windows" is true
Unit Testing - As the name suggests, this method tests at the object level. Individual software components are tested for any errors. Knowledge of the program is needed for this test and the test codes are created to check if the software behaves as it is intended to.
Functional Testing - Is carried out without any knowledge of the internal working of the system. The tester will try to use the system by just following requirements, by providing different inputs and testing the generated outputs. This test is also known as closed-box testing or black-box.
Acceptance Testing - This is the last test that is conducted before the software is handed over to the client. It is carried out to ensure that the developed software meets all the customer requirements. There are two types of acceptance testing - one that is carried out by the members of the development team, known as internal acceptance testing (Alpha testing), and the other that is carried out by the customer or end user known as (Beta testing)
Integration Testing - Individual modules that are already subjected to unit testing are integrated with one another. Generally the two approachs are followed :
1) Top-Down
2) Bottom-Up
sys.path
. See site
module.A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/
Thanks, @lampShaded for your answer.
In your API/URL directly use http://10.0.2.2:[your port]/
and under emulator setting add the proxy address as 10.0.2.2 with the port number. For more, you can visit: https://developer.android.com/studio/run/emulator-networking.html
You can use
my_array=( $(<command>) )
to store the output of command <command>
into the array my_array
.
You can access the length of that array using
my_array_length=${#my_array[@]}
Now the length is stored in my_array_length
.
Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.
interface IName {
firstName: string
lastName?: string
}
function sayName(params: IName) {
const { firstName, lastName = "Smith" } = params
const fullName = `${firstName} ${lastName}`
console.log("FullName-> ", fullName)
}
sayName({ firstName: "Bob" })
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
parameter?: type
is a shorthand for parameter: type | undefined
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
You can find what you're looking for in the information schema: SQL Server 2005 System Tables and Views I think you need SQL Server 2005 or higher to use the approach described in this article, but a similar method can be used for earlier versions.
It's a warning, not an error. It occurs because fsevents
is an optional dependency, used only when project is run on macOS environment (the package provides 'Native Access to Mac OS-X FSEvents').
And since you're running your project on Windows, fsevents
is skipped as irrelevant.
There is a PR to fix this behaviour here: https://github.com/npm/cli/pull/169
You can do this using Escape Sequence.
\"
So you will have to write something like this :
String name = "\"john\"";
You can learn about Escape Sequences from here.
I created a library to do this. It also has customizable colors!
It's very simple to use.
First you create a listener:
private SlideDateTimeListener listener = new SlideDateTimeListener() {
@Override
public void onDateTimeSet(Date date)
{
// Do something with the date. This Date object contains
// the date and time that the user has selected.
}
@Override
public void onDateTimeCancel()
{
// Overriding onDateTimeCancel() is optional.
}
};
Then you create and show the dialog:
new SlideDateTimePicker.Builder(getSupportFragmentManager())
.setListener(listener)
.setInitialDate(new Date())
.build()
.show();
I hope you find it useful.
You can do that I believe. It needs root permission. If you want to know where your apk files are stored, open a emulator and then go to
DDMS>File Explorer-> you can see a directory by name "data" -> Click on it and you will see a "app" folder.
Your apks are stored there. In fact just copying a apk directly to the folder works for me with emulators.
Just look at setAccessible()
method used to access private
fields and methods:
Now there is a lot more conditions required for this method to work. The only reason it doesn't break almost all of older software is that modules autogenerated from plain JARs are very permissive (open and export everything for everyone).
Your lastIndex += findStr.length();
was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always to findStr.length()
).
Here is the fixed version :
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += findStr.length();
}
}
System.out.println(count);
You are trying to load a XIB named DetailViewController
, but no such XIB exists or it's not member of your current target.
I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:
if (!$('#videoUploadFile').val()) {
alert('Please Upload File');
}
Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:
$(document).on("click", ":submit", function (e) {
if (!$('#videoUploadFile').val()) {
e.preventDefault();
alert('Please Upload File');
}
}
just to add another solution, particularly useful if you are using the new pandas assessors, other solutions will replace the original pandas and lose the assessors
df.drop(df.loc[df['line_race']==0].index, inplace=True)
The best way to do this in Angular and keep the code simple is to use this project.
https://www.npmjs.com/package/ngx-clipboard
<fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true"
ngxClipboard [cbContent]="target value here"
(cbOnSuccess)="copied($event)"></fa-icon>
You should take a look the reference documentation. It's well explained.
In your case, I think you cannot use between because you need to pass two parameters
Between - findByStartDateBetween … where x.startDate between ?1 and ?2
In your case take a look to use a combination of LessThan
or LessThanEqual
with GreaterThan
or GreaterThanEqual
LessThan - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
Acording to the docs:
Note The urllib2 module has been split across several modules in Python 3 named
urllib.request
andurllib.error
. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request
.
Note that if you're not using the full jquery UI library, this can be triggered if you're missing Widget, Menu, Position, or Core. There might be different dependencies depending on your version of jQuery UI
This is a fairly old question, but I though I should post this. It is a foreach loop for GNU C99.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define FOREACH_COMP(INDEX, ARRAY, ARRAY_TYPE, SIZE) \
__extension__ \
({ \
bool ret = 0; \
if (__builtin_types_compatible_p (const char*, ARRAY_TYPE)) \
ret = INDEX < strlen ((const char*)ARRAY); \
else \
ret = INDEX < SIZE; \
ret; \
})
#define FOREACH_ELEM(INDEX, ARRAY, TYPE) \
__extension__ \
({ \
TYPE *tmp_array_ = ARRAY; \
&tmp_array_[INDEX]; \
})
#define FOREACH(VAR, ARRAY) \
for (void *array_ = (void*)(ARRAY); array_; array_ = 0) \
for (size_t i_ = 0; i_ && array_ && FOREACH_COMP (i_, array_, \
__typeof__ (ARRAY), \
sizeof (ARRAY) / sizeof ((ARRAY)[0])); \
i_++) \
for (bool b_ = 1; b_; (b_) ? array_ = 0 : 0, b_ = 0) \
for (VAR = FOREACH_ELEM (i_, array_, __typeof__ ((ARRAY)[0])); b_; b_ = 0)
/* example's */
int
main (int argc, char **argv)
{
int array[10];
/* initialize the array */
int i = 0;
FOREACH (int *x, array)
{
*x = i;
++i;
}
char *str = "hello, world!";
FOREACH (char *c, str)
printf ("%c\n", *c);
return EXIT_SUCCESS;
}
This code has been tested to work with gcc, icc and clang on GNU/Linux.
Many questions get answers if we use .Net Reflector
to see the actual code of SqlConnection
:)
true
and sspi
are the same:
internal class DbConnectionOptions
...
internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
if ((CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true")) || CompareInsensitiveInvariant(stringValue, "yes"))
{
return true;
}
}
...
EDIT 20.02.2018 Now in .Net Core we can see its open source on github! Search for ConvertValueToIntegratedSecurityInternal method:
For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)
on the buttons object will assist.
Sample
Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);
"find '-maxdepth' " does not work with my old version of bash, therefore I use:
for f in $(ls) ; do if [ -f $f ] ; then echo $f ; fi ; done
See this example:
$(document).ready(function(){
$(".dropdown-toggle").css({
"color": "#212529",
"background-color": "#ffc107",
"border-color": "#ffc107"
});
$(".multiselect-selected-text").text('Select Tags');
});
You don't have to use Calendar. You can just play with timestamps :
Date d = initDate();//intialize your date to any date
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days
UPDATE DO NOT FORGET TO ADD "l" for long by the end of 1000.
Please consider the below WARNING:
Adding 1000*60*60*24
milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use.
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
You could also do
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
As an even easier solution, you could just use:
$results = $objects.Name
Which should fill $results
with an array of all the 'Name' property values of the elements in $objects
.
To solve the problem of:
E: Unable to locate package python-pip
you should do this. This works with the python2.7 and you not going to get disappointed by it.
follow the steps that are mention below.
go to get-pip.py and copy all the code from it.
open the terminal using CTRL + ALT +T
vi get-pip.py
paste the copied code here and then exit from the vi editor by pressing
ESC then :wq => press Enter
lastly, now run the code and see the magic
sudo python get-pip.py
It automatically adds the pip command in your Linux.
you can see the output of my machine
Suggestions:
true
would allow appending text into the File if it exists. println(...)
on your PrintWriter, writing your new text into the file.close()
of the PrintWriter should be in the try's finally block.e.g.,
PrintWriter pw = null;
try {
File file = new File("fubars.txt");
FileWriter fw = new FileWriter(file, true);
pw = new PrintWriter(fw);
pw.println("Fubars rule!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
Easy, no?
Section 6.5.8.6 of the C standard says:
Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.
No one mentioned that case classes have val
constructor parameters yet this is also the default for regular classes (which I think is an inconsistency in the design of Scala). Dario implied such where he noted they are "immutable".
Note you can override the default by prepending the each constructor argument with var
for case classes. However, making case classes mutable causes their equals
and hashCode
methods to be time variant.[1]
sepp2k already mentioned that case classes automatically generate equals
and hashCode
methods.
Also no one mentioned that case classes automatically create a companion object
with the same name as the class, which contains apply
and unapply
methods. The apply
method enables constructing instances without prepending with new
. The unapply
extractor method enables the pattern matching that others mentioned.
Also the compiler optimizes the speed of match
-case
pattern matching for case classes[2].
For some reason, you can not delete the .idea folder
The best way is
You can try using a regex like this:
$s = preg_replace('|/.*$|', '', $s);
sometimes, regex are slower though, so if performance is an issue, make sure to benchmark this properly and use an other alternative with substrings if it's more suitable for you.
Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.
The purpose of .iteritems()
was to use less memory space by yielding one result at a time while looping. I am not sure why Python 3 version does not support iteritems()
though it's been proved to be efficient than .items()
If you want to include a code that supports both the PY version 2 and 3,
try:
iteritems
except NameError:
iteritems = items
This can help if you deploy your project in some other system and you aren't sure about the PY version.
I think the best way would be using a SimpleDateFormat
object.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here
findIndex
retrieves only the first index which matches callback output. You can implement your own findIndexes
by extending Array , then casting your arrays to the new structure .
class EnhancedArray extends Array {_x000D_
findIndexes(where) {_x000D_
return this.reduce((a, e, i) => (where(e, i) ? a.concat(i) : a), []);_x000D_
}_x000D_
}_x000D_
/*----Working with simple data structure (array of numbers) ---*/_x000D_
_x000D_
//existing array_x000D_
let myArray = [1, 3, 5, 5, 4, 5];_x000D_
_x000D_
//cast it :_x000D_
myArray = new EnhancedArray(...myArray);_x000D_
_x000D_
//run_x000D_
console.log(_x000D_
myArray.findIndexes((e) => e===5)_x000D_
)_x000D_
/*----Working with Array of complex items structure-*/_x000D_
_x000D_
let arr = [{name: 'Ahmed'}, {name: 'Rami'}, {name: 'Abdennour'}];_x000D_
_x000D_
arr= new EnhancedArray(...arr);_x000D_
_x000D_
_x000D_
console.log(_x000D_
arr.findIndexes((o) => o.name.startsWith('A'))_x000D_
)
_x000D_
Try bootstrap-datepicker if you are using bootstrap.
For spring :
File inputFile = new ClassPathResource("\\chrome\\chromedriver.exe").getFile();
System.setProperty("webdriver.chrome.driver",inputFile.getCanonicalPath());
I'll interpret your question as two questions: 1) why ->
even exists, and 2) why .
does not automatically dereference the pointer. Answers to both questions have historical roots.
Why does ->
even exist?
In one of the very first versions of C language (which I will refer as CRM for "C Reference Manual", which came with 6th Edition Unix in May 1975), operator ->
had very exclusive meaning, not synonymous with *
and .
combination
The C language described by CRM was very different from the modern C in many respects. In CRM struct members implemented the global concept of byte offset, which could be added to any address value with no type restrictions. I.e. all names of all struct members had independent global meaning (and, therefore, had to be unique). For example you could declare
struct S {
int a;
int b;
};
and name a
would stand for offset 0, while name b
would stand for offset 2 (assuming int
type of size 2 and no padding). The language required all members of all structs in the translation unit either have unique names or stand for the same offset value. E.g. in the same translation unit you could additionally declare
struct X {
int a;
int x;
};
and that would be OK, since the name a
would consistently stand for offset 0. But this additional declaration
struct Y {
int b;
int a;
};
would be formally invalid, since it attempted to "redefine" a
as offset 2 and b
as offset 0.
And this is where the ->
operator comes in. Since every struct member name had its own self-sufficient global meaning, the language supported expressions like these
int i = 5;
i->b = 42; /* Write 42 into `int` at address 7 */
100->a = 0; /* Write 0 into `int` at address 100 */
The first assignment was interpreted by the compiler as "take address 5
, add offset 2
to it and assign 42
to the int
value at the resultant address". I.e. the above would assign 42
to int
value at address 7
. Note that this use of ->
did not care about the type of the expression on the left-hand side. The left hand side was interpreted as an rvalue numerical address (be it a pointer or an integer).
This sort of trickery was not possible with *
and .
combination. You could not do
(*i).b = 42;
since *i
is already an invalid expression. The *
operator, since it is separate from .
, imposes more strict type requirements on its operand. To provide a capability to work around this limitation CRM introduced the ->
operator, which is independent from the type of the left-hand operand.
As Keith noted in the comments, this difference between ->
and *
+.
combination is what CRM is referring to as "relaxation of the requirement" in 7.1.8: Except for the relaxation of the requirement that E1
be of pointer type, the expression E1->MOS
is exactly equivalent to (*E1).MOS
Later, in K&R C many features originally described in CRM were significantly reworked. The idea of "struct member as global offset identifier" was completely removed. And the functionality of ->
operator became fully identical to the functionality of *
and .
combination.
Why can't .
dereference the pointer automatically?
Again, in CRM version of the language the left operand of the .
operator was required to be an lvalue. That was the only requirement imposed on that operand (and that's what made it different from ->
, as explained above). Note that CRM did not require the left operand of .
to have a struct type. It just required it to be an lvalue, any lvalue. This means that in CRM version of C you could write code like this
struct S { int a, b; };
struct T { float x, y, z; };
struct T c;
c.b = 55;
In this case the compiler would write 55
into an int
value positioned at byte-offset 2 in the continuous memory block known as c
, even though type struct T
had no field named b
. The compiler would not care about the actual type of c
at all. All it cared about is that c
was an lvalue: some sort of writable memory block.
Now note that if you did this
S *s;
...
s.b = 42;
the code would be considered valid (since s
is also an lvalue) and the compiler would simply attempt to write data into the pointer s
itself, at byte-offset 2. Needless to say, things like this could easily result in memory overrun, but the language did not concern itself with such matters.
I.e. in that version of the language your proposed idea about overloading operator .
for pointer types would not work: operator .
already had very specific meaning when used with pointers (with lvalue pointers or with any lvalues at all). It was very weird functionality, no doubt. But it was there at the time.
Of course, this weird functionality is not a very strong reason against introducing overloaded .
operator for pointers (as you suggested) in the reworked version of C - K&R C. But it hasn't been done. Maybe at that time there was some legacy code written in CRM version of C that had to be supported.
(The URL for the 1975 C Reference Manual may not be stable. Another copy, possibly with some subtle differences, is here.)
I try 2 option:
Recently faced this issue on my production server. I had installed pyscopg2 using
sudo pip install psycopg2
It worked beautifully on my local, but had me for a run on my ec2 server.
sudo python -m pip install psycopg2
The above command worked for me there. Posting here just in case it would help someone in future.
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
after a lot of tries, I've read in other topics which someone said "delete all your apps and create it again". I did that but, as you can imagine, a new App will create a new Application ID on Facebook's page.
So, even after all the "set public things" it didn't work because the application ID was wrong in my code due to the creation of a new App on Facebook developer page.
So, as AndrewSmiley said above, you should remeber to update that in your app @strings
I prefer this solution, over the accepted answer by Michael Williamson, it catches changes to sources+inline files, then sources+headers, and finally sources only. Advantage here is that the whole library is not recompiled if only a a few changes are made. Not a huge consideration for a project with a couple of files, bur if you have 10 or a 100 sources, you will notice the difference.
COMMAND= gcc -Wall -Iinclude ...
%.o: %.cpp %.inl
$(COMMAND)
%.o: %.cpp %.hpp
$(COMMAND)
%.o: %.cpp
$(COMMAND)
For me, the problem was from ISP side. The Port number was not enabled by the Internet Service Provider. So asked them to enable the port number over my network and it started working.
Only to test: Connect to mobile hotspot and type ssh -T [email protected] or git pull.
If it works, then ask your ISP to enable the port.
I just had to revisit this issue today and found Get the source directory of a Bash script from within the script itself:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
There's more variants at the linked answer, e.g. for the case where the script itself is a symlink.
Try this instead:
echo "This is 02G05 a test string 20-Jul-2012" | sed 's/.* \([0-9]\+G[0-9]\+\) .*/\1/'
But note, if there is two pattern on one line, it will prints the 2nd.
http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>my_config.properties</value></property>
<property name="properties">
<props>
<prop key="entry.1">123</prop>
</props>
</property>
</bean>
You should kill all processes running on port 8081 by kill -9 $(lsof -i:8081)
If you want the name, use Martin's method. If you want to know whether it's an instance of a certain class:
boolean b = a instanceof String
I know this is an older issue, but I recently had the same problem and was having issues resolving it, despite attempting the DisplayUnlockCaptcha fix. This is how I got it alive.
Head over to Account Security Settings (https://www.google.com/settings/security/lesssecureapps) and enable "Access for less secure apps", this allows you to use the google smtp for clients other than the official ones.
Update
Google has been so kind as to list all the potential problems and fixes for us. Although I recommend trying the less secure apps setting. Be sure you are applying these to the correct account.
- If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.
- Sign in to your account from the web version of Gmail at https://mail.google.com. Once you’re signed in, try signing in
to the mail app again.- Visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If asked, enter the
letters in the distorted picture.- Your app might not support the latest security standards. Try changing a few settings to allow less secure apps access to your account.
- Make sure your mail app isn't set to check for new email too often. If your mail app checks for new messages more than once every 10
minutes, the app’s access to your account could be blocked.
If you are on ubuntu, just install pyqt5 with apt-get
command:
sudo apt-get install python3-pyqt5 # for python3
or
sudo apt-get install python-pyqt5 # for python2
However, on Ubuntu 14.04 the python-pyqt5 package is left out [source] and need to be installed manually [source]
There is a method specifically for this purpose:
data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
Using @angular/forms
when you use a <form>
tag it automatically creates a FormGroup
.
For every contained ngModel
tagged <input>
it will create a FormControl
and add it into the FormGroup
created above; this FormControl
will be named into the FormGroup
using attribute name
.
Example:
<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
<span>{{ f.controls['firstField']?.value }}</span>
</form>
Said this, the answer to your question follows.
When you mark it as standalone: true
this will not happen (it will not be added to the FormGroup
).
Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474
Docker Compose does not support the deploy
key. It's only respected when you use your version 3 YAML file in a Docker Stack.
This message is printed when you add the deploy
key to you docker-compose.yml
file and then run docker-compose up -d
WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use
docker stack deploy
to deploy to a swarm.
The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:
Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.
The download from java.com
which installs in /Library/Internet Plug-Ins
is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home
which you can then add to Eclipse via Preferences -> Java -> Installed JREs.
This is an annoying problem, that can take some time to find out the root case. The way you should proceed is @CommonsWare answer.
I faced this problem recently and found it hard to resolve.
My problem was i was including a library by "+" version in build.gradle. Latest version of library contained one of older dex and bang.
I reverted to older version of library and solved it.
It is good to run your androidDependencies and see what is really happening. Its also good to search in your build folder.
Above all Android Studio 2.2 provide in build features to track this problem.
Happy Coding Guys
Besides the settings for bash/ zsh terminal which are well covered by the other answers, if you want a permanent system environment variable for terminal + GUI applications (works for macOS Sierra; should work for El Capitan too):
launchctl setenv JAVA_HOME $(/usr/libexec/java_home -v 1.8)
(this will set JAVA_HOME to the latest 1.8 JDK, chances are you have gone through serveral updates e.g. javac 1.8.0_101, javac 1.8.0_131)
Of course, change 1.8 to 1.7 or 1.6 (really?) to suit your need and your system
I ran into a very similar issue.
I needed to use an old 32-bit DLL within a Web Application that was being developed on a 64-bit machine. I registered the 32-bit DLL into the windows\sysWOW64 folder using the version of regsrv32 in that folder.
Calls to the third party DLL worked from unit tests in Visual Studio but failed from the Web Application hosted in IIS on the same machine with the 80040154 error.
Changing the application pool to "Enable 32-Bit Applications" resolved the issue.
Just add to @Bert's solution to make it more clear:
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
const router = new VueRouter({
routes,
linkExactActiveClass: "active" // active class for *exact* links.
})
As one can see, this line should be removed:
linkActiveClass: "active", // active class for non-exact links.
this way, ONLY the current link is hi-lighted. This should apply to most of the cases.
David
You should add the ngDefaultControl attribute to your input like this:
<md-input
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
class="col-sm-4"
(blur)="addRecipient(recipient)"
ngDefaultControl>
</md-input>
Taken from comments in this post:
angular2 rc.5 custom input, No value accessor for form control with unspecified name
Note: For later versions of @angular/material:
Nowadays you should instead write:
<md-input-container>
<input
mdInput
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
(blur)="addRecipient(recipient)">
</md-input-container>
You should use <span>
, because as specified by the spec, <font>
has been deprecated and probably won't display as you intend.
Do you have any other projects in that solution ?(may be another project was referencing an old version) Usually in VS, dll dependency spans all projects in the solution.
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
In xcode 6, provisioning profiles are stored under Xcode > Preferences > accounts. Press "View details". On selecting your profile, you will get option to revoke it under settings(gear) icon below.
Here is a little help function. Great for when you have multiple languages!
private void setColor(TextView view, String fulltext, String subtext, int color) {
view.setText(fulltext, TextView.BufferType.SPANNABLE);
Spannable str = (Spannable) view.getText();
int i = fulltext.indexOf(subtext);
str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
I had similar issue when I had to install from github repo, but did not want to install git , etc.
The simple way to do it is using zip archive of the package. Add /zipball/master
to the repo URL:
$ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading master
Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...
This way you will make pip work with github source repositories.
If you have not yet pushed the commit anywhere, you can use git rebase -i
to remove that commit. First, find out how far back that commit is (approximately). Then do:
git rebase -i HEAD~N
The ~N
means rebase the last N
commits (N
must be a number, for example HEAD~10
). Then, you can edit the file that Git presents to you to delete the offending commit. On saving that file, Git will then rewrite all the following commits as if the one you deleted didn't exist.
The Git Book has a good section on rebasing with pictures and examples.
Be careful with this though, because if you change something that you have pushed elsewhere, another approach will be needed unless you are planning to do a force push.
Use the exec() method. For example, say you have a dictionary and you want to turn each key into a variable with its original dictionary value can do the following.
Python 2
>>> c = {"one": 1, "two": 2}
>>> for k,v in c.iteritems():
... exec("%s=%s" % (k,v))
>>> one
1
>>> two
2
Python 3
>>> c = {"one": 1, "two": 2}
>>> for k,v in c.items():
... exec("%s=%s" % (k,v))
>>> one
1
>>> two
2
For integers you can use Integer.signum()
Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
I was getting this same problem with Android SDK 23, while developing on a Mac OS X Yosemite Machine. It turned out that I did not have Java SDK 7.
Once I installed Java SDK 7 and pointed the SDK from with the Android Studio to the new SDK, everything worked for me.
Here are the steps that I followed:
1) Shutdown Android SDK
2) Install Java SDK for Mac OS X from http://www.oracle.com/technetwork/java/javase/downloads/index.html
3) Start the Android SDK and point the SDK for this project to the new 1.7 Java SDK by going to File -> Project Structure -> JDK Location
4) Restart Android Studio
Hope this help
words = "apple banana apple strawberry banana lemon"
w=words.split()
e=list(set(w))
word_freqs = {}
for i in e:
word_freqs[i]=w.count(i)
print(word_freqs)
Hope this helps!
Along with the points made by others, the $=
selector is the "ends with" selector. You will want the *=
(contains) selector, like so:
$('a').each(function() {
if ($(this).is('[href*="?"')) {
alert("Contains questionmark");
}
});
As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:
$('a[href*="?"]').each(function() {
alert("Contains questionmark");
});
According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:
dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"
You've forgot to define an onclick attribute to do something when the button is clicked, so nothing happening is the correct execution, see below;
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
----------------------
function_that_needs_strings(*my_list) # works!
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
@Corey - It just simply strips out all invalid characters. However, your comment made me think of the answer.
The problem was that many of the fields in my database are nullable. When using SqlBulkCopy, an empty string is not inserted as a null value. So in the case of my fields that are not varchar (bit, int, decimal, datetime, etc) it was trying to insert an empty string, which obviously is not valid for that data type.
The solution was to modify my loop where I validate the values to this (repeated for each datatype that is not string)
//--- convert decimal values
foreach (DataColumn DecCol in DecimalColumns)
{
if(string.IsNullOrEmpty(dr[DecCol].ToString()))
dr[DecCol] = null; //--- this had to be set to null, not empty
else
dr[DecCol] = Helpers.CleanDecimal(dr[DecCol].ToString());
}
After making the adjustments above, everything inserts without issues.
from StringIO import StringIO
out = StringIO()
out = tree.export_graphviz(clf, out_file=out)
print out.getvalue()
You can see a digraph Tree. Then, clf.tree_.feature
and clf.tree_.value
are array of nodes splitting feature and array of nodes values respectively. You can refer to more details from this github source.
LFTP is great, however it is Linux only. You can find the Windows port here. Never tried though.
Achtunq, it uses Cygwin, but everything is included in the bundle.
Usually all users will have write access to /tmp. Place the file to /tmp and then login to putty , then you can sudo and copy the file.
You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.
<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>
<style>
.div_r{
float:right;
color:red;
}
</style>
set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"
>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye
:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp
Set values using set commands before above lines.
I believe this helps you.
Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html
Easiest way I've found is with feDropShadow
.
<filter id="shadow" x="0" y="0" width="200%" height="200%">
<feDropShadow dx="40" dy="40" stdDeviation="35" flood-color="#ff0000" flood-opacity="1" />
</filter>
On the element:
<path d="..." filter="url(#shadow)"/>
In my case with jquery slider with 2 handles only following way worked.
$('#Slider').slider('option',{values: [0.15, 0.6]});
Here's A PHP Function I hobbled together from all of the above info for a similar purpose, namely adjusting image tag width and length properties on the fly ... a bit clunky, perhaps, but seems to work dependably:
function ReSizeImagesInHTML($HTMLContent,$MaximumWidth,$MaximumHeight) {
// find image tags
preg_match_all('/<img[^>]+>/i',$HTMLContent, $rawimagearray,PREG_SET_ORDER);
// put image tags in a simpler array
$imagearray = array();
for ($i = 0; $i < count($rawimagearray); $i++) {
array_push($imagearray, $rawimagearray[$i][0]);
}
// put image attributes in another array
$imageinfo = array();
foreach($imagearray as $img_tag) {
preg_match_all('/(src|width|height)=("[^"]*")/i',$img_tag, $imageinfo[$img_tag]);
}
// combine everything into one array
$AllImageInfo = array();
foreach($imagearray as $img_tag) {
$ImageSource = str_replace('"', '', $imageinfo[$img_tag][2][0]);
$OrignialWidth = str_replace('"', '', $imageinfo[$img_tag][2][1]);
$OrignialHeight = str_replace('"', '', $imageinfo[$img_tag][2][2]);
$NewWidth = $OrignialWidth;
$NewHeight = $OrignialHeight;
$AdjustDimensions = "F";
if($OrignialWidth > $MaximumWidth) {
$diff = $OrignialWidth-$MaximumHeight;
$percnt_reduced = (($diff/$OrignialWidth)*100);
$NewHeight = floor($OrignialHeight-(($percnt_reduced*$OrignialHeight)/100));
$NewWidth = floor($OrignialWidth-$diff);
$AdjustDimensions = "T";
}
if($OrignialHeight > $MaximumHeight) {
$diff = $OrignialHeight-$MaximumWidth;
$percnt_reduced = (($diff/$OrignialHeight)*100);
$NewWidth = floor($OrignialWidth-(($percnt_reduced*$OrignialWidth)/100));
$NewHeight= floor($OrignialHeight-$diff);
$AdjustDimensions = "T";
}
$thisImageInfo = array('OriginalImageTag' => $img_tag , 'ImageSource' => $ImageSource , 'OrignialWidth' => $OrignialWidth , 'OrignialHeight' => $OrignialHeight , 'NewWidth' => $NewWidth , 'NewHeight' => $NewHeight, 'AdjustDimensions' => $AdjustDimensions);
array_push($AllImageInfo, $thisImageInfo);
}
// build array of before and after tags
$ImageBeforeAndAfter = array();
for ($i = 0; $i < count($AllImageInfo); $i++) {
if($AllImageInfo[$i]['AdjustDimensions'] == "T") {
$NewImageTag = str_ireplace('width="' . $AllImageInfo[$i]['OrignialWidth'] . '"', 'width="' . $AllImageInfo[$i]['NewWidth'] . '"', $AllImageInfo[$i]['OriginalImageTag']);
$NewImageTag = str_ireplace('height="' . $AllImageInfo[$i]['OrignialHeight'] . '"', 'height="' . $AllImageInfo[$i]['NewHeight'] . '"', $NewImageTag);
$thisImageBeforeAndAfter = array('OriginalImageTag' => $AllImageInfo[$i]['OriginalImageTag'] , 'NewImageTag' => $NewImageTag);
array_push($ImageBeforeAndAfter, $thisImageBeforeAndAfter);
}
}
// execute search and replace
for ($i = 0; $i < count($ImageBeforeAndAfter); $i++) {
$HTMLContent = str_ireplace($ImageBeforeAndAfter[$i]['OriginalImageTag'],$ImageBeforeAndAfter[$i]['NewImageTag'], $HTMLContent);
}
return $HTMLContent;
}