GitHub is svn compatible so you can use svn ls
svn ls https://github.com/user/repository.git/branches/master/
BitBucket supports git archive so you can download tar archive and list archived files. It is not very efficient but works:
git archive [email protected]:repository HEAD directory | tar -t
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
Like Daniel said you can run python commands directly from Matlab using the py. command. To run any of the libraries you just have to make sure Malab is running the python environment where you installed the libraries:
On a Mac:
Open a new terminal window;
type: which python (to find out where the default version of python is installed);
Restart Matlab;
For example:
py.sys.version;
py.sklearn.cluster.dbscan
This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:
boolean
MySQLDatabase: BIT(1)
SQLiteDatabase: BOOLEAN
H2Database: BOOLEAN
PostgresDatabase: BOOLEAN
UnsupportedDatabase: BOOLEAN
DB2Database: SMALLINT
MSSQLDatabase: [bit]
OracleDatabase: NUMBER(1)
HsqlDatabase: BOOLEAN
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: BOOLEAN
SybaseDatabase: BIT
SybaseASADatabase: BIT
tinyint
MySQLDatabase: TINYINT
SQLiteDatabase: TINYINT
H2Database: TINYINT
PostgresDatabase: SMALLINT
UnsupportedDatabase: TINYINT
DB2Database: SMALLINT
MSSQLDatabase: [tinyint]
OracleDatabase: NUMBER(3)
HsqlDatabase: TINYINT
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: TINYINT
SybaseDatabase: TINYINT
SybaseASADatabase: TINYINT
int
MySQLDatabase: INT
SQLiteDatabase: INTEGER
H2Database: INT
PostgresDatabase: INT
UnsupportedDatabase: INT
DB2Database: INTEGER
MSSQLDatabase: [int]
OracleDatabase: INTEGER
HsqlDatabase: INT
FirebirdDatabase: INT
DerbyDatabase: INTEGER
InformixDatabase: INT
SybaseDatabase: INT
SybaseASADatabase: INT
mediumint
MySQLDatabase: MEDIUMINT
SQLiteDatabase: MEDIUMINT
H2Database: MEDIUMINT
PostgresDatabase: MEDIUMINT
UnsupportedDatabase: MEDIUMINT
DB2Database: MEDIUMINT
MSSQLDatabase: [int]
OracleDatabase: MEDIUMINT
HsqlDatabase: MEDIUMINT
FirebirdDatabase: MEDIUMINT
DerbyDatabase: MEDIUMINT
InformixDatabase: MEDIUMINT
SybaseDatabase: MEDIUMINT
SybaseASADatabase: MEDIUMINT
bigint
MySQLDatabase: BIGINT
SQLiteDatabase: BIGINT
H2Database: BIGINT
PostgresDatabase: BIGINT
UnsupportedDatabase: BIGINT
DB2Database: BIGINT
MSSQLDatabase: [bigint]
OracleDatabase: NUMBER(38, 0)
HsqlDatabase: BIGINT
FirebirdDatabase: BIGINT
DerbyDatabase: BIGINT
InformixDatabase: INT8
SybaseDatabase: BIGINT
SybaseASADatabase: BIGINT
float
MySQLDatabase: FLOAT
SQLiteDatabase: FLOAT
H2Database: FLOAT
PostgresDatabase: FLOAT
UnsupportedDatabase: FLOAT
DB2Database: FLOAT
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT
HsqlDatabase: FLOAT
FirebirdDatabase: FLOAT
DerbyDatabase: FLOAT
InformixDatabase: FLOAT
SybaseDatabase: FLOAT
SybaseASADatabase: FLOAT
double
MySQLDatabase: DOUBLE
SQLiteDatabase: DOUBLE
H2Database: DOUBLE
PostgresDatabase: DOUBLE PRECISION
UnsupportedDatabase: DOUBLE
DB2Database: DOUBLE
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT(24)
HsqlDatabase: DOUBLE
FirebirdDatabase: DOUBLE PRECISION
DerbyDatabase: DOUBLE
InformixDatabase: DOUBLE PRECISION
SybaseDatabase: DOUBLE
SybaseASADatabase: DOUBLE
decimal
MySQLDatabase: DECIMAL
SQLiteDatabase: DECIMAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL
MSSQLDatabase: [decimal](18, 0)
OracleDatabase: DECIMAL
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL
DerbyDatabase: DECIMAL
InformixDatabase: DECIMAL
SybaseDatabase: DECIMAL
SybaseASADatabase: DECIMAL
number
MySQLDatabase: numeric
SQLiteDatabase: NUMBER
H2Database: NUMBER
PostgresDatabase: numeric
UnsupportedDatabase: NUMBER
DB2Database: numeric
MSSQLDatabase: [numeric](18, 0)
OracleDatabase: NUMBER
HsqlDatabase: numeric
FirebirdDatabase: numeric
DerbyDatabase: numeric
InformixDatabase: numeric
SybaseDatabase: numeric
SybaseASADatabase: numeric
blob
MySQLDatabase: LONGBLOB
SQLiteDatabase: BLOB
H2Database: BLOB
PostgresDatabase: BYTEA
UnsupportedDatabase: BLOB
DB2Database: BLOB
MSSQLDatabase: [varbinary](MAX)
OracleDatabase: BLOB
HsqlDatabase: BLOB
FirebirdDatabase: BLOB
DerbyDatabase: BLOB
InformixDatabase: BLOB
SybaseDatabase: IMAGE
SybaseASADatabase: LONG BINARY
function
MySQLDatabase: FUNCTION
SQLiteDatabase: FUNCTION
H2Database: FUNCTION
PostgresDatabase: FUNCTION
UnsupportedDatabase: FUNCTION
DB2Database: FUNCTION
MSSQLDatabase: [function]
OracleDatabase: FUNCTION
HsqlDatabase: FUNCTION
FirebirdDatabase: FUNCTION
DerbyDatabase: FUNCTION
InformixDatabase: FUNCTION
SybaseDatabase: FUNCTION
SybaseASADatabase: FUNCTION
UNKNOWN
MySQLDatabase: UNKNOWN
SQLiteDatabase: UNKNOWN
H2Database: UNKNOWN
PostgresDatabase: UNKNOWN
UnsupportedDatabase: UNKNOWN
DB2Database: UNKNOWN
MSSQLDatabase: [UNKNOWN]
OracleDatabase: UNKNOWN
HsqlDatabase: UNKNOWN
FirebirdDatabase: UNKNOWN
DerbyDatabase: UNKNOWN
InformixDatabase: UNKNOWN
SybaseDatabase: UNKNOWN
SybaseASADatabase: UNKNOWN
datetime
MySQLDatabase: datetime
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: datetime
DB2Database: TIMESTAMP
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: datetime
time
MySQLDatabase: time
SQLiteDatabase: time
H2Database: time
PostgresDatabase: TIME WITHOUT TIME ZONE
UnsupportedDatabase: time
DB2Database: time
MSSQLDatabase: [time](7)
OracleDatabase: DATE
HsqlDatabase: time
FirebirdDatabase: time
DerbyDatabase: time
InformixDatabase: INTERVAL HOUR TO FRACTION(5)
SybaseDatabase: time
SybaseASADatabase: time
timestamp
MySQLDatabase: timestamp
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: timestamp
DB2Database: timestamp
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: timestamp
date
MySQLDatabase: date
SQLiteDatabase: date
H2Database: date
PostgresDatabase: date
UnsupportedDatabase: date
DB2Database: date
MSSQLDatabase: [date]
OracleDatabase: date
HsqlDatabase: date
FirebirdDatabase: date
DerbyDatabase: date
InformixDatabase: date
SybaseDatabase: date
SybaseASADatabase: date
char
MySQLDatabase: CHAR
SQLiteDatabase: CHAR
H2Database: CHAR
PostgresDatabase: CHAR
UnsupportedDatabase: CHAR
DB2Database: CHAR
MSSQLDatabase: [char](1)
OracleDatabase: CHAR
HsqlDatabase: CHAR
FirebirdDatabase: CHAR
DerbyDatabase: CHAR
InformixDatabase: CHAR
SybaseDatabase: CHAR
SybaseASADatabase: CHAR
varchar
MySQLDatabase: VARCHAR
SQLiteDatabase: VARCHAR
H2Database: VARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: VARCHAR
DB2Database: VARCHAR
MSSQLDatabase: [varchar](1)
OracleDatabase: VARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: VARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: VARCHAR
SybaseDatabase: VARCHAR
SybaseASADatabase: VARCHAR
nchar
MySQLDatabase: NCHAR
SQLiteDatabase: NCHAR
H2Database: NCHAR
PostgresDatabase: NCHAR
UnsupportedDatabase: NCHAR
DB2Database: NCHAR
MSSQLDatabase: [nchar](1)
OracleDatabase: NCHAR
HsqlDatabase: CHAR
FirebirdDatabase: NCHAR
DerbyDatabase: NCHAR
InformixDatabase: NCHAR
SybaseDatabase: NCHAR
SybaseASADatabase: NCHAR
nvarchar
MySQLDatabase: NVARCHAR
SQLiteDatabase: NVARCHAR
H2Database: NVARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: NVARCHAR
DB2Database: NVARCHAR
MSSQLDatabase: [nvarchar](1)
OracleDatabase: NVARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: NVARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: NVARCHAR
SybaseDatabase: NVARCHAR
SybaseASADatabase: NVARCHAR
clob
MySQLDatabase: LONGTEXT
SQLiteDatabase: TEXT
H2Database: CLOB
PostgresDatabase: TEXT
UnsupportedDatabase: CLOB
DB2Database: CLOB
MSSQLDatabase: [varchar](MAX)
OracleDatabase: CLOB
HsqlDatabase: CLOB
FirebirdDatabase: BLOB SUB_TYPE TEXT
DerbyDatabase: CLOB
InformixDatabase: CLOB
SybaseDatabase: TEXT
SybaseASADatabase: LONG VARCHAR
currency
MySQLDatabase: DECIMAL
SQLiteDatabase: REAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL(19, 4)
MSSQLDatabase: [money]
OracleDatabase: NUMBER(15, 2)
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL(18, 4)
DerbyDatabase: DECIMAL
InformixDatabase: MONEY
SybaseDatabase: MONEY
SybaseASADatabase: MONEY
uuid
MySQLDatabase: char(36)
SQLiteDatabase: TEXT
H2Database: UUID
PostgresDatabase: UUID
UnsupportedDatabase: char(36)
DB2Database: char(36)
MSSQLDatabase: [uniqueidentifier]
OracleDatabase: RAW(16)
HsqlDatabase: char(36)
FirebirdDatabase: char(36)
DerbyDatabase: char(36)
InformixDatabase: char(36)
SybaseDatabase: UNIQUEIDENTIFIER
SybaseASADatabase: UNIQUEIDENTIFIER
For reference, this is the groovy script I've used to generate this output:
@Grab('org.liquibase:liquibase-core:3.5.1')
import liquibase.database.core.*
import liquibase.datatype.core.*
def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType]
def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase]
datatypes.each {
def datatype = it.newInstance()
datatype.finishInitialization("")
println datatype.name
databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"}
println ''
}
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
I would try the program screen.
Many complicated answers here. Base on the accepted answer and the comment mentioning the 'ac'-'bb' issue assuming A=65 B=66 C=67, we could simply use the square of each integer that represent a char and solve the problem:
public boolean anagram(String s, String t) {
if(s.length() != t.length())
return false;
int value = 0;
for(int i = 0; i < s.length(); i++){
value += ((int)s.charAt(i))^2;
value -= ((int)t.charAt(i))^2;
}
return value == 0;
}
Just an example of event handler for Add event. Assumes that singleFileUploads option is enabled (which is the default). Read more jQuery File Upload documentation how to bound with add/fileuploadadd event. Inside loop you can use both vars this or file. An example of getting size property: this['size'] or file.size.
/**
* Handles Add event
*/
base.eventAdd = function(e, data) {
var errs = [];
var acceptFileTypes = /(\.|\/)(gif|jpe?g|png)$/i;
var maxFileSize = 5000000;
// Validate file
$.each(data.files, function(index, file) {
if (file.type.length && !acceptFileTypes.test(file.type)) {
errs.push('Selected file "' + file.name + '" is not alloawed. Invalid file type.');
}
if (this['size'] > maxFileSize) {
errs.push('Selected file "' + file.name + '" is too big, ' + parseInt(file.size / 1024 / 1024) + 'M.. File should be smaller than ' + parseInt(maxFileSize / 1024 / 1024) + 'M.');
}
});
// Output errors or submit data
if (errs.length > 0) {
alert('An error occured. ' + errs.join(" "));
} else {
data.submit();
}
};
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
Check that:
stateConnectionString="tcpip=server:port"
is correct. Also please check that default port (42424
) is available and your system does not have a firewall
that is blocking the port on your system
ssh -t 'command; bash -l'
will execute the command and then start up a login shell when it completes. For example:
ssh -t [email protected] 'cd /some/path; bash -l'
I couldn't find exactly what I was looking for so wrote something as basic as I could make it. The highlighted class could just be a background color.
var blinking = false; // global scope
function start_blinking() {
blinking = true;
blink();
}
function stop_blinking() {
blinking = false;
}
function blink(x=0) {
$("#element").removeClass("highlighted"); // default to not highlighted to account for the extra iteration after stopping
if (blinking) {
if (x%2 == 0) $("#element").addClass("highlighted"); // highlight on even numbers of x
setTimeout(function(){blink(++x)},500); // increment x and recurse
}
}
In Kotlin
evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
doTheLoginWork()
}
true
}
Partial Xml Code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginUserEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="actionDone"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
try below:
var temp_datetime_obj = new Date();
collection.find({
start_date:{
$gte: new Date(temp_datetime_obj.toISOString())
}
}).toArray(function(err, items) {
/* you can console.log here */
});
We use Log4Net at work as the logging provider, with a singleton wrapper for the log instance (although the singleton is under review, questioning whether they are a good idea or not).
We chose it for the following reasons:
I should mention, this is speaking from an ASP.NET development point of view
I can see some merits in using the Trace that is in the .NET framework but I'm not entirely sold on it, mainly because the components I work with don't really do any Trace calls. The only thing that I frequently use that does is System.Net.Mail
from what I can tell.
So we have a library which wraps log4net and within our code we just need stuff like this:
Logger.Instance.Warn("Something to warn about");
Logger.Instance.Fatal("Something went bad!", new Exception());
try {
var i = int.Parse("Hello World");
} catch(FormatException, ex) {
Logger.Instance.Error(ex);
}
Within the methods we do a check to see if the logging level is enabled, so you don't have redundant calls to the log4net API (so if Debug isn't enabled, the debug statements are ignored), but when I get some time I'll be updating it to expose those so that you can do the checks yourself. This will prevent evaluations being undertaken when they shouldn't, eg:
Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);
This will become:
if(Logger.DebugEnabled) Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);
(Save a bit of execusion time)
By default we log at two locations:
Files are done as rolling of each day or 10mb (IIRC). We don't use the EventLog as it can require higher security than we often want to give a site.
I find Notepad works just fine for reading logs.
You derive B
from A<B>
, so the first thing the compiler does, once it sees the definition of class B
is to try to instantiate A<B>
. To do this it needs to known B::mytype
for the parameter of action
. But since the compiler is just in the process of figuring out the actual definition of B
, it doesn't know this type yet and you get an error.
One way around this is would be to declare the parameter type as another template parameter, instead of inside the derived class:
template<typename Subclass, typename Param>
class A {
public:
void action(Param var) {
(static_cast<Subclass*>(this))->do_action(var);
}
};
class B : public A<B, int> { ... };
You can use the OfType
operator. It ignores null values in the source sequence. Just use the same type as MyProperty
and it won't filter out anything else.
// given:
// public T MyProperty { get; }
var nonNullItems = list.Select(x => x.MyProperty).OfType<T>();
I would advise against this though. If you want to pick non-null values, what can be more explicit than saying you want "the MyProperties from the list that are not null"?
the sort method contains an optional argument to pass a custom compare function.
Assuming you wanted an array of arrays:
var arr = [[3, "Mike", 20],[5, "Alex", 15]];
function compareName(a, b)
{
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
arr.sort(compareName);
Otherwise if you wanted an array of objects, you could do:
function compareName(a, b)
{
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
Create an alias for gcc with your favorite includes.
alias mygcc='gcc -I /whatever/'
For completion's sake, here's the snippet that creates the transport client using proper static method provided by InetSocketTransportAddress
:
Client esClient = TransportClient.builder()
.settings(settings)
.build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("143.79.236.xxx"), 9300));
onkeydown
is fired when the key is down (like in shortcuts; for example, in Ctrl+A
, Ctrl
is held 'down'.
onkeyup
is fired when the key is released (including modifier/etc keys)
onkeypress
is fired as a combination of onkeydown
and onkeyup
, or depending on keyboard repeat (when onkeyup
isn't fired). (this repeat behaviour is something that I haven't tested. If you do test, add a comment!)
textInput
(webkit only) is fired when some text is entered (for example, Shift+A
would enter uppercase 'A', but Ctrl+A
would select text and not enter any text input. In that case, all other events are fired)
try the following (in RowDataBound method of GridView):
protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
// this will only change the rows backgound not the column header
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col
e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col
}
}
I guess you are using an IDE (like Netbeans) which allows you to run the code even if certain classes are not compilable. During the application's runtime, if you access this class it would lead to this exception.
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
If you are logged in into psql on the Linux shell the command is:
\i fileName.sql
for an absolute path and
\ir filename.sql
for the relative path from where you have called psql.
JSON does not allow real line-breaks. You need to replace all the line breaks with \n
.
eg:
"first line
second line"
can saved with:
"first line\nsecond line"
Note:
for Python
, this should be written as:
"first line\\nsecond line"
where \\
is for escaping the backslash, otherwise python will treat \n
as
the control character "new line"
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
You can use the accept attribute along with the . It doesn't work in IE and Safari.
Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.
For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes
You can only extract path and filename from (1) a parameter of the BAT itself %1
, or (2) the parameter of a CALL %1
or (3) a local FOR variable %%a
.
in HELP CALL
or HELP FOR
you may find more detailed information:
%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file
And then try the following:
Either pass the string to be parsed as a parameter to a CALL
call :setfile ..\Desktop\fs.cfg
echo %file% = %filepath% + %filename%
goto :eof
:setfile
set file=%~f1
set filepath=%~dp1
set filename=%~nx1
goto :eof
or the equivalent, pass the filename as a local FOR variable
for %%a in (..\Desktop\fs.cfg) do (
set file=%%~fa
set filepath=%%~dpa
set filename=%%~nxa
)
echo %file% = %filepath% + %filename%
In regards to styled-components and react-router v4 you can do this:
import {NavLink} from 'react-router-dom'
const Link = styled(NavLink)`
background: blue;
&:hover {
color: white;
}
`
...
<Clickable><Link to="/somewhere">somewhere</Link></Clickable>
add:
import math
at beginning. and then use:
math.sqrt(num) # or any other function you deem neccessary
This worked for me. I have done like, when i click on the menu button, im adding or removing the class 'in' because by adding or removing that class the toggle is working by default. 'e.stopPropagation()' is to stop the default animation by bootstrap(i guess) you can also use the 'toggleClass' in place of add or remove class.
$('#ChangeToggle').on('click', function (e) {
if ($('.navbar-collapse').hasClass('in')) {
$('.navbar-collapse').removeClass('in');
e.stopPropagation();
} else {
$('.navbar-collapse').addClass('in');
$('.navbar-collapse').collapse();
}
});
Another pitfall with this is that command substitution — $()
— strips trailing newlines. Probably not always important, but if you really want to preserve exactly what was output, you'll have to use another line and some quoting:
RESULTX="$(./myscript; echo x)"
RESULT="${RESULTX%x}"
This is especially important if you want to handle all possible filenames (to avoid undefined behavior like operating on the wrong file).
Demo is here: jsfiddle
Try this :
//auto-hide-placeholder-text-upon-focus
if(!$.browser.webkit){
$("input").each(
function(){
$(this).data('holder',$(this).attr('placeholder'));
$(this).focusin(function(){
$(this).attr('placeholder','');
});
$(this).focusout(function(){
$(this).attr('placeholder',$(this).data('holder'));
});
});
}
"using" can also be used to resolve name space conflicts. See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/ for a short tutorial I wrote on the subject.
This is quite simple really.
-> This is centered Text <-
So taking that in mind you can apply this to the img syntax.
->![alt text](/link/to/img)<-
I needed a fat static lib for JsonKit so created a static lib project in Xcode and then ran this bash script in the project directory. So long as you've configured the xcode project with "Build active configuration only" turned off, you should get all architectures in one lib.
#!/bin/bash
xcodebuild -sdk iphoneos
xcodebuild -sdk iphonesimulator
lipo -create -output libJsonKit.a build/Release-iphoneos/libJsonKit.a build/Release-iphonesimulator/libJsonKit.a
Try this:
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);
Note that you can also tell logback to periodically scan your config file like this:
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
List<String> yourList = new ArrayList<>(map.keySet());
This is will do just fine.
I decided to use a recursive function because for me it was easier to follow the logic. Note that SQL Server has a default function recursion limit of 32, so this is only good for smaller workloads.
create function dbo._charindex_nth (
@FindThis varchar(8000),
@InThis varchar(max),
@StartFrom int,
@NthOccurence tinyint
)
returns bigint
as
begin
/*
Recursive helper used by dbo.charindex_nth to return the position of the nth occurance of @FindThis in @InThis
Who When What
PJR 160421 Initial
*/
declare @Pos bigint
if isnull(@NthOccurence, 0) <= 0 or isnull(@StartFrom, 0) <= 0
begin
select @Pos = 0
end else begin
if @NthOccurence = 1
begin
select @Pos = charindex(@FindThis, @InThis, @StartFrom)
end else begin
select @Pos = dbo._charindex_nth(@FindThis, @InThis, nullif(charindex(@FindThis, @InThis, @StartFrom), 0) + 1, @NthOccurence - 1)
end
end
return @Pos
end
create function dbo.charindex_nth (
@FindThis varchar(8000),
@InThis varchar(max),
@NthOccurence tinyint
)
returns bigint
as
begin
/*
Returns the position of the nth occurance of @FindThis in @InThis
Who When What
PJR 160421 Initial
*/
return dbo._charindex_nth(@FindThis, @InThis, 1, @NthOccurence)
end
declare @val varchar(max) = 'zzz_12_3_3_45.gif'
select dbo.charindex_nth('_', @val, 1) Underscore1
, dbo.charindex_nth('_', @val, 2) Underscore2
, dbo.charindex_nth('_', @val, 3) Underscore3
, dbo.charindex_nth('_', @val, 4) Underscore4
It's the conditional operator.
a ? b : c
It's a shortcut for IF/THEN/ELSE.
means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.
From long to DateTime: new DateTime(long ticks)
From DateTime to long: DateTime.Ticks
There is a more efficient way of doing this in Windows 7. SETX is installed by default and supports connecting to other systems.
To modify a remote system's global environment variables, you would use
setx /m /s HOSTNAME-GOES-HERE VariableNameGoesHere VariableValueGoesHere
This does not require restarting Windows Explorer.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetRight="-2dp">
<shape android:shape="rectangle">
<corners
android:bottomLeftRadius="4dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="4dp"
android:topRightRadius="0dp" />
<stroke
android:width="1dp"
android:color="@color/nasty_green" />
<solid android:color="@android:color/transparent" />
</shape>
</inset>
You can easily re-export the default import:
export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';
There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';
.
Check out the Arrays.sort methods:
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html
You should also really abstract finding the median into its own method, and just return the value to the calling method. This will make testing your code much easier.
This has to be done during your exe4j configuration. In the fourth step of Exe4j wizard which is Executable Info select> Advanced options select 32-bit or 64-bit. This worked well for me. or else install both JDK tool-kits x64 and x32 in your machine.
That's probably a requireJS module definition
Check here for more details
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
Two things you can do:
git checkout -b sillyname
git commit -am "silly message"
git checkout -
or
git stash -u
git branch sillyname stash@{0}
(git checkout -
<-- the dash is a shortcut for the previous branch you were on )
(git stash -u
<-- the -u
means that it also takes unstaged changes )
Try using the command: git status
It's mentioned by @watsonic that in Sublime Text 3 on Mac OS, starting with an empty selection, simply ^?G (AltF3 on Windows) does the trick, instead of ?D + ^?G in Sublime Text 2.
Beware that new Random()
is seeded on current timestamp.
If you want to generate just one number you can use:
new Random().Next( int.MinValue, int.MaxValue )
For more information, look at the Random class, though please note:
However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers
So do not use this code to generate a series of random number.
In LinearLayout
, use: android:layout_gravity="center"
.
In RelativeLayout
, use: android:layout_centerInParent="true"
.
$(function(){ _x000D_
$('.bordered').css({_x000D_
"border":"1px solid #EFEFEF",_x000D_
"margin":"0 auto",_x000D_
"width":"80%"_x000D_
});_x000D_
_x000D_
$('h1').css({_x000D_
"margin-left":"10px"_x000D_
});_x000D_
_x000D_
$('#myParagraph').css({_x000D_
"margin-left":"10px",_x000D_
"font-family":"sans-serif"_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
<h1>Header</h1>_x000D_
<p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
This will do it:
window.history.pushState(null,null,'https://www.google.com');
If the number of files you want to view fits within the maximum argument limit you can use globbing to get what you want, with recursion if you have globstar support.
For exactly 2 layers deep use: ls -d * */*
With globstar, for recursion use: ls -d **/*
The -d
argument to ls
tells it not to recurse directories passed as arguments (since you are using the shell globbing to do the recursion). This prevents ls
using its recursion formatting.
How to disable clicking another div click until first one popup div close
<p class="btn1">One</p>
<div id="box1" class="popup">
Test Popup Box One
<span class="close">X</span>
</div>
<!-- Two -->
<p class="btn2">Two</p>
<div id="box2" class="popup">
Test Popup Box Two
<span class="close">X</span>
</div>
<style>
.disabledbutton {
pointer-events: none;
}
.close {
cursor: pointer;
}
</style>
<script>
$(document).ready(function(){
//One
$(".btn1").click(function(){
$("#box1").css('display','block');
$(".btn2,.btn3").addClass("disabledbutton");
});
$(".close").click(function(){
$("#box1").css('display','none');
$(".btn2,.btn3").removeClass("disabledbutton");
});
</script>
OK I did it finally:
Sub CountUniqueRecords()
Dim Array() as variant, UniqueArray() as variant, UniqueNo as Integer,
Dim i as integer, j as integer, k as integer
Redim UnquiArray(1)
k= Upbound(array)
For i = 1 To k
For j = 1 To UniqueNo + 1
If Array(i) = UniqueArray(j) Then GoTo Nx
Next j
UniqueNo = UniqueNo + 1
ReDim Preserve UniqueArray(UniqueNo + 1)
UniqueArray(UniqueNo) = Array(i)
Nx:
Next i
MsgBox UniqueNo
End Sub
I went through the same issue recently while installing mysql on mac os x capitan. I did not find the correct answer here, so adding this answer.
MySql in current versions, generates a temporary password when you install mysql. Use this password to set a new password using the mysqladmin utility as below;
/usr/local/mysql/bin/mysqladmin -u root -p'<your temp password>' password '<your new password>'
Hope it helps you and others.
As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:
df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))
The .transform()
processes each column as a series. Contrary to .apply()
which passes the columns aggregated in a DataFrame.
Consequently you can apply the Series method map()
.
Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)
accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map()
method
Explicit cursors are rarely needed in plpgsql. Use the simpler and faster implicit cursor of a FOR
loop:
Note: Since table names are not unique per database, you have to schema-qualify table names to be sure. Also, I limit the function to the default schema 'public'. Adapt to your needs, but be sure to exclude the system schemas pg_*
and information_schema
.
Be very careful with these functions. They nuke your database. I added a child safety device. Comment the RAISE NOTICE
line and uncomment EXECUTE
to prime the bomb ...
CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
RETURNS void AS
$func$
DECLARE
_tbl text;
_sch text;
BEGIN
FOR _sch, _tbl IN
SELECT schemaname, tablename
FROM pg_tables
WHERE tableowner = _username
AND
-- dangerous, test before you execute!
RAISE NOTICE '%', -- once confident, comment this line ...
-- EXECUTE -- ... and uncomment this one
format('TRUNCATE TABLE %I.%I CASCADE', _sch, _tbl);
END LOOP;
END
$func$ LANGUAGE plpgsql;
format()
requires Postgres 9.1 or later. In older versions concatenate the query string like this:
'TRUNCATE TABLE ' || quote_ident(_sch) || '.' || quote_ident(_tbl) || ' CASCADE';
Since we can TRUNCATE
multiple tables at once we don't need any cursor or loop at all:
Aggregate all table names and execute a single statement. Simpler, faster:
CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
RETURNS void AS
$func$
BEGIN
-- dangerous, test before you execute!
RAISE NOTICE '%', -- once confident, comment this line ...
-- EXECUTE -- ... and uncomment this one
(SELECT 'TRUNCATE TABLE '
|| string_agg(format('%I.%I', schemaname, tablename), ', ')
|| ' CASCADE'
FROM pg_tables
WHERE tableowner = _username
AND schemaname = 'public'
);
END
$func$ LANGUAGE plpgsql;
Call:
SELECT truncate_tables('postgres');
You don't even need a function. In Postgres 9.0+ you can execute dynamic commands in a DO
statement. And in Postgres 9.5+ the syntax can be even simpler:
DO
$func$
BEGIN
-- dangerous, test before you execute!
RAISE NOTICE '%', -- once confident, comment this line ...
-- EXECUTE -- ... and uncomment this one
(SELECT 'TRUNCATE TABLE ' || string_agg(oid::regclass::text, ', ') || ' CASCADE'
FROM pg_class
WHERE relkind = 'r' -- only tables
AND relnamespace = 'public'::regnamespace
);
END
$func$;
About the difference between pg_class
, pg_tables
and information_schema.tables
:
About regclass
and quoted table names:
Create a "template" database (let's name it my_template
) with your vanilla structure and all empty tables. Then go through a DROP
/ CREATE DATABASE
cycle:
DROP DATABASE mydb;
CREATE DATABASE mydb TEMPLATE my_template;
This is extremely fast, because Postgres copies the whole structure on the file level. No concurrency issues or other overhead slowing you down.
If concurrent connections keep you from dropping the DB, consider:
While pidof
and pgrep
are great tools for determining what's running, they are both, unfortunately, unavailable on some operating systems. A definite fail safe would be to use the following: ps cax | grep command
The output on Gentoo Linux:
14484 ? S 0:00 apache2 14667 ? S 0:00 apache2 19620 ? Sl 0:00 apache2 21132 ? Ss 0:04 apache2
The output on OS X:
42582 ?? Z 0:00.00 (smbclient) 46529 ?? Z 0:00.00 (smbclient) 46539 ?? Z 0:00.00 (smbclient) 46547 ?? Z 0:00.00 (smbclient) 46586 ?? Z 0:00.00 (smbclient) 46594 ?? Z 0:00.00 (smbclient)
On both Linux and OS X, grep returns an exit code so it's easy to check if the process was found or not:
#!/bin/bash
ps cax | grep httpd > /dev/null
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
Furthermore, if you would like the list of PIDs, you could easily grep for those as well:
ps cax | grep httpd | grep -o '^[ ]*[0-9]*'
Whose output is the same on Linux and OS X:
3519 3521 3523 3524
The output of the following is an empty string, making this approach safe for processes that are not running:
echo ps cax | grep aasdfasdf | grep -o '^[ ]*[0-9]*'
This approach is suitable for writing a simple empty string test, then even iterating through the discovered PIDs.
#!/bin/bash
PROCESS=$1
PIDS=`ps cax | grep $PROCESS | grep -o '^[ ]*[0-9]*'`
if [ -z "$PIDS" ]; then
echo "Process not running." 1>&2
exit 1
else
for PID in $PIDS; do
echo $PID
done
fi
You can test it by saving it to a file (named "running") with execute permissions (chmod +x running) and executing it with a parameter: ./running "httpd"
#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
WARNING!!!
Please keep in mind that you're simply parsing the output of ps ax
which means that, as seen in the Linux output, it is not simply matching on processes, but also the arguments passed to that program. I highly recommend being as specific as possible when using this method (e.g. ./running "mysql"
will also match 'mysqld' processes). I highly recommend using which
to check against a full path where possible.
References:
You can use
@PostConstruct
public void init() {
// ...
}
Try this code using the hostip.info service:
$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;
// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);
echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);
To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.
var file = choofdlog.FileName; // for one file
or for multiple files
var files = choofdlog.FileNames; // for multiple files.
To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path
To specify a classpath for a single Java process, you can add a classpath option when you run the Java command.
In you command line. Use
java -cp "path/to/your/jar:." main
rather than just
java main
The option tells Java where to search for libraries.
1.Right click on your Database , 2.Then select properties . 3.Select the option in compatibility levels choose sql 2008[100] if you are working with Microsoft sql 2008.
4.Then select the file and write ( sa ) in owner`s textbox
100% works for me.
Use the below link to download IE Driver latest version
If you are splitting from Linux, you can still reassemble in Windows.
copy /b file1 + file2 + file3 + file4 filetogether
In case anyone else has the same issue as this on
Centos, try:
yum install python-lxml
Ubuntu
sudo apt-get install -y python-lxml
worked for me.
Just keep
Intent intent = new Intent(ProfileActivity.this,
LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.
Use this
using System;
using System.ComponentModel;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
public static class ObservableFactory
{
public static T Create<T>(T target)
{
if (!typeof(T).IsInterface)
throw new ArgumentException("Target should be an interface", "target");
var proxy = new Observable<T>(target);
return (T)proxy.GetTransparentProxy();
}
}
internal class Observable<T> : RealProxy, INotifyPropertyChanged, INotifyPropertyChanging
{
private readonly T target;
internal Observable(T target)
: base(ImplementINotify(typeof(T)))
{
this.target = target;
}
public override IMessage Invoke(IMessage msg)
{
var methodCall = msg as IMethodCallMessage;
if (methodCall != null)
{
return HandleMethodCall(methodCall);
}
return null;
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
IMessage HandleMethodCall(IMethodCallMessage methodCall)
{
var isPropertySetterCall = methodCall.MethodName.StartsWith("set_");
var propertyName = isPropertySetterCall ? methodCall.MethodName.Substring(4) : null;
if (isPropertySetterCall)
{
OnPropertyChanging(propertyName);
}
try
{
object methodCalltarget = target;
if (methodCall.MethodName == "add_PropertyChanged" || methodCall.MethodName == "remove_PropertyChanged"||
methodCall.MethodName == "add_PropertyChanging" || methodCall.MethodName == "remove_PropertyChanging")
{
methodCalltarget = this;
}
var result = methodCall.MethodBase.Invoke(methodCalltarget, methodCall.InArgs);
if (isPropertySetterCall)
{
OnPropertyChanged(methodCall.MethodName.Substring(4));
}
return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall);
}
catch (TargetInvocationException invocationException)
{
var exception = invocationException.InnerException;
return new ReturnMessage(exception, methodCall);
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanging(string propertyName)
{
var handler = PropertyChanging;
if (handler != null) handler(this, new PropertyChangingEventArgs(propertyName));
}
public static Type ImplementINotify(Type objectType)
{
var tempAssemblyName = new AssemblyName(Guid.NewGuid().ToString());
var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
tempAssemblyName, AssemblyBuilderAccess.RunAndCollect);
var moduleBuilder = dynamicAssembly.DefineDynamicModule(
tempAssemblyName.Name,
tempAssemblyName + ".dll");
var typeBuilder = moduleBuilder.DefineType(
objectType.FullName, TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract);
typeBuilder.AddInterfaceImplementation(objectType);
typeBuilder.AddInterfaceImplementation(typeof(INotifyPropertyChanged));
typeBuilder.AddInterfaceImplementation(typeof(INotifyPropertyChanging));
var newType = typeBuilder.CreateType();
return newType;
}
}
}
If you get this error in a context of creating ForeignKey relations between models. Example below raises AppRegistryNotReady: Models aren't loaded yet
error.
from my_app.models import Workspace
workspace = models.ForeignKey(Workspace)
Then please try to reffer to a model as a string.
from my_app.models import Workspace
# One of these two lines might fix the problem.
workspace = models.ForeignKey('Workspace')
workspace = models.ForeignKey('my_app.Workspace')
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
In the source header you can declare:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
It is described in the PEP 0263:
Then you can use UTF-8 in strings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
I got here looking for the inverse of your question, going from camel case to snake case. Use underscore for that (not decamelize):
AppUser.name.underscore # => "app_user"
or, if you already have a camel case string:
"AppUser".underscore # => "app_user"
or, if you want to get the table name, which is probably why you'd want the snake case:
AppUser.name.tableize # => "app_users"
According to ADO: ActiveX Data Objects, a book by Jason T. Roff, published by O'Reilly Media in 2001 (excellent diagram here), he says precisely what MOZILLA said.
(directly from page 7 of that book)
- ODBC provides access only to relational databases
- OLE DB provides the following features
- Access to data regardless of its format or location
- Full access to ODBC data sources and ODBC drivers
So it would seem that OLE DB interacts with SQL-based datasources THRU the ODBC driver layer.
I'm not 100% sure this image is correct. The two connections I'm not certain about are ADO.NET thru ADO C-api, and OLE DB thru ODBC to SQL-based data source (because in this diagram the author doesn't put OLE DB's access thru ODBC, which I believe is a mistake).
@object.as_json
as_json has very flexible way to configure complex object according to model relations
EXAMPLE
Model campaign belongs to shop and has one list
Model list has many list_tasks and each of list_tasks has many comments
We can get one json which combines all those data easily.
@campaign.as_json(
{
except: [:created_at, :updated_at],
include: {
shop: {
except: [:created_at, :updated_at, :customer_id],
include: {customer: {except: [:created_at, :updated_at]}}},
list: {
except: [:created_at, :updated_at, :observation_id],
include: {
list_tasks: {
except: [:created_at, :updated_at],
include: {comments: {except: [:created_at, :updated_at]}}
}
}
},
},
methods: :tags
})
Notice methods: :tags can help you attach any additional object which doesn't have relations with others. You just need to define a method with name tags in model campaign. This method should return whatever you need (e.g. Tags.all)
Official documentation for as_json
I had the same issue displaying my side navigation panel height to 100%.
My steps to fix it was to:
In the index.css file ------
.html {
height: 100%;
}
.body {
height:100%;
}
In the sidePanel.css (this was giving me issues):
.side-panel {
height: 100%;
position: fixed; <--- this is what made the difference and scaled to 100% correctly
}
Other attributes were taken out for clarity, but I think the issue lies with scaling the height to 100% in nested containers like how you are trying to scale height in your nested containers. The parent classes height will need to be applied the 100%. - What i'm curious about is why fixed: position corrects the scale and fails without it; this is something i'll learn eventually with some more practice.
I've been working with react for a week now and i'm a novice to web developing, but I wanted to share a fix that I discovered with scaling height to 100%; I hope this helps you or anyone who has a similar issue. Good luck!
Here's the 2020 answer for this:
#anchor {
scroll-margin-top: 100px;
}
Because it's widely supported!
You can also define a variable directly in the PowerShell command line and then execute the script. The variable will be defined there, too. This helped me in a case where I couldn't modify a signed script.
Example:
PS C:\temp> $stepsize = 30
PS C:\temp> .\itunesForward.ps1
with iTunesForward.ps1 being
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $stepsize
}
We can create method for it. Simply use it.
public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
self.layer.borderWidth = width
self.layer.cornerRadius = radius
self.layer.shouldRasterize = false
self.layer.rasterizationScale = 2
self.clipsToBounds = true
self.layer.masksToBounds = true
let cgColor: CGColor = color.cgColor
self.layer.borderColor = cgColor
}
above given methods are for if you have an web url ,but if you have an local html then you can have also html by this code
AssetManager mgr = mContext.getAssets();
try {
InputStream in = null;
if(condition)//you have a local html saved in assets
{
in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
}
else if(condition)//you have an url
{
URL feedURL = new URL(sURL);
in = feedURL.openConnection().getInputStream();}
// here you will get your html
String sHTML = streamToString(in);
in.close();
//display this html in the browser or web view
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static String streamToString(InputStream in) throws IOException {
if(in == null) {
return "";
}
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
}
return writer.toString();
}
Depends on the situation, you can also try using padding property here...
MyControl.Margin=new Padding(0,0,0,0);
DISTINCT
is the keyword
For me your query is correct
Just try to do this first
SELECT DISTINCT title,id FROM tbl_countries
Later on you can try with order by.
You can use String.getBytes()
which returns the byte[]
array.
In the previous answers Code coverage has been explained well . I am just adding some knowledge related to tools if your are working on iOS
and OSX
platforms, Xcode provides the facility to test and monitor code coverage.
Reference Links:
https://medium.com/zendesk-engineering/code-coverage-and-xcode-6b2fb8756a51
Both are helpful links for learning and exploring code coverage with Xcode.
Here's an example you can run as a batch script (copy-paste into a .bat file), using the SQLCMD utility in Sql Server client tools:
BACKUP:
echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%DATE:~-4%.%DATE:~7,2%.%DATE:~4,2%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=your server name here
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause
RESTORE:
echo off
cls
echo -- RESTORE DATABASE --
set /p BACKUPFILENAME=Enter backup file name:%CD%\
set /p DATABASENAME=Enter database name:
set SERVERNAME=your server name here
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"
:: WARNING - delete the database, suits me
:: sqlcmd -E -S %SERVERNAME% -d master -Q "IF EXISTS (SELECT * FROM sysdatabases WHERE name=N'%DATABASENAME%' ) DROP DATABASE [%DATABASENAME%]"
:: sqlcmd -E -S %SERVERNAME% -d master -Q "CREATE DATABASE [%DATABASENAME%]"
:: restore
sqlcmd -E -S %SERVERNAME% -d master -Q "RESTORE DATABASE [%DATABASENAME%] FROM DISK = N'%CD%\%BACKUPFILENAME%' WITH REPLACE"
:: remap user/login (http://msdn.microsoft.com/en-us/library/ms174378.aspx)
sqlcmd -E -S %SERVERNAME% -d %DATABASENAME% -Q "sp_change_users_login 'Update_One', 'login-name', 'user-name'"
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET MULTI_USER"
echo.
pause
In Chrome, you are supposed to be able to allow this capability with a runtime flag --allow-file-access-from-files
However, it looks like there is a problem with current versions of Chrome (37, 38) where this doesn't work unless you also pass the runtime flag --disable-web-security
That's an unacceptable solution, except perhaps as a short-term workaround, but it has been identified as an issue: https://code.google.com/p/chromium/issues/detail?id=379206
In eclipse go to the DDMS perspective and in the devices tab click the process you want to kill under the device you want to kill it on. You then just need to press the stop button and it should kill the process.
I'm not sure how you'd do this from the command line tool but there must be a way. Maybe you do it through the adb shell...
Mac OSX only
An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:
brew install chromedriver
That should put the chromedriver in your path and you should be all set.
CDATA
has no meaning at all in HTML.
CDATA
is an XML construct which sets a tag's contents that is normally #PCDATA - parsed character data, to be instead taken as #CDATA, that is, non-parsed character data. It is only relevant and valid in XHTML.
It is used in script
tags to avoid parsing <
and &
. In HTML, this is not needed, because in HTML, script
is already #CDATA.
Just for fun, this one also works.
a = num;
b = 0;
if (a % 10 == 0)
return a == 0;
do {
b = 10 * b + a % 10;
if (a == b)
return true;
a = a / 10;
} while (a > b);
return a == b;
If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.
<?xml version="1.0" ?>
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-access-from domain="*"/>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
please fill the @likeTablename param for search table.
now this parameter set to %tbltrans% for search all table contain tbltrans in name.
set @likeTablename to '%' to show all table.
declare @AllTableNames nvarchar(max);
select @AllTableNames=STUFF((select ' SELECT TABLE_CATALOG collate DATABASE_DEFAULT+''.''+TABLE_SCHEMA collate DATABASE_DEFAULT+''.''+TABLE_NAME collate DATABASE_DEFAULT as tablename FROM '+name+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' union '
FROM master.sys.databases
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
set @AllTableNames=left(@AllTableNames,len(@AllTableNames)-6)
declare @likeTablename nvarchar(200)='%tbltrans%';
set @AllTableNames=N'select tablename from('+@AllTableNames+N')at where tablename like '''+N'%'+@likeTablename+N'%'+N''''
exec sp_executesql @AllTableNames
You're allowed to have more than one return
statement, so it's legal to write
if (some_condition) {
return true;
}
return false;
It's also unnecessary to compare boolean values to true
or false
, so you can write
if (verifyPwd()) {
// do_task
}
Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.
boolean success = true;
if (some_condition) {
// Handle the condition.
success = false;
} else if (some_other_condition) {
// Handle the other condition.
success = false;
}
if (another_condition) {
// Handle the third condition.
}
// Do some more critical things.
return success;
The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.
Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).
Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.
Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.
So the relationships are:
There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.
Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.
One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.
I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.
Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like
$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});
The callback parameter will be filled in automatically by the browser, so don't worry.
On the server side ('validate.php') you would have something like this
<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>
OK, as others note, the best thing to do is to use java.util.concurrent
package. I highly recommend "Java Concurrency in Practice". It's a great book that covers almost everything you need to know.
As for your particular implementation, as I noted in the comments, don't start Threads from Constructors -- it can be unsafe.
Leaving that aside, the second implementation seem better. You don't want to put queues in static fields. You are probably just loosing flexibility for nothing.
If you want to go ahead with your own implementation (for learning purpose I guess?), supply a start()
method at least. You should construct the object (you can instantiate the Thread
object), and then call start()
to start the thread.
Edit: ExecutorService
have their own queue so this can be confusing.. Here's something to get you started.
public class Main {
public static void main(String[] args) {
//The numbers are just silly tune parameters. Refer to the API.
//The important thing is, we are passing a bounded queue.
ExecutorService consumer = new ThreadPoolExecutor(1,4,30,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100));
//No need to bound the queue for this executor.
//Use utility method instead of the complicated Constructor.
ExecutorService producer = Executors.newSingleThreadExecutor();
Runnable produce = new Produce(consumer);
producer.submit(produce);
}
}
class Produce implements Runnable {
private final ExecutorService consumer;
public Produce(ExecutorService consumer) {
this.consumer = consumer;
}
@Override
public void run() {
Pancake cake = Pan.cook();
Runnable consume = new Consume(cake);
consumer.submit(consume);
}
}
class Consume implements Runnable {
private final Pancake cake;
public Consume(Pancake cake){
this.cake = cake;
}
@Override
public void run() {
cake.eat();
}
}
Further EDIT:
For producer, instead of while(true)
, you can do something like:
@Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
//do stuff
}
}
This way you can shutdown the executor by calling .shutdownNow()
. If you'd use while(true)
, it won't shutdown.
Also note that the Producer
is still vulnerable to RuntimeExceptions
(i.e. one RuntimeException
will halt the processing)
The following does not return a response:
You must return anything like return afunction()
or return 'a string'
.
This can solve the issue
You have used some type errors. If you want to set 08/16/2011 to following pattern. It is wrong because,
mm stands for minutes, use MM as it is for Months
DD is wrong, it should be dd which represents Days
Try this to achieve the output you want to get ( Tue Aug 16 "Whatever Time" IST 2011
),
String date = "08/16/2011"; //input date as String
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); // date pattern
Date myDate = simpleDateFormat.parse(date); // returns date object
System.out.println(myDate); //outputs: Tue Aug 16 00:00:00 IST 2011
In Python, paths are relative to the current working directory, which in most cases is the directory from which you run your program. The current working directory is very likely not as same as the directory of your module file, so using a path relative to your current module file is always a bad choice.
Using absolute path should be the best solution:
import os
package_dir = os.path.dirname(os.path.abspath(__file__))
thefile = os.path.join(package_dir,'test.cvs')
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
My environment are:
pip install mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl
works for me.
import MySQLdb, sys
# --------------------------------------------------
# Connect to MySQL
# --------------------------------------------------
try:
db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database", charset='cp1251')
except MySQLdb.Error as e:
print ("Error %d: %s" % (e.args[0], e.args[1]))
sys.exit()
# Creating cursor
cursor = db.cursor()
Tested on Ubuntu:
sudo apt install git-extras
git-show-tree
This produces an effect similar to the 2 most upvoted answers here.
Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html
Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow
shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch
or manually via git branch --set-upstream-to=upstream_branch
).
git branch
you are on too!"Below is an image showing nested frames and the effect of different target values, followed by an explanation of the image.
Imagine a webpage containing 3 nested <iframe>
aka "frame"/"frameset". So:
Then target attributes have these effects:
target="_self"
, the link targets frame 1 (i.e. the link targets the frame containing the link (i.e. targets itself))target="_parent"
, the link targets frame 2 (i.e. the link targets the parent frame)target="_top"
, the link targets the initial webpage (i.e. the link targets the topmost/outermost frame; (in this case; the link skips past the grandparent frame 3))
target="_top"
, the link also targets the initial webpage (i.e. again, the link targets the topmost/outermost frame)target="_blank"
, the link targets an auxiliary browsing context, aka a "new window"/"new tab"
target="_blank"
; use the rel="noopener"
attributeThis script is neat and tidy. Set it up as a cron job and relax:
http://www.crucialwebhost.com/kb/magneto-log-and-cache-maintenance-script/
Here is complete article about streaming android camera video to a webpage.
Android Streaming Live Camera Video to Web Page
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
This will return query parameters as an associative array
var queryParams =[];
var query= document.location.search.replace("?",'').split("&");
for(var i =0; i< query.length; i++)
{
if(query[i]){
var temp = query[i].split("=");
queryParams[temp[0]] = temp[1]
}
}
From my recent experience, JsonReader#setLenient
basically makes the parser very tolerant, even to allow malformed JSON data.
But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim
the data would avoid the error:
String trimmed = result1.trim();
Then gson.fromJson(trimmed, T)
might work. Surely this only covers a special case, so YMMV.
Seems to be a typo error in that package of gcc. The solution:
mv /usr/include/c++/4.x/i486-linux-gnu /usr/include/c++/4.x/i686-linux-gnu/64
You have no valid main method... The signature should be: public static void main(String[] args);
Hence, in your case the code should look like this:
public class Echo {
public static void main (String[] arg) {
System.out.println(arg[0]);
}
}
Edit: Please note that Oscar is also right in that you are missing . in your classpath, you would run into the problem I solve after you have dealt with that error.
use this:
$(document).on('show.bs.modal','#myModal', function () {
alert('hi');
})
Both John Conde's and ryeballar's answers are correct and will work.
If you want to get too geeky:
John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center
and it has to decide whether to add/remove left
), when clearly only one is needed.
Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)
So, you can do the following as an alternative:
ng-class="{true:'center',false:'left'}[page.isSelected(1)]"
joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up tick_right()
with a call to set_ticks_position('both')
. A revised example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()
The result is a plot with ticks on both sides, but tick labels on the right.
You've got the right idea, but for /f
is designed to work on multi-line files or commands, not individual strings.
In its simplest form, for
is like Perl's for
, or every other language's foreach
. You pass it a list of tokens, and it iterates over them, calling the same command each time.
for %a in (hello world) do @echo %a
The extensions merely provide automatic ways of building the list of tokens. The reason your current code is coming up with nothing is that ';
' is the default end of line (comment) symbol. But even if you change that, you'd have to use %%g, %%h, %%i, ...
to access the individual tokens, which will severely limit your batch file.
The closest you can get to what you ask for is:
set TabbedPath=%PATH:;= %
for %%g in (%TabbedPath%) do echo %%g
But that will fail for quoted paths that contain semicolons.
In my experience, for /l
and for /r
are good for extending existing commands, but otherwise for
is extremely limited. You can make it slightly more powerful (and confusing) with delayed variable expansion (cmd /v:on
), but it's really only good for lists of filenames.
I'd suggest using WSH or PowerShell if you need to perform string manipulation. If you're trying to write whereis
for Windows, try where /?
.
In short:
Source: code.
I see only hacks in the answers, but there's actually a builtin solution very easy to use : Basically you can capture the focus element like this:
const focusedElement = document.activeElement
https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
the problem for me was I was trying to use IBM RAD which appears to not work properly for this, I installed Eclipse and now have a different error but I should be able to get past it
unset()
and initialization:unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
self.materials
is a dict
and by default you are iterating over just the keys (which are strings).
Since self.materials
has more than two keys*, they can't be unpacked into the tuple
"k, m
", hence the ValueError
exception is raised.
In Python 2.x, to iterate over the keys and the values (the tuple
"k, m
"), we use self.materials.iteritems()
.
However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:
for m in self.materials.itervalues():
In Python 3.x, prefer dict.values()
(which returns a dictionary view object):
for m in self.materials.values():
If you are using a relatively recent version of JSHint, the generally preferred approach is to create a .jshintrc file in the root of your project, and put this config in it:
{
"globals": {
"$": false
}
}
This declares to JSHint that $ is a global variable, and the false indicates that it should not be overridden.
The .jshintrc file was not supported in really old versions of JSHint (such as v0.5.5 like the original question in 2012). If you cannot or do not want to use the .jshintrc file, you can add this at the top of the script file:
/*globals $:false */
There is also a shorthand "jquery" jshint option as seen on the JSHint options page..
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
2.List<Integer> list2 = Arrays.asList(ia);
In line 2, Arrays.asList(ia)
returns a List
reference of inner class object defined within Arrays
, which is also called ArrayList
but is private and only extends AbstractList
. This means what returned from Arrays.asList(ia)
is a class object different from what you get from new ArrayList<Integer>
.
You cannot use some operations to line 2 because the inner private class within Arrays
does not provide those methods.
Take a look at this link and see what you can do with the private inner class: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.ArrayList
Line 1 creates a new ArrayList
object copying elements from what you get from line 2. So you can do whatever you want since java.util.ArrayList
provides all those methods.
ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\
.
From there, use the search function to find your application.
On the properties tab of the report (myReport.rdlc), change the "Keep Together" attribute to False. I've been struggling with this issue for a while and this seems to have solved my issue.
Using Collections#addAll()
String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, words);
When you go to the MySQL download page, choose the platform "Microsoft Windows". Then download the "Windows (x86, xx-bit), ZIP Archive" (be sure to select the one with size over 140M.
The binaries will be in the "bin" folder.
I understand that this is not just the client binaries, but at least you don't have to install and setup the entire server.
I start with the following template, which is derived from numerous printings of Itzik Ben-Gan's routine:
;WITH
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
select Number from Tally where Number <= 1000000
The "WHERE N<= 1000000" clause limits the output to 1 to 1 million, and can easily be adjusted to your desired range.
Since this is a WITH clause, it can be worked into an INSERT... SELECT... like so:
-- Sample use: create one million rows
CREATE TABLE dbo.Example (ExampleId int not null)
DECLARE @RowsToCreate int
SET @RowsToCreate = 1000000
-- "Table of numbers" data generator, as per Itzik Ben-Gan (from multiple sources)
;WITH
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
INSERT Example (ExampleId)
select Number
from Tally
where Number <= @RowsToCreate
Indexing the table after it's built will be the fastest way to index it.
Oh, and I'd refer to it as a "Tally" table. I think this is a common term, and you can find loads of tricks and examples by Googling it.
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
Simple example: Form with textbox and Search button.
If you write "name" into the textbox
and submit form, it will brings you patients with "name" in table.
View:
@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
@Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
@* ... *@
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@
_patientList.cshtml:
@model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
</tr>
@foreach (var patient in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
@Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
Patient.cs
public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
PatientController.cs
public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.
Using AWS Management Console:
Redis is an in memory data store, that can persist it's state to disk (to enable recovery after restart). However, being an in-memory data store means the size of the data store (on a single node) cannot exceed the total memory space on the system (physical RAM + swap space). In reality, it will be much less that this, as Redis is sharing that space with many other processes on the system, and if it exhausts the system memory space it will likely be killed off by the operating system.
Mongo is a disk based data store, that is most efficient when it's working set fits within physical RAM (like all software). Being a disk based data means there are no intrinsic limits on the size of a Mongo database, however configuration options, available disk space, and other concerns may mean that databases sizes over a certain limit may become impractical or inefficient.
Both Redis and Mongo can be clustered for high availability, backup and to increase the overall size of the datastore.
Yocoder is right,
Inside the DataTemplate
, your DataContext
is set to the Rule
its currently handling..
To access the parents DataContext
, you can also consider using a RelativeSource
in your binding:
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ____Your Parent control here___ }}, Path=DataContext.SelectedRule.Name}" />
More info on RelativeSource
can be found here:
http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx
you can try this
ts_create
TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ts_update
TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
Commonly when updating a column, we want to map an old value to a new value. Here's a way to do that in pyspark without UDF's:
# update df[update_col], mapping old_value --> new_value
from pyspark.sql import functions as F
df = df.withColumn(update_col,
F.when(df[update_col]==old_value,new_value).
otherwise(df[update_col])).
A list comprehension is a simple approach:
j2 = [x for x in j if x >= 5]
Alternately, you can use filter
for the exact same result:
j2 = filter(lambda x: x >= 5, j)
Note that the original list j
is unmodified.
In class WeatherRecord
:
First import the class if they are in different package else this statement is not requires
Import <path>.ClassName
Then, just referene or call your object like:
Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();
But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.
Date.date(date,month,year); // this is enough to call those static function
Have clear concept on Object and Static functions. Click me
You need to export the User.name
field so that the json
package can see it. Rename the name
field to Name
.
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Output:
{"Name":"Frank"}
What I can do to fix this (other than installing a real SSL certificate).
You can't.
On an https webpage you can only make AJAX request to https webpage (With a certificate trusted by the browser, if you use a self-signed one, it will not work for your visitors)
Expanding on Donut's answer and the other answers here, you can get even better results by using a generator comprehension instead of a list comprehension, and by using a set
data structure (since the in
operator is O(n) on a list but O(1) on a set).
So here's a function that would work for you:
def filter_list(full_list, excludes):
s = set(excludes)
return (x for x in full_list if x not in s)
The result will be an iterable that will lazily fetch the filtered list. If you need a real list object (e.g. if you need to do a len()
on the result), then you can easily build a list like so:
filtered_list = list(filter_list(full_list, excludes))
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
yum uses RPM, so the following command will list the contents of the installed package:
$ rpm -ql package-name
The latest version of Springsource STS (3.6) supports Tomcat 8. It is based on eclipse Luna 4.4 and supports Java 8. Have at it!
If your CSS is constructed completely around ex
or em
units, then this might be possible and feasible. You'd just need to declare font-size: 150%
in your style for body
or html
. This should cause every other lengths to scale proportionally. You can't scale images this way, though, unless they get a style too.
But that's a very big if on most sites, anyway.
how about gets ?
myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
//do stuff with line
end
Both commands are correct
php_value post_max_size 30M
php_value upload_max_filesize 30M
BUT to use the .htaccess
you have to enable rewrite_module
in Apache config file. In httpd.conf
find this line:
# LoadModule rewrite_module modules/mod_rewrite.so
and remove the #
.
I had the same issue too, the problem is exacerbated with the download link now only working for Visual Studio 2017, and installing the package from the download link did nothing for VS2015, although it took up 5gB of space.
I looked everywhere on how to do it with the Nu Get package manager and I couldn't find the solution.
It turns out it's even simpler than that, all you have to do is right-click the project or solution in the Solution Explorer from within Visual Studio, and click "Install Missing Components"
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
You can also use HTTP_HOST
instead of SERVER_NAME
as Herman commented. See this related question for a full discussion. In short, you are probably OK with using either. Here is the 'host' version:
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
Typically, I set ServerName
in the VirtualHost
because I want that to be the canonical form of the website. The $_SERVER['HTTP_HOST']
is set based on the request headers. If the server responds to any/all domain names at that IP address, a user could spoof the header, or worse, someone could point a DNS record to your IP address, and then your server / website would be serving out a website with dynamic links built on an incorrect URL. If you use the latter method you should also configure your vhost
or set up an .htaccess
rule to enforce the domain you want to serve out, something like:
RewriteEngine On
RewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$
RewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]
#sometimes u may need to omit this slash ^ depending on your server
Hope that helps. The real point of this answer was just to provide the first line of code for those people who ended up here when searching for a way to get the complete URL with apache :)
I have seen Big Theta, and I'm pretty sure I was taught the difference in school. I had to look it up though. This is what Wikipedia says:
Big O is the most commonly used asymptotic notation for comparing functions, although in many cases Big O may be replaced with Big Theta T for asymptotically tighter bounds.
Source: Big O Notation#Related asymptotic notation
I don't know why people use Big-O when talking formally. Maybe it's because most people are more familiar with Big-O than Big-Theta? I had forgotten that Big-Theta even existed until you reminded me. Although now that my memory is refreshed, I may end up using it in conversation. :)
(inline if) in java won't work if you are using 'if' statement .. the right syntax is in the following example:
int y = (c == 19) ? 7 : 11 ;
or
String y = (s > 120) ? "Slow Down" : "Safe";
System.out.println(y);
as You can see the type of the variable Y is the same as the return value ...
in your case it is better to use the normal if statement not inline if as it is in the pervious answer without "?"
if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");
I would recommend looking at Selection sort or Insertion sort if you aren't too worried about performance. Maybe that will give you some ideas.
I just changed the .htaccess file contents and as shown in the following links answer. And tried refreshing the page (which didn't work, and couldn't find the request to my controller) it worked.
Then just because of my doubt I undone the changes I did to my .htaccess inside my public_html folder back to original .htaccess content. So it's now as follows (which is originally it was):
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
And now also it works.
Hint: Seems like before the Rewrite Rules haven't been clearly setup within the Server context.
My file structure is as follows:
/
|- gheapp
| |- application
| L- system
|
|- public_html
| |- .htaccess
| L- index.php
And in the index.php
I have set up the following paths to the system and the application:
$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';
Note: by doing so, our application source code becomes hidden to the public at first.
Please, if you guys find anything wrong with my answer, comment and re-correct me!
Hope beginners would find this answer helpful.
Thanks!
Radio button without panel
public class RadioButton2 : RadioButton
{
public string GroupName { get; set; }
}
private void RadioButton2_Clicked(object sender, EventArgs e)
{
RadioButton2 rb = (sender as RadioButton2);
if (!rb.Checked)
{
foreach (var c in Controls)
{
if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
{
(c as RadioButton2).Checked = false;
}
}
rb.Checked = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//a group
RadioButton2 rb1 = new RadioButton2();
rb1.Text = "radio1";
rb1.AutoSize = true;
rb1.AutoCheck = false;
rb1.Top = 50;
rb1.Left = 50;
rb1.GroupName = "a";
rb1.Click += RadioButton2_Clicked;
Controls.Add(rb1);
RadioButton2 rb2 = new RadioButton2();
rb2.Text = "radio2";
rb2.AutoSize = true;
rb2.AutoCheck = false;
rb2.Top = 50;
rb2.Left = 100;
rb2.GroupName = "a";
rb2.Click += RadioButton2_Clicked;
Controls.Add(rb2);
//b group
RadioButton2 rb3 = new RadioButton2();
rb3.Text = "radio3";
rb3.AutoSize = true;
rb3.AutoCheck = false;
rb3.Top = 80;
rb3.Left = 50;
rb3.GroupName = "b";
rb3.Click += RadioButton2_Clicked;
Controls.Add(rb3);
RadioButton2 rb4 = new RadioButton2();
rb4.Text = "radio4";
rb4.AutoSize = true;
rb4.AutoCheck = false;
rb4.Top = 80;
rb4.Left = 100;
rb4.GroupName = "b";
rb4.Click += RadioButton2_Clicked;
Controls.Add(rb4);
}
You should really use the standard List class. Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.
You'll find plenty of simple tutorials via google, like this one. If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.
var EM = new events_managment();
EM.addEvent(window, 'resize', function(win,doc, event_){
console.log('resized');
//EM.removeEvent(win,doc, event_);
});
function events_managment(){
this.events = {};
this.addEvent = function(node, event_, func){
if(node.addEventListener){
if(event_ in this.events){
node.addEventListener(event_, function(){
func(node, event_);
this.events[event_](win_doc, event_);
}, true);
}else{
node.addEventListener(event_, function(){
func(node, event_);
}, true);
}
this.events[event_] = func;
}else if(node.attachEvent){
var ie_event = 'on' + event_;
if(ie_event in this.events){
node.attachEvent(ie_event, function(){
func(node, ie_event);
this.events[ie_event]();
});
}else{
node.attachEvent(ie_event, function(){
func(node, ie_event);
});
}
this.events[ie_event] = func;
}
}
this.removeEvent = function(node, event_){
if(node.removeEventListener){
node.removeEventListener(event_, this.events[event_], true);
this.events[event_] = null;
delete this.events[event_];
}else if(node.detachEvent){
node.detachEvent(event_, this.events[event_]);
this.events[event_] = null;
delete this.events[event_];
}
}
}
A map will not keep insertion order. Use *(myMap.begin())
to get the value of the first pair (the one with the smallest key when ordered).
You could also do myMap.begin()->first
to get the key and myMap.begin()->second
to get the value.
This is something I just recently had to do:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[cjso_UpdateCustomerLogin]
(
@CustomerID AS INT,
@UserName AS VARCHAR(25),
@Password AS BINARY(16)
)
AS
BEGIN
IF ISNULL((SELECT CustomerID FROM tblOnline_CustomerAccount WHERE CustomerID = @CustomerID), 0) = 0
BEGIN
INSERT INTO [tblOnline_CustomerAccount] (
[CustomerID],
[UserName],
[Password],
[LastLogin]
) VALUES (
/* CustomerID - int */ @CustomerID,
/* UserName - varchar(25) */ @UserName,
/* Password - binary(16) */ @Password,
/* LastLogin - datetime */ NULL )
END
ELSE
BEGIN
UPDATE [tblOnline_CustomerAccount]
SET UserName = @UserName,
Password = @Password
WHERE CustomerID = @CustomerID
END
END
To answer your question directly: while the loop condition is True. Which it always is, in this particular bit of code.
You probably updated your Ubuntu installation and one of the updates included the upgrade of Apache to version 2.4.x
In Apache 2.4.x the vhost configuration files, located in the /etc/apache2/sites-available directory, must have the .conf extension.
Using terminal (mv command), rename all your existing configuration files and add the .conf extension to all of them.
mv /etc/apache2/sites-available/cmsplus.dev /etc/apache2/sites-available/cmsplus.dev.conf
If you get a "Permission denied" error, then add "sudo " in front of your terminal commands.
You do not need to make any other changes to the configuration files.
Enable the vhost(s):
a2ensite cmsplus.dev.conf
And then reload Apache:
service apache2 reload
Your sites should be up and running now.
UPDATE: As mentioned here, a Linux distribution that you installed changed the configuration to Include *.conf only. Therefore it has nothing to do with Apache 2.2 or 2.4
Use npm list
and filter by contains using grep
Example:
npm list -g | grep name-of-package
You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:
It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:
use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;
$domain = (new DomainConfiguration('example.com'))
->setUsername('username') # A separate AD service account used by your app
->setPassword('password')
->setServers(['dc1', 'dc2', 'dc3'])
->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);
if (!$ldap->authenticate($username, $password, $message)) {
echo "Error: $message";
} else {
// Do something...
}
The authenticate call above will:
There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.
Using sqlplus
sqlplus / as sysdba
run:
SELECT * FROM dba_users
Should you only want the usernames do the following:
SELECT username FROM dba_users
This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the rpt
string increases.
def repeat(rpt, length):
return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle: https://jsfiddle.net/zm75cq2a/
Well, string type is a completely managed class for character strings, while char[] is still what it was in C, a byte array representing a character string for you.
In terms of API and standard library everything is implemented in terms of strings and not char[], but there are still lots of functions from the libc that receive char[] so you may need to use it for those, apart from that I would always use std::string.
In terms of efficiency of course a raw buffer of unmanaged memory will almost always be faster for lots of things, but take in account comparing strings for example, std::string has always the size to check it first, while with char[] you need to compare character by character.
You can use this one also (sets a special listener to be called when an action is performed on the EditText), it works both for DONE and RETURN:
max.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
Log.i(TAG,"Enter pressed");
}
return false;
}
});
There's nothing on the Documentation that mentions about anything like that.
Here's a quote:
-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:
java -Dfoo="some string" SomeClass
You also have CSS Grid and CSS Flex, both can give you columns that keep their position and size ratios depending on screen size, and flex can also easily rearrange the columns if screen size is too small so they can maintain a minimum width nicely.
See these guides for full details:
Grid:
.container {
display: grid | inline-grid;
}
Flex:
.container {
display: flex | inline-flex;
}
Maybe it's the comma in your if
condition.
function answers() {
var answer=document.getElementById("mySelect");
if(answer[answer.selectedIndex].value == "To measure time.") {
alert("That's correct!");
}
}
You can also write it like this.
function answers(){
document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}
<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.
session_destroy();
// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>
Just using Data Binding syntax. For example,
<Button x:Name="btn"
Content="Click"
Command="{Binding ClickCmd}"
CommandParameter="{Binding ElementName=btn,Path=Content}" />
Not only can we use Data Binding to get some data from View Models, but also pass data back to View Models. In CommandParameter, must use ElementName to declare binding source explicitly.
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
How about something like
import numpy as np
import matplotlib.pyplot as plt
V = np.array([[1,1], [-2,2], [4,-7]])
origin = np.array([[0, 0, 0],[0, 0, 0]]) # origin point
plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
plt.show()
Then to add up any two vectors and plot them to the same figure, do so before you call plt.show()
. Something like:
plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
v12 = V[0] + V[1] # adding up the 1st (red) and 2nd (blue) vectors
plt.quiver(*origin, v12[0], v12[1])
plt.show()
NOTE: in Python2 use origin[0], origin[1]
instead of *origin
I know its been quite old. But thought of its of any use to anyone else. Recently I came across this similar problem where I need a queue that is modifiable during iteration. I used listIterator to implement the same much in the same lines as of what Avi suggested -> Avi's Answer. See if this would suit for your need.
ModifyWhileIterateQueue.java
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ModifyWhileIterateQueue<T> {
ListIterator<T> listIterator;
int frontIndex;
List<T> list;
public ModifyWhileIterateQueue() {
frontIndex = 0;
list = new ArrayList<T>();
listIterator = list.listIterator();
}
public boolean hasUnservicedItems () {
return frontIndex < list.size();
}
public T deQueue() {
if (frontIndex >= list.size()) {
return null;
}
return list.get(frontIndex++);
}
public void enQueue(T t) {
listIterator.add(t);
}
public List<T> getUnservicedItems() {
return list.subList(frontIndex, list.size());
}
public List<T> getAllItems() {
return list;
}
}
ModifyWhileIterateQueueTest.java
@Test
public final void testModifyWhileIterate() {
ModifyWhileIterateQueue<String> queue = new ModifyWhileIterateQueue<String>();
queue.enQueue("one");
queue.enQueue("two");
queue.enQueue("three");
for (int i=0; i< queue.getAllItems().size(); i++) {
if (i==1) {
queue.enQueue("four");
}
}
assertEquals(true, queue.hasUnservicedItems());
assertEquals ("[one, two, three, four]", ""+ queue.getUnservicedItems());
assertEquals ("[one, two, three, four]", ""+queue.getAllItems());
assertEquals("one", queue.deQueue());
}
SELECT Collumn1 + ' - ' + Collumn2 AS 'FullName' FROM TableName
You can use new Date().getTime()
for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms
into s
.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
If all items are unique, you can use sets.
>>> items = set([-1, 0, 1, 2])
>>> set([1, 2]).issubset(items)
True
>>> set([1, 3]).issubset(items)
False
Create a segue to present modally and set Presentation property of that segue to over current context it will work 100 %
On Mac
Netbeans 8.0.2 Tools -> Plugins -> type in search: Dark Look and Feel. Then install plugin.
NOTE: There is no "Option" Or "Appearance" in the "Tools" section in Netbeans 8.0.2.
The best way I've found to do this is with StrMethodFormatter
:
import matplotlib as mpl
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
For example:
import pandas as pd
import requests
import matplotlib.pyplot as plt
import matplotlib as mpl
url = 'https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USDT&aggregate=1'
df = pd.DataFrame({'BTC/USD': [d['close'] for d in requests.get(url).json()['Data']]})
ax = df.plot()
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
plt.show()
vector<char> toVector( const std::string& s ) {
string s = "apple";
vector<char> v(s.size()+1);
memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector(std::string("apple"));
// what you were looking for (mutable)
char* c = v.data();
.c_str() works for immutable. The vector will manage the memory for you.
Definitely the easiest way to do that is using Gson's default parsing function fromJson()
.
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType
(e.g., any List
), which is fromJson(JsonElement json, Type typeOfT)
.
In your case, you just need to get the Type
of a List<String>
and then parse the JSON array into that Type
, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson
is a JsonElement
, but it could also be a String
, any Reader
or a JsonReader
.
You may want to take a look at Gson API documentation.
null
is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null
returns "object"
. But that is actually a bug (that might even be fixed in ECMAScript 6).
The difference between null
and undefined
is as follows:
undefined
: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.
> var noValueYet;
> console.log(noValueYet);
undefined
> function foo(x) { console.log(x) }
> foo()
undefined
> var obj = {};
> console.log(obj.unknownProperty)
undefined
Accessing unknown variables, however, produces an exception:
> unknownVariable
ReferenceError: unknownVariable is not defined
null
: used by programmers to indicate “no value”, e.g. as a parameter to a function.
Examining a variable:
console.log(typeof unknownVariable === "undefined"); // true
var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true
var bar = null;
console.log(bar === null); // true
As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null
is an edge case, because it works for both null
and undefined
:
> null == null
true
> undefined == null
true
A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true
. That conversion is performed by the if
statement and the boolean operator ! (“not”).
function foo(param) {
if (param) {
// ...
}
}
function foo(param) {
if (! param) param = "abc";
}
function foo(param) {
// || returns first operand that can't be converted to false
param = param || "abc";
}
Drawback of this approach: All of the following values evaluate to false
, so you have to be careful (e.g., the above checks can’t distinguish between undefined
and 0
).
undefined
, null
false
+0
, -0
, NaN
""
You can test the conversion to boolean by using Boolean
as a function (normally it is a constructor, to be used with new
):
> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true
Complementing the @djechlin answer (good answer by the way!), this function call could be also used as dummy code to hold a breakpoint in an IDE when you want to stop in some specific iteration or a particular recursive call, for example:
isUserAGoat()
could be used instead of a dummy variable declaration that will be shown in the IDE as a warning and, in Eclipse particular case, will clog the breakpoint mark, making it difficult to enable/disable it. If the method is used as a convention, all the invocations could be later filtered by some script (during commit phase maybe?).
Google guys are heavy Eclipse users (they provide several of their projects as Eclipse plugins: Android SDK, GAE, etc), so the @djechlin answer and this complementary answer make a lot of sense (at least for me).
If you like C++ better than C, you can try this:
#include <ios>
#include <iostream>
bool b = IsSomethingTrue();
std::cout << std::boolalpha << b;
You can change your the Build Target for your project at any time:
Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.
Edit the following elements in the AndroidManifest.xml file (it is in your project root directory)
In this case, that will be:
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
Save it
Rebuild your project.
Click the Project on the menu bar, select Clean...
Now, run the project again.
Right Click Project name, move on Run as, and select Android Application
By the way, reviewing Managing Projects from Eclipse with ADT will be helpful. Especially the part called Creating an Android Project.
You can also use START WITH
to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,
SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!
using jquery u need import library
i recommend you using php
<?php
echo"<html>
<body>";
?>
<?php
include "b.html";
?>
<?php
echo" </body>
</html>";
?>
b.html
<div>hi this is ur file :3<div>
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.register);
session = new UserSessionManeger(getApplicationContext());
login_id= (EditText) findViewById(R.id.loginid);
Suponser_id= (EditText) findViewById(R.id.sponserid);
name=(EditText) findViewById(R.id.name);
pass=(EditText) findViewById(R.id.pass);
moblie=(EditText) findViewById(R.id.mobile);
email= (EditText) findViewById(R.id.email);
placment= (EditText) findViewById(R.id.placement);
Adress= (EditText) findViewById(R.id.adress);
State = (EditText) findViewById(R.id.state);
city=(EditText) findViewById(R.id.city);
pincopde=(EditText) findViewById(R.id.pincode);
counntry= (EditText) findViewById(R.id.country);
plantype= (EditText) findViewById(R.id.plantype);
mRegister = (Button)findViewById(R.id.registration);
// session.createUserLoginSession(info.getCustomerID(),info.getName(),info.getMobile(),info.getEmailID(),info.getAccountType());
mRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
request.addProperty("LoginCustomerID",login_id.getText().toString());
request.addProperty("SponsorID",Suponser_id.getText().toString());
request.addProperty("Name", name.getText().toString());
request.addProperty("LoginPassword",pass.getText().toString() );
request.addProperty("MobileNumber",smoblie=moblie.getText().toString());
request.addProperty("Email",email.getText().toString() );
request.addProperty("Placement", placment.getText().toString());
request.addProperty("address1", Adress.getText().toString());
request.addProperty("StateID", State.getText().toString());
request.addProperty("CityName",city.getText().toString());
request.addProperty("Pincode",pincopde.getText().toString());
request.addProperty("CountryID",counntry.getText().toString());
request.addProperty("PlanType",plantype.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
SoapObject result = (SoapObject)envelope.getResponse();
Log.e("value of result", " result"+result);
if(result!= null)
{
Toast.makeText(getApplicationContext(), "successfully register ", 2000).show() ;
}
else {
Toast.makeText(getApplicationContext(), "Try Again..", 2000).show() ;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
When you receive the request you can
var origin = (req.headers.origin || "*");
than when you have to response go with something like that:
res.writeHead(
206,
{
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': origin,
}
);
Try this:
String dateStr = "Jul 27, 2011 8:35:29 AM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
String formattedDate = writeFormat.format(date);
}
You can parse a string into an integer with int.parse()
. For example:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Note that int.parse()
accepts 0x
prefixed strings. Otherwise the input is treated as base-10.
You can parse a string into a double with double.parse()
. For example:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse()
will throw FormatException if it cannot parse the input.
I had the same problem, put the ! outside the brackets;
while ! [ -f /tmp/list.txt ];
do
echo "#"
sleep 1
done
Also, if you add an echo inside the loop it will tell you if you are getting into the loop or not.
let toSort = {a:2323, b: 14, c: 799}
let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1])
Output:
[ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ]
As of the latest Bootstrap (3.1.x), the way to achieve a fluid layout it to use .container-fluid
class.
See Bootstrap grid for reference