You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
You are missing table NewScores
, so it can't be found. Just join this table.
If you really want to avoid joining it directly you can replace NewScores.NetScore
with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}
It seems in general you're just looking for a join:
> dat1 = pd.DataFrame({'dat1': [9,5]})
> dat2 = pd.DataFrame({'dat2': [7,6]})
> dat1.join(dat2)
dat1 dat2
0 9 7
1 5 6
$eval
and $parse
don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.
Q: What exactly is $eval doing? Why does it need its own mini parsing language?
From the docs:
Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.
It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).
Q: Why isn't plain old javascript "eval" being used?
Because it's not actually evaluating JavaScript. As the docs say:
If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.
The docs linked to above have a lot more information.
add Location to your constructor from @angular/common
constructor(private _location: Location) {}
add the back function:
back() {
this._location.back();
}
and then in your view:
<button class="btn" (click)="back()">Back</button>
Anti-aliasing cannot be turned on or off, and is controlled by the browser.
Try this code, Let $ be defined
(function ($, Drupal) {
'use strict';
Drupal.behaviors.module_name = {
attach: function (context, settings) {
jQuery(document).ready(function($) {
$("#search_text").autocomplete({
source:results,
minLength:2,
position: { offset:'-30 0' },
select: function(event, ui ) {
goTo(ui.item.value);
return false;
}
});
});
}
};
})(jQuery, Drupal);
A token
is a piece of data which only Server X
could possibly have created, and which contains enough data to identify a particular user.
You might present your login information and ask Server X
for a token
; and then you might present your token
and ask Server X
to perform some user-specific action.
Token
s are created using various combinations of various techniques from the field of cryptography as well as with input from the wider field of security research. If you decide to go and create your own token
system, you had best be really smart.
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html
.neon {
font-size: 20px;
color: #fff;
text-shadow: 0 0 8px yellow;
animation: blinker 6s;
animation-iteration-count: 1;
}
@keyframes blinker {
0% {
opacity: 0.2;
}
19% {
opacity: 0.2;
}
20% {
opacity: 1;
}
21% {
opacity: 1;
}
22% {
opacity: 0.2;
}
23% {
opacity: 0.2;
}
36% {
opacity: 0.2;
}
40% {
opacity: 1;
}
41% {
opacity: 0;
}
42% {
opacity: 1;
}
43% {
opacity: 0.5;
}
50% {
opacity: 1;
}
100% {
opacity: 1;
}
}
I used font-family: "Quicksand", sans-serif;
This is the import of the font (goes in the top of the style.css)
@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@300&display=swap");
Since diawi.com have added some limitations for free accounds.
Next best available and easy to use alternative is
Microsoft
https://firebase.google.com/docs/app-distribution/ios/distribute-console
Others
Happy build sharing!
First, there are errors in your code, ie. you are missing a semicolon and a closing parenthesis in the for loop.
Then, if you are trying to append values to the view, you should use textview.appendText(), instead of .setText().
There's a similar question here: how to change text in Android TextView
There is no default database for user. There is default database for current session.
You can get it using DATABASE() function -
SELECT DATABASE();
And you can set it using USE statement -
USE database1;
You should set it manually - USE db_name
, or in the connection string.
In my case or all using android studio
you can import google play service
place in your build.gradle
compile 'com.google.android.gms:play-services:7.8.0'
or latest version of play services depend in time you watch this answer
More Specific import
please review this individual gradle imports
https://developers.google.com/android/guides/setup
Google Maps
com.google.android.gms:play-services-maps:7.8.0
error may occurred
if you face error while you sync project with gradle files
make sure you install latest update
1- Android Support Repository.
2- Android Support Library.
3- Google Repository.
4-Google Play Services.
You may need restart your android studio to response
You can try with this: (Note: name of input tag === field of object)
<input name="myField" type="text"
value={this.state.myObject.myField}
onChange={this.handleChangeInpForm}>
</input>
-----------------------------------------------------------
handleChangeInpForm = (e) => {
let newObject = this.state.myObject;
newObject[e.target.name] = e.target.value;
this.setState({
myObject: newObject
})
}
They are as they were. That one key is JUST DELETED
UPDATE 2018 MAY:
Alternatively, you can embed Edge browser, but only targetting windows 10.
List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();
String query = "SELECT rlink_id, COUNT(*)"
+ "FROM dbo.Locate "
+ "GROUP BY rlink_id ";
Statement stmt = yourconnection.createStatement();
try {
ResultSet rs4 = stmt.executeQuery(query);
while (rs4.next()) {
sids.add(rs4.getString(1));
lids.add(rs4.getString(2));
}
} finally {
stmt.close();
}
String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());
The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).
In almost all cases I suggest using an EnumMap
instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).
private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
pageIndexes.put(Page.SIGN_CREATE, 1);
//etc., ...
int createIndex = pageIndexes.get(Page.SIGN_CREATE);
It's typically incredibly efficient, too.
Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.
Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap
instead of ordinal indexing.
As an alternative to everyone else's answers I've always done something like this:
List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
if (someCondition) {
toRemove.add(str);
}
}
myArrayList.removeAll(toRemove);
This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
You can override any built-in function by just re-declaring it.
parseFloat = function(a){
alert(a)
};
Now parseFloat(3)
will alert 3.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
FIX IDEA Hey guys so i have made an app and did not used any push notification functions but i still got an email. After checking the certificates, ids and profiles of the bundle identifier i used to create my app in apple store connect in the apple developer portal i realized that push notificiations were turned on.
What you have to do is:
go to apple developer login site where you can manage your certificates a.s.o 2. select "Certificates, IDs and Profiles" Tab on the right side 3. now select "Identifiers" 4. and the bundle id from the list to the right 5. now scroll down till you see push notification 6. turn it off 7. archive your build and reupload it to Apple Store Connect
Hope it helps!
I had missing application context in the Tomcat Run\Debug configuration:
Adding it, solved the problem and I got the right response instead of "The origin server did not find..."
None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.
CSS
.iframe-container {
overflow: hidden;
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
padding-top: 75%;
}
HTML
<div class="iframe-container">
<iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>
substring(): It has 2 parameters "start" and "end".
If the end parameter is not specified, all the characters from the start position till the end of the string are extracted.
var str = "Substring Example";_x000D_
var result = str.substring(0, 10);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
If the value of start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as start.
var str = "Substring Example";_x000D_
var result = str.substring(10, 0);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
substr(): It has 2 parameters "start" and "count".
start parameter is required and specifies the position where to start the extraction.
count parameter is optional and specifies the number of characters to extract.
var str = "Substr Example";_x000D_
var result = str.substr(0, 10);_x000D_
alert(result);_x000D_
_x000D_
_x000D_
Output : Substr Exa
_x000D_
If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If count is 0 or negative, an empty string is returned.
var str = "Substr Example";_x000D_
var result = str.substr(11);_x000D_
alert(result);_x000D_
_x000D_
Output : ple
_x000D_
Here is a couple of extra methods:
Method 1
IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
DROP TABLE dbo.Numbers
GO
CREATE TABLE Numbers (Number int NOT NULL PRIMARY KEY);
GO
DECLARE @i int = 1;
INSERT INTO dbo.Numbers (Number)
VALUES (1),(2);
WHILE 2*@i < 1048576
BEGIN
INSERT INTO dbo.Numbers (Number)
SELECT Number + 2*@i
FROM dbo.Numbers;
SET @i = @@ROWCOUNT;
END
GO
SELECT COUNT(*) FROM Numbers AS RowCownt --1048576 rows
Method 2
IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
DROP TABLE dbo.Numbers
GO
CREATE TABLE dbo.Numbers (Number int NOT NULL PRIMARY KEY);
GO
DECLARE @i INT = 0;
INSERT INTO dbo.Numbers (Number)
VALUES (1);
WHILE @i <= 9
BEGIN
INSERT INTO dbo.Numbers (Number)
SELECT N.Number + POWER(4, @i) * D.Digit
FROM dbo.Numbers AS N
CROSS JOIN (VALUES(1),(2),(3)) AS D(Digit)
ORDER BY D.Digit, N.Number
SET @i = @i + 1;
END
GO
SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --1048576 rows
Method 3
IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
DROP TABLE dbo.Numbers
GO
CREATE TABLE Numbers (Number int identity NOT NULL PRIMARY KEY, T bit NULL);
WITH
T1(T) AS (SELECT T FROM (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS T(T)) --10 rows
,T2(T) AS (SELECT A.T FROM T1 AS A CROSS JOIN T1 AS B CROSS JOIN T1 AS C) --1,000 rows
,T3(T) AS (SELECT A.T FROM T2 AS A CROSS JOIN T2 AS B CROSS JOIN T2 AS C) --1,000,000,000 rows
INSERT INTO dbo.Numbers(T)
SELECT TOP (1048576) NULL
FROM T3;
ALTER TABLE Numbers
DROP COLUMN T;
GO
SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --1048576 rows
Method 4, taken from Defensive Database Programming book by Alex Kuznetsov
IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
DROP TABLE dbo.Numbers
GO
CREATE TABLE Numbers (Number int NOT NULL PRIMARY KEY);
GO
DECLARE @i INT = 1 ;
INSERT INTO dbo.Numbers (Number)
VALUES (1);
WHILE @i < 524289 --1048576
BEGIN;
INSERT INTO dbo.Numbers (Number)
SELECT Number + @i
FROM dbo.Numbers;
SET @i = @i * 2 ;
END
GO
SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --1048576 rows
Method 5, taken from Arrays and Lists in SQL Server 2005 and Beyond article by Erland Sommarskog
IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
DROP TABLE dbo.Numbers
GO
CREATE TABLE Numbers (Number int NOT NULL PRIMARY KEY);
GO
WITH digits (d) AS (
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL
SELECT 0)
INSERT INTO Numbers (Number)
SELECT Number
FROM (SELECT i.d + ii.d * 10 + iii.d * 100 + iv.d * 1000 +
v.d * 10000 + vi.d * 100000 AS Number
FROM digits i
CROSS JOIN digits ii
CROSS JOIN digits iii
CROSS JOIN digits iv
CROSS JOIN digits v
CROSS JOIN digits vi) AS Numbers
WHERE Number > 0
GO
SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --999999 rows
Summary:
Among those 5 methods, method 3 seems to be the fastest.
you can use the left_on and right_on options as follows:
pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)
pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')
My way to replicate Excel's MOD(a,b)
in VBA is to use XLMod(a,b)
in VBA where you include the function:
Function XLMod(a, b)
' This replicates the Excel MOD function
XLMod = a - b * Int(a / b)
End Function
in your VBA Module
Happened to me on node 13.7.0
and npm 6.13.6
(macOS Mojave).
I had the following as part of my errors:
found X vulnerabilities (Y moderate, Z high)
run `npm audit fix` to fix them, or `npm audit` for details
And running the following fixed the problem:
$ npm audit fix
$ npm install
Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.
Meanwhile you have to use double quotes not single quote to expand variables:
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
Semicolons at the end of a single command are also unnecessary.
So far:
#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
For su
you can run it with:
su -c 'sh /path/to/script.sh'
Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using .
or source
from the interactive shell. It could have been a standalone scipt, or it could have been source
'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
$res = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = '$databasename' AND table_name = '$tablename';");
If no records are returned then it doesn't exist.
In C++11, the using
keyword when used for type alias
is identical to typedef
.
7.1.3.2
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
Bjarne Stroustrup provides a practical example:
typedef void (*PFD)(double); // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double); // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP
Pre-C++11, the using
keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):
class Derived : public Base {
public:
using Base::f; // lift Base's f into Derived's scope -- works in C++98
void f(char); // provide a new f
void f(int); // prefer this f to Base::f(int)
using Base::Base; // lift Base constructors Derived's scope -- C++11 only
Derived(char); // provide a new constructor
Derived(int); // prefer this constructor to Base::Base(int)
// ...
};
Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard
, Design decisions
, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.
Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.
First let’s consider a toy example:
template <typename T> class MyAlloc {/*...*/}; template <typename T, class A> class MyVector {/*...*/}; template <typename T> struct Vec { typedef MyVector<T, MyAlloc<T> > type; }; Vec<int>::type p; // sample usage
The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.
template <typename T> void foo (Vec<T>::type&);
So, the syntax is somewhat ugly. We would rather avoid the nested
::type
We’d prefer something like the following:template <typename T> using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below Vec<int> p; // sample usage
Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on
Vec<T>
in deducible context, and the syntax is improved as well. For example we could rewrite foo as:template <typename T> void foo (Vec<T>&);
We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to
foo(p)
will succeed.
The follow-up paper n1489 explains why using
instead of using typedef
:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentencetemplate<class T> using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
I think the important distinction is made here, aliases instead of types. Another quote from the same document:
An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.
Summary, for the role of using
:
namespace PO = boost::program_options
and using PO = ...
equivalent)A typedef declaration can be viewed as a special case of non-template alias-declaration
. It's an aesthetic change, and is considered identical in this case.namespace std
into the global scope), member functions, inheriting constructorsIt cannot be used for:
int i;
using r = i; // compile-error
Instead do:
using r = decltype(i);
Naming a set of overloads.
// bring cos into scope
using std::cos;
// invalid syntax
using std::cos(double);
// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);
type
%matplotlib qt
when you want graphs in a separate window and
%matplotlib inline
when you want an inline plot
From enable-cors.org:
CORS on ASP.NET
If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
If you do not care about the data in management database; i.e. users
, vhosts
, messages
etc., and neither about other queues
, then you can reset
via commandline by running the following commands in order:
WARNING: In addition to the queues, this will also remove any
users
andvhosts
, you have configured on your RabbitMQ server; and will delete any persistentmessages
rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app
The rabbitmq documentation says that the reset
command:
Returns a RabbitMQ node to its virgin state.
Removes the node from any cluster it belongs to, removes all data from the management database, such as configured users and vhosts, and deletes all persistent messages.
So, be careful using it.
If you want to update the app icon in the taskbar, then Update following in main.js (if using typescript then main.ts)
win.setIcon(path.join(__dirname, '/src/assets/logo-small.png'));
__dirname
points to the root directory (same directory as package.json
) of your application.
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
A Numpy array is immutable, meaning you technically cannot delete an item from it. However, you can construct a new array without the values you don't want, like this:
b = np.delete(a, [2,3,6])
Anyone using composer dependencies, you might want to consider this library: https://github.com/ramsey/uuid
It doesn't get any easier than this:
Uuid::uuid4();
The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:
param($minutes = 60)
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 60
$myshell.sendkeys(".")
}
and an alternative from the comments, which moves the mouse a single pixel:
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)
Here is a workaround to know if softkeyboard is visible.
Some of the popular keyboards have certain keywords in their classNames:
From ActivityManager.RunningServiceInfo, check for the above patterns in ClassNames. Also, ActivityManager.RunningServiceInfo's clientPackage=android, indicating that the keyboard is bound to system.
The above mentioned information could be combined for a strict way to find out if soft keyboard is visible.
Based on ng5000's answer, I like using this extension:
#region Suspend
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static IDisposable BeginSuspendlock(this Control ctrl)
{
return new suspender(ctrl);
}
private class suspender : IDisposable
{
private Control _ctrl;
public suspender(Control ctrl)
{
this._ctrl = ctrl;
SendMessage(this._ctrl.Handle, WM_SETREDRAW, false, 0);
}
public void Dispose()
{
SendMessage(this._ctrl.Handle, WM_SETREDRAW, true, 0);
this._ctrl.Refresh();
}
}
#endregion
Use:
using (this.BeginSuspendlock())
{
//update GUI
}
You can use the following code :
<!DOCTYPE html>
<html>
<body onLoad="triggerJS();">
<script>
function triggerJS(){
location.replace("http://www.google.com");
/*
location.assign("New_WebSite_Url");
//Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
*/
}
</script>
</body>
</html>
Straight from the ECMA-262, Fifth Edition ECMAScript Specification:
7.9.1 Rules of Automatic Semicolon Insertion
There are three basic rules of semicolon insertion:
- When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
- The offending token is separated from the previous token by at least one
LineTerminator
.- The offending token is }.
- When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript
Program
, then a semicolon is automatically inserted at the end of the input stream.- When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no
LineTerminator
here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see 12.6.3).
The List<>
class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
According to MSDN:
...List "Represents a strongly typed list of objects that can be accessed by index."
The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.
You might be getting odd results from your code if you're moving the item later in the list, as your Remove()
will move all of the other items down one place before the call to Insert()
.
Can you boil your code down to something small enough to post?
table td{
color:#0000ff;
}
<table>
<tbody>
<tr>
<td>
<select name="test">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
Not sure if it was removed before, I heard it was kinda buggy in 0.5.8
but in AS 0.5.9
the settings is there:
Gradle > Global Gradle settings > Offline work
Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:
All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.
This restriction accomplishes four functions, 1st and 3rd are important in this particular case:
And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.
One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.
There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:
If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.
Hope this will helps you to find the proper solution!
I can see it's an old question, if you want to put other HTML inside could use the radiobutton with GroupName propery same in all radiobuttons and in the Text property set something like an image or the html you need.
<asp:RadioButton GroupName="group1" runat="server" ID="paypalrb" Text="<img src='https://www.paypalobjects.com/webstatic/mktg/logo/bdg_secured_by_pp_2line.png' border='0' alt='Secured by PayPal' style='width: 103px; height: 61px; padding:10px;'>" />
I was able to get it to work by following these instructions.
Download the sample code
Unzip it to a new location
Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)
Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to)
Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs:
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Run (hit F5)
They are lists because you type them as lists in the dictionary:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
You should use the bike-class instead:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
This will allow you to get the cost of the bikes with bike.cost as you were trying to.
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
This will now print:
Kruzer : 33.0
Trike : 20.0
If anyone ever gets this far down, I spent some time hacking on this trying to patch moment.js (https://github.com/moment/moment). Here's something that I took away from it:
function isNumeric(val) {
var _val = +val;
return (val !== val + 1) //infinity check
&& (_val === +val) //Cute coercion check
&& (typeof val !== 'object') //Array/object check
}
Handles the following cases:
True! :
isNumeric("1"))
isNumeric(1e10))
isNumeric(1E10))
isNumeric(+"6e4"))
isNumeric("1.2222"))
isNumeric("-1.2222"))
isNumeric("-1.222200000000000000"))
isNumeric("1.222200000000000000"))
isNumeric(1))
isNumeric(0))
isNumeric(-0))
isNumeric(1010010293029))
isNumeric(1.100393830000))
isNumeric(Math.LN2))
isNumeric(Math.PI))
isNumeric(5e10))
False! :
isNumeric(NaN))
isNumeric(Infinity))
isNumeric(-Infinity))
isNumeric())
isNumeric(undefined))
isNumeric('[1,2,3]'))
isNumeric({a:1,b:2}))
isNumeric(null))
isNumeric([1]))
isNumeric(new Date()))
Ironically, the one I am struggling with the most:
isNumeric(new Number(1)) => false
Any suggestions welcome. :]
Update: while the following solution works, there's a much easier method. See below.
Here's what I came up with, and I hope this comes in handy - to you or anybody else:
$('#element').attr('style', function(i, style)
{
return style && style.replace(/display[^;]+;?/g, '');
});
This will remove that inline style.
I'm not sure this is what you wanted. You wanted to override it, which, as pointed out already, is easily done by $('#element').css('display', 'inline')
.
What I was looking for was a solution to REMOVE the inline style completely. I need this for a plugin I'm writing where I have to temporarily set some inline CSS values, but want to later remove them; I want the stylesheet to take back control. I could do it by storing all of its original values and then putting them back inline, but this solution feels much cleaner to me.
Here it is in plugin format:
(function($)
{
$.fn.removeStyle = function(style)
{
var search = new RegExp(style + '[^;]+;?', 'g');
return this.each(function()
{
$(this).attr('style', function(i, style)
{
return style && style.replace(search, '');
});
});
};
}(jQuery));
If you include this plugin in the page before your script, you can then just call
$('#element').removeStyle('display');
and that should do the trick.
Update: I now realized that all this is futile. You can simply set it to blank:
$('#element').css('display', '');
and it'll automatically be removed for you.
Here's a quote from the docs:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
I don't think jQuery is doing any magic here; it seems the style
object does this natively.
You can use the size
attribute to make the <select>
appear as a box instead of a dropdown. The number you use in the size
attribute defines how many options are visible in the box without scrolling.
<select size="5">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
You can’t apply this to a <select>
and have it still appear as a drop-down list though. The browser/operating system will decide how many options should be displayed for drop-down lists, unless you use HTML, CSS and JavaScript to create a fake dropdown list.
Using MySql, the SqlFunctions.StringConvert
didn't work for me. Since I use SelectListItem
in 20+ places in my project, I wanted a solution that work without contorting the 20+ LINQ statements. My solution was to sub-class SelectedListItem
in order to provide an integer setter, which moves type conversion away from LINQ. Obviously, this solution is difficult to generalize, but was quite helpful for my specific project.
To use, create the following type and use in your LINQ query in place of SelectedListItem
and use IntValue in place of Value.
public class BtoSelectedListItem : SelectListItem
{
public int IntValue
{
get { return string.IsNullOrEmpty(Value) ? 0 : int.Parse(Value); }
set { Value = value.ToString(); }
}
}
In my example, two timeouts are set. The connection timeout throws java.net.SocketTimeoutException: Socket is not connected
and the socket timeout java.net.SocketTimeoutException: The operation timed out
.
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().
httpClient.setParams(httpParameters);
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
You're looking for the MemoryStream.Write
method.
For example, the following code will write the contents of a byte[]
array into a memory stream:
byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);
Alternatively, you could create a new, non-resizable MemoryStream
object based on the byte array:
byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);
Sounds like a job for the UNIX command split:
split MyBigFile.csv
Just split my 55 GB csv file in 21k chunks in less than 10 minutes.
It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win
In python many things are iterable including files and strings. Iterating over a filehandler gives you a list of all the lines in that file. Iterating over a string gives you a list of all the characters in that string.
charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes
for line in open(filePath):
for char in line:
charsFromFile.append(char)
#apply code on each character here
or if you want a one liner
#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]
.
.
Edit: as agf mentions you can use itertools.chain.from_iterable
His method is better, unless you want the ability to specify which lines to grab
list(itertools.chain.from_iterable(open(filename, 'rU)))
This does however require one to be familiar with itertools, and as a result looses some readablity
If you only want to iterate over the chars, and don't care about storing a list, then I would use the nested for loops. This method is also the most readable.
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
You need to specify the minimum width of the field.
String.format("%" + numberOfSpaces + "s", "");
Why do you want to generate a String of spaces of a certain length.
If you want a column of this length with values then you can do:
String.format("%" + numberOfSpaces + "s", "Hello");
which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
To sort by MULTIPLE COLUMN (Sort by column_1
, and then sort by column_2
)
with open('unsorted.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)
with open('sorted.csv', 'w') as f:
fieldnames = ['column_1', 'column_2', column_3]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)
Try it:
def showDf(df, count=None, percent=None, maxColumns=0):
if (df == None): return
import pandas
from IPython.display import display
pandas.set_option('display.encoding', 'UTF-8')
# Pandas dataframe
dfp = None
# maxColumns param
if (maxColumns >= 0):
if (maxColumns == 0): maxColumns = len(df.columns)
pandas.set_option('display.max_columns', maxColumns)
# count param
if (count == None and percent == None): count = 10 # Default count
if (count != None):
count = int(count)
if (count == 0): count = df.count()
pandas.set_option('display.max_rows', count)
dfp = pandas.DataFrame(df.head(count), columns=df.columns)
display(dfp)
# percent param
elif (percent != None):
percent = float(percent)
if (percent >=0.0 and percent <= 1.0):
import datetime
now = datetime.datetime.now()
seed = long(now.strftime("%H%M%S"))
dfs = df.sample(False, percent, seed)
count = df.count()
pandas.set_option('display.max_rows', count)
dfp = dfs.toPandas()
display(dfp)
Examples of usages are:
# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)
# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15)
Just add show.json.erb
file with the contents
<%= @user.to_json %>
Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. image_path(@user.avatar)
or something to generate additional properties in JSON:
<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>
I want my python function to split a sentence (input) and store each word in a list
The str().split()
method does this, it takes a string, splits it into a list:
>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0
The problem you're having is because of a typo, you wrote print(words)
instead of print(word)
:
Renaming the word
variable to current_word
, this is what you had:
def split_line(text):
words = text.split()
for current_word in words:
print(words)
..when you should have done:
def split_line(text):
words = text.split()
for current_word in words:
print(current_word)
If for some reason you want to manually construct a list in the for loop, you would use the list append()
method, perhaps because you want to lower-case all words (for example):
my_list = [] # make empty list
for current_word in words:
my_list.append(current_word.lower())
Or more a bit neater, using a list-comprehension:
my_list = [current_word.lower() for current_word in words]
FWIW, I was getting this error when I was accidentally making a GET request to an endpoint that was expecting a POST request. Presumably that was just that particular servers way of handling the problem.
I believe the proper way of adding pthread
in CMake
is with the following
find_package (Threads REQUIRED)
target_link_libraries(helloworld
${CMAKE_THREAD_LIBS_INIT}
)
If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.
Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Don't include header.php. You should not output HTML when you are going to redirect.
Make a new file, eg. "pre.php". Put this in it:
<?php
include('class.user.php');
include('class.Connection.php');
?>
Then in header.php, include that, in stead of including the two other files. In form.php, include pre.php in stead of header.php.
By default git uses uses less as pager. I normally prefer more, as it will print the first page and then allow you to scroll through the content.
Further, the content will remain in the console when done. This is usually convenient, as you often want to do something with the content after lookup (eg. email the commiter and tell him he introduced a bug in his last commit).
If you then want to pipe content, it would be inconvenient to scroll to print everything. The good thing with more is you will be able to combine it with pipeline and it will pipe through everything, eg.
# Find the commit abcdef123 in the full commit history and read author and commit message
git log |grep -C 5 'abcdef123'
Basically more is all you would ever need, unless you do not want the content to remain in the console when done. To use more instead, do as below.
git config --global core.pager 'more'
To complete @GauravKachhadiya's answer :
IndexIgnore *.jpg
means "hide only .jpg extension files from indexing.
IndexIgnore directive uses wildcard expression to match against directories and files.
a star character , it matches any charactes in a string ,eg : foo or foo.extension, in the following example, we are going to turn off the directory listing, no files or dirs will appear in the index :
IndexIgnore *
Or if you want to hide spacific files , in the directory listing, then we can use
IndexIgnore *.php
*.php => matches a string that starts with any char and ends with .php
The example above hides all files that end with .php
Python
element.get_attribute("attribute name")
Java
element.getAttribute("attribute name")
Ruby
element.attribute("attribute name")
C#
element.GetAttribute("attribute name");
You may use NULL
instead of NA
. This creates a truly empty data frame.
In Bootstrap 4, there is a new utility known as .mx-auto
. You just need to specify the width of the centered element.
Ref: http://v4-alpha.getbootstrap.com/utilities/spacing/#horizontal-centering
Diffferent from Bass Jobsen's answer, which is a relative center to the elements on both ends, the following example is absolute centered.
Here's the HTML:
<nav class="navbar bg-faded">
<div class="container">
<ul class="nav navbar-nav pull-sm-left">
<li class="nav-item">
<a class="nav-link" href="#">Link 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 4</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-logo mx-auto">
<li class="nav-item">
<a class="nav-link" href="#">Brand</a>
</li>
</ul>
<ul class="nav navbar-nav pull-sm-right">
<li class="nav-item">
<a class="nav-link" href="#">Link 5</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 6</a>
</li>
</ul>
</div>
</nav>
And CSS:
.navbar-logo {
width: 90px;
}
This works.
$("div.row-form input[type='checkbox']").attr('checked','checked');
The string function split can take an option boolean argument 'expand'.
Here is a solution using this argument:
(a.var1
.str.split(",",expand=True)
.set_index(a.var2)
.stack()
.reset_index(level=1, drop=True)
.reset_index()
.rename(columns={0:"var1"}))
Make sure your DataGrid has Width
set to something like {Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window,AncestorLevel=1}}
.
Like that, your setting of Width="*"
attribute on DataGrid.Columns/DataGridXXXXColumn
elements should work.
i use this
<style>
html, body{height:100%;margin:0;padding:0 0}
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
You can use jquery function.
<form name='add'>
<input type='text' name='stud_name' id="stud_name" value=""/>
Age: <select name='age' id="age">
<option value='1' stud_name='sre'>23</option>
<option value='2' stud_name='sam'>24</option>
<option value='5' stud_name='john'>25</option>
</select>
<input type='submit' name='submit'/>
</form>
jquery code :
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function() {
$("#age").change(function(){
var option = $('option:selected', this).attr('stud_name');
$('#stud_name').val(option);
});
});
</script>
You can use a CSS3 transition
for this. Have a look at this example:
Here is the main code:
#box {
position : relative;
width : 100px;
height : 100px;
background-color : gray;
border : 5px solid black;
-webkit-transition : border 500ms ease-out;
-moz-transition : border 500ms ease-out;
-o-transition : border 500ms ease-out;
transition : border 500ms ease-out;
}
#box:hover {
border : 10px solid red;
}
this is my blog on git and its for beginners who want to get started on git. https://techxposers.com/git-for-beginners/
The code commented works as well, just choose which do you prefer
import numpy as np
from PIL import Image
def convert_from_cv2_to_image(img: np.ndarray) -> Image:
# return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
return Image.fromarray(img)
def convert_from_image_to_cv2(img: Image) -> np.ndarray:
# return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
return np.asarray(img)
I assume your talking about windows forms:
To display your form use the Show() method:
Form form2 = new Form();
form2.Show();
to close the form use Close():
form2.Close();
The below 'd help you to add the cert to the Root Store-
certutil -enterprise -f -v -AddStore "Root" <Cert File path>
This worked for me perfectly.
In your head element add
<script type="text/javascript" src="myscript.js"></script>
If you need to override IE's Compatibility View Settings for intranet sites you can do so in the web.config (IIS7) or through the custom HTTP headers in the web site's properties (IIS6) and set X-UA-Compatible there. The meta tag doesn't override IE's intranet setting in Compatibility View Settings, but if you set it at the hosting server it will override the compatibility.
Example for web.config in IIS7:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=EmulateIE8" />
</customHeaders>
</httpProtocol>
</system.webServer>
Edit: I removed the clear
code from just before the add
; it was an unnecessary oversight from copying and pasting. Good catch, commenters!
I'm surprised nobody pointed out JSON's []
method, which makes it very easy and transparent to decode and encode from/to JSON.
If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.
Consider this:
require 'json'
hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"
str
now contains the JSON encoded hash
.
It's easy to reverse it using:
JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}
Custom objects need to_s
defined for the class, and inside it convert the object to a Hash then use to_json
on it.
By the Spring guys, used for Grails reloading but works with Java too:
Here is another solution, If you are using ES6 using spread operator:
var arr = [0, 21, 22, 7];
const indexOfMaxValue = arr.indexOf(Math.max(...arr));
ZZ
(works like :wq
)
And about the cursor position: I found that a cursor which always stays in the middle of screen is cool -
set scrolloff=9999
This should work
SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;
I have assumed the ** were just for highlighting?
The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format
<TextBox Text="{Binding Value, StringFormat={}{0:#,0.0}}"
See if you can recreate the issue in an Incognito tab. If you find that the problem no longer occurs then I would recommend you go through your extensions, perhaps disabling them one at a time. This is commonly the cause as touched on by Nikola
My understanding is that set and get are for computed properties (no backing from stored properties)
if you are coming from an Objective-C bare in mind that the naming conventions have changed. In Swift an iVar or instance variable is named stored property
var test : Int {
get {
return test
}
}
This will result in a warning because this results in a recursive function call (the getter calls itself).The warning in this case is "Attempting to modify 'test' within its own getter".
var test : Int {
get {
return test
}
set (aNewValue) {
//I've contrived some condition on which this property can be set
//(prevents same value being set)
if (aNewValue != test) {
test = aNewValue
}
}
}
Similar problem - you cannot do this as it's recursively calling the setter. Also, note this code will not complain about no initialisers as there is no stored property to initialise.
Here is a pattern that allows conditional setting of an actual stored property
//True model data
var _test : Int = 0
var test : Int {
get {
return _test
}
set (aNewValue) {
//I've contrived some condition on which this property can be set
if (aNewValue != test) {
_test = aNewValue
}
}
}
Note The actual data is called _test (although it could be any data or combination of data) Note also the need to provide an initial value (alternatively you need to use an init method) because _test is actually an instance variable
//True model data
var _test : Int = 0 {
//First this
willSet {
println("Old value is \(_test), new value is \(newValue)")
}
//value is set
//Finaly this
didSet {
println("Old value is \(oldValue), new value is \(_test)")
}
}
var test : Int {
get {
return _test
}
set (aNewValue) {
//I've contrived some condition on which this property can be set
if (aNewValue != test) {
_test = aNewValue
}
}
}
Here we see willSet and didSet intercepting a change in an actual stored property. This is useful for sending notifications, synchronisation etc... (see example below)
//Underlying instance variable (would ideally be private)
var _childVC : UIViewController? {
willSet {
//REMOVE OLD VC
println("Property will set")
if (_childVC != nil) {
_childVC!.willMoveToParentViewController(nil)
self.setOverrideTraitCollection(nil, forChildViewController: _childVC)
_childVC!.view.removeFromSuperview()
_childVC!.removeFromParentViewController()
}
if (newValue) {
self.addChildViewController(newValue)
}
}
//I can't see a way to 'stop' the value being set to the same controller - hence the computed property
didSet {
//ADD NEW VC
println("Property did set")
if (_childVC) {
// var views = NSDictionaryOfVariableBindings(self.view) .. NOT YET SUPPORTED (NSDictionary bridging not yet available)
//Add subviews + constraints
_childVC!.view.setTranslatesAutoresizingMaskIntoConstraints(false) //For now - until I add my own constraints
self.view.addSubview(_childVC!.view)
let views = ["view" : _childVC!.view] as NSMutableDictionary
let layoutOpts = NSLayoutFormatOptions(0)
let lc1 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("|[view]|", options: layoutOpts, metrics: NSDictionary(), views: views)
let lc2 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: layoutOpts, metrics: NSDictionary(), views: views)
self.view.addConstraints(lc1)
self.view.addConstraints(lc2)
//Forward messages to child
_childVC!.didMoveToParentViewController(self)
}
}
}
//Computed property - this is the property that must be used to prevent setting the same value twice
//unless there is another way of doing this?
var childVC : UIViewController? {
get {
return _childVC
}
set(suggestedVC) {
if (suggestedVC != _childVC) {
_childVC = suggestedVC
}
}
}
Note the use of BOTH computed and stored properties. I've used a computed property to prevent setting the same value twice (to avoid bad things happening!); I've used willSet and didSet to forward notifications to viewControllers (see UIViewController documentation and info on viewController containers)
I hope this helps, and please someone shout if I've made a mistake anywhere here!
Before I continue, I must warn you that itoa
is NOT an ANSI function — it's not a standard C function. You should use sprintf
to convert an int
into a string.
itoa
takes three arguments.
char *
variable, so you should pass in a normal sized char array and it will work fine.The function returns a pointer to its second argument — where it has stored the converted string.
itoa
is a very useful function, which is supported by some compilers - it's a shame it isn't support by all, unlike atoi
.
If you still want to use itoa
, here is how should you use it. Otherwise, you have another option using sprintf
(as long as you want base 8, 10 or 16 output):
char str[5];
printf("15 in binary is %s\n", itoa(15, str, 2));
I had the same question but about rather short vector<bool>
(afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):
-O0 -O3
-------- --------
memset 0.666 1.045
fill 19.357 1.066
iterator 67.368 1.043
assign 17.975 0.530
for i 22.610 1.004
So apparently for these sizes, vector<bool>::assign()
is faster. The code used for tests:
#include <vector>
#include <cstring>
#include <cstdlib>
#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;
using namespace std;
int main(int argc, char** argv) {
std::vector<int> v(TEST_ARRAY_SIZE, 0);
for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
std::fill(v.begin(), v.end(), false);
#elif TEST_METHOD == 3
for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
*it = 0;
}
#elif TEST_METHOD == 4
v.assign(v.size(),false);
#elif TEST_METHOD == 5
for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
v[i] = false;
}
#endif
}
return EXIT_SUCCESS;
}
I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:
g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp
The best safe way is: <%= sanitize @x %>
It will avoid XSS!
Since you're using Spring Boot, I assume you'd prefer to rely on Spring's auto configuration where possible. To add additional custom configuration like your interceptors, just provide a configuration or bean of WebMvcConfigurerAdapter
.
Here's an example of a config class:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
HandlerInterceptor yourInjectedInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(...)
...
registry.addInterceptor(getYourInterceptor());
registry.addInterceptor(yourInjectedInterceptor);
// next two should be avoid -- tightly coupled and not very testable
registry.addInterceptor(new YourInterceptor());
registry.addInterceptor(new HandlerInterceptor() {
...
});
}
}
NOTE do not annotate this with @EnableWebMvc, if you want to keep Spring Boots auto configuration for mvc.
If you try it on CellContentClick
Event
Use:
dataGridView1.EndEdit(); //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
From:
http://gking.harvard.edu/zelig/docs/How_do_I2.html (mirror)
Windows users may get the error that R has run out of memory.
If you have R already installed and subsequently install more RAM, you may have to reinstall R in order to take advantage of the additional capacity.
You may also set the amount of available memory manually. Close R, then right-click on your R program icon (the icon on your desktop or in your programs directory). Select ``Properties'', and then select the ``Shortcut'' tab. Look for the ``Target'' field and after the closing quotes around the location of the R executible, add
--max-mem-size=500M
as shown in the figure below. You may increase this value up to 2GB or the maximum amount of physical RAM you have installed.
If you get the error that R cannot allocate a vector of length x, close out of R and add the following line to the ``Target'' field:
--max-vsize=500M
or as appropriate. You can always check to see how much memory R has available by typing at the R prompt
memory.limit()
which gives you the amount of available memory in MB. In previous versions of R you needed to use: round(memory.limit()/2^20, 2)
.
Not the best solution, but here is what I got:
1) Annotate getter you want to initialize with this annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface Lazy {
}
2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:
public <T> void forceLoadLazyCollections(T entity) {
Session session = getSession().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.refresh(entity);
if (entity == null) {
throw new RuntimeException("Entity is null!");
}
for (Method m : entityClass.getMethods()) {
Lazy annotation = m.getAnnotation(Lazy.class);
if (annotation != null) {
m.setAccessible(true);
logger.debug(" method.invoke(obj, arg1, arg2,...); {} field", m.getName());
try {
Hibernate.initialize(m.invoke(entity));
}
catch (Exception e) {
logger.warn("initialization exception", e);
}
}
}
}
finally {
session.close();
}
}
I usually use the Fusion Log Viewer (Fuslogvw.exe from a Visual Studio command prompt or Fusion Log Viewer from the start menu) - my standard setup is:
c:\FusionLogs
(Important: make sure that you have actually created this folder in the file system.)Remember to turn of logging off once you're done!
(I just posted this on a similar question - I think it's relevant here too.)
i'd try tinyproxy. in fact, the vey best would be to embedd a scripting language there... sounds like a perfect job for Lua, especially after seeing how well it worked for mysqlproxy
Here's an example of how you might concatenate email addresses from a table into a single @recipients parameter:
CREATE TABLE #emailAddresses (email VARCHAR(25))
INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')
DECLARE @recipients VARCHAR(MAX)
SELECT @recipients = COALESCE(@recipients + ';', '') + email
FROM #emailAddresses
SELECT @recipients
DROP TABLE #emailAddresses
The resulting @recipients will be:
Try the following code :
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];
By combining existing answers (this one and this one) the proper type safe way to add an ArrayList
to a JComboBox
is the following:
private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
In your GUI
code you set the entire list into your JComboBox
as follows:
DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);
This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.
var mySkus = myLines.Select(x => x.Sku);
Or if you want it as an Array just do...
var mySkus = myLines.Select(x => x.Sku).ToArray();
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));
I hope this would be helpful:
.top_image img{
display: block;
margin: 0 auto;
}
Use the values
attribute to return the values as a np array and then use [0]
to get the first value:
In [4]:
df.loc[df.Letters=='C','Letters'].values[0]
Out[4]:
'C'
EDIT
I personally prefer to access the columns using subscript operators:
df.loc[df['Letters'] == 'C', 'Letters'].values[0]
This avoids issues where the column names can have spaces or dashes -
which mean that accessing using .
.
Me - nothing was helping in changing the v11.0 value of VisualStudioVersion variable to v10.0. Changing variable in .csproj file didn't. Setting it through command promt didn't. Etc...
Ended up copying my local folder of that specific version (v11.0) to my build server.
If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:
SQL> connect SYSTEM/fyicenter
Connected.
SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
2 FROM USER_TABLESPACES;
TABLESPACE_NAME STATUS CONTENTS
------------------------------ --------- ---------
SYSTEM ONLINE PERMANENT
UNDO ONLINE UNDO
SYSAUX ONLINE PERMANENT
TEMP ONLINE TEMPORARY
USERS ONLINE PERMANENT
http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html
Check the project properties. It's configurable there if you are using another .net windows application for example
The easiest way to set the version in Android Studio:
1. Press SHIFT+CTRL+ALT+S (or File -> Project Structure -> app)
Android Studio < 3.4:
Android Studio >= 3.4:
just changed Application's target framework to ".Net Framework 4".
And error got Disappeared.
good luck; :D
Try this in your .htaccess:
.htaccess
ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]
RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]
# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]
The ErrorDocument
redirects all 404s to a specific URL, all 500s to another url (replace with your domain).
The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.
Local Redirect:
Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):
ErrorDocument 404 /pages/errors/404_redirect.php
404_redirect.php
<?php
header('Location: /404/');
exit;
?>
Redirect based on error number
Looks like you'll need to specify an ErrorDocument
line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.
error_redirect.php
<?php
$error_url = $_SERVER["REDIRECT_STATUS"] . '/';
$error_path = $error_url . '.php';
if ( ! file_exists($error_path)) {
// this is the default error if a specific error page is not found
$error_url = '404/';
}
header('Location: ' . $error_url);
exit;
?>
You can use unsigned assemblies if your assembly is also unsigned.
itertools.product
Available from Python 2.6.
import itertools
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
for element in itertools.product(*somelists):
print(element)
Which is the same as,
for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
print(element)
You may have also put your console.log
after an expectation that fails and is uncaught, so your log line never gets executed.
First, you need to compile your code with appropriate flags, enabling debug into code.
$ gcc -Wall -g -ggdb -o ex1 ex1.c
then just run you code with your favourite debugger
$ gdb ./ex1
show me the code.
(gdb) list
1 #include <stdio.h>
2 int main(void)
3 {
4 int i = 0;
5 for(i=0;i<7;++i)
6 printf("%d\n", i);
7
8 return 0;
9 }
break on lines 5 and looks if i == 5.
(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i
checking breakpoints
(gdb) info b
Num Type Disp Enb Address What
1 breakpoint keep y 0x00000000004004fb in main at ex1.c:5
breakpoint already hit 1 time
5 read watchpoint keep y i
stop only if i==5
running the program
(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i
Value = 5
0x0000000000400523 in main () at ex1.c:5
5 for(i=0;i<7;++i)
You can use the length()
method on File
which returns the size in bytes.
$_SERVER['HTTP_REFERER']
will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _
, is that a typo?
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
SELECT * FROM
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser
Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.
As of now in 2017, you can just write
$(window).on('wheel', function(event){
// deltaY obviously records vertical scroll, deltaX and deltaZ exist too
if(event.originalEvent.deltaY < 0){
// wheeled up
}
else {
// wheeled down
}
});
Works with current Firefox 51, Chrome 56, IE9+
React (or JSX) doesn't support variable interpolation inside an attribute value, but you can put any JS expression inside curly braces as the entire attribute value, so this works:
<img className="image" src={"images/" + this.props.image} />
For phpMyAdmin I figured this out:
SELECT GROUP_CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" SEPARATOR ' ') AS OneSQLString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="yourtableschemaname"
AND TABLE_TYPE="BASE TABLE"
Just change yourtableschemaname and you're fine.
...and on my 64 bit W7 machine, with VB6 installed... in DOS, as Admin, this worked to solve an OCX problem I was having with a VB6 App:
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
YES! This solution solved the problem I had using MSCAL.OCX (The Microsoft Calendar Control) in VB6.
Thank you guys! :-)
<table id="table_id" class="table table-hover">
<thead>
<tr>
...
...
</tr>
</thead>
</table>
use this command to clear the body of that table: $("#table_id tbody").empty()
I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.
hope this helps you.
You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.
Actually the answer by ƒernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.
Looking at your code I am assuming the Notification
simply isn't showing.
Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification
will not show without one.
addAction
is only available since 4.1. Prior to that you would use the PendingIntent
to launch an Activity
. You seem to specify a PendingIntent
, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.
Using
dependencies:
connectivity: ^0.4.2
what we got from resouces is
import 'package:connectivity/connectivity.dart';
Future<bool> check() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
Future is little problematic for me, we have to implement it every single time like :
check().then((intenet) {
if (intenet != null && intenet) {
// Internet Present Case
}
// No-Internet Case
});
So to solve this problem i have created a class Which accept a function with boolean isNetworkPresent parameter like this
methodName(bool isNetworkPresent){}
And the Utility Class is
import 'package:connectivity/connectivity.dart'; class NetworkCheck { Future<bool> check() async { var connectivityResult = await (Connectivity().checkConnectivity()); if (connectivityResult == ConnectivityResult.mobile) { return true; } else if (connectivityResult == ConnectivityResult.wifi) { return true; } return false; } dynamic checkInternet(Function func) { check().then((intenet) { if (intenet != null && intenet) { func(true); } else{ func(false); } }); } }
And to use connectivity-check utilty
fetchPrefrence(bool isNetworkPresent) {
if(isNetworkPresent){
}else{
}
}
i will use this syntax
NetworkCheck networkCheck = new NetworkCheck();
networkCheck.checkInternet(fetchPrefrence)
You can do it with drop_duplicates
as you wanted
# initialisation
d = pd.DataFrame({'A' : [1,1,2,3,3], 'B' : [2,2,7,4,4], 'C' : [1,4,1,0,8]})
d = d.sort_values("C", ascending=False)
d = d.drop_duplicates(["A","B"])
If it's important to get the same order
d = d.sort_index()
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
Must check whether incoming access to port 3306 is block or not by the firewall.
In my case, I disabled McAfee and then successfully installed tensorflow2.0 RC
Not with CSS, but you can emulate and extend / customize the desired behavior with JavaScript.
@miyuru. As suggested by him run all the steps.
Ubuntu version 16.04
Still when I ran docker --version
it was returning a version. So to uninstall it completely
Again run the dpkg -l | grep -i docker
which will list package still there in system.
For example:
ii docker-ce-cli 5:19.03.6~3-0~ubuntu-xenial
amd64 Docker CLI: the open-source application container engine
Now remove them as show below :
sudo apt-get purge -y docker-ce-cli
sudo apt-get autoremove -y --purge docker-ce-cli
sudo apt-get autoclean
Hope this will resolve it, as it did in my case.
Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.
Below is my original answer.
It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.
There is no native IF/ELSE for CSS available. CSS preprocessors like SASS (and Compass) can help, but if you’re looking for more feature-specific if/else conditions you should give Modernizr a try. It does feature-detection and then adds classes to the HTML element to indicate which CSS3 & HTML5 features the browser supports and doesn’t support. You can then write very if/else-like CSS right in your CSS without any preprocessing, like this:
.geolocation #someElem {
/* only apply this if the browser supports Geolocation */
}
.no-geolocation #someElem {
/* only apply this if the browser DOES NOT support Geolocation */
}
Keep in mind that you should always progressively enhance, so rather than the above example (which illustrates the point better), you should write something more like this:
#someElem {
/* default styles, suitable for both Geolocation support and lack thereof */
}
.geolocation #someElem {
/* only properties as needed to overwrite the default styling */
}
Note that Modernizr does rely on JavaScript, so if JS is disabled you wouldn’t get anything. Hence the progressive enhancement approach of #someElem first, as a no-js foundation.
Just remember:
So, choose the way what you want to handle your branch.
You'd better know the difference between merge and rebase :)
Welcome to 2020 here is the answer in Python/Django:
from django.conf import settings
import boto3
s3 = boto3.client('s3')
s3.delete_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=f"media/{item.file.name}")
Took me far too long to find the answer and it was as simple as this.
Just leaving this here for future visitors:
In my case the /WEB-INF/classes directory was missing. If you are using Eclipse, make sure the .settings/org.eclipse.wst.common.component is correct (Deployment Assembly in the project settings).
In my case it was missing
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/resources"/>
This file is also a common source of errors as mentioned by Anuj (missing dependencies of other projects).
Otherwise, hopefully the other answers (or the "Problems" tab) will help you.
If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :
var postData = $('#yourform').serializeArray();
// postData (array with objects) :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]
...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :
postData.push({"name": "phone", "value": "1234-123456"});
Result:
// postData :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]
You should also read about python packages here: http://docs.python.org/tutorial/modules.html.
From your example, I would guess that you really have a package at ~/codez/project
. The file __init__.py
in a python directory maps a directory into a namespace. If your subdirectories all have an __init__.py
file, then you only need to add the base directory to your PYTHONPATH
. For example:
PYTHONPATH=$PYTHONPATH:$HOME/adaifotis/project
In addition to testing your PYTHONPATH environment variable, as David explains, you can test it in python like this:
$ python
>>> import project # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line # print current python path
...
I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.
with Kotlin I execute this code:
requireContext().startActivity<YourTargetActivity>()
Why does it have to be encoded? A request looks like this:
GET /url HTTP/1.1
(Ignoring headers)
There are 3 fields separated by a white space. If you put a space in your url:
GET /url end_url HTTP/1.1
You know have 4 fields, the HTTP server will tell you it is an invalid request.
GET /url%20end_url HTTP/1.1
3 fields => valid
Note: in the query string (after ?), a space is usually encoded as a +
GET /url?var=foo+bar HTTP/1.1
rather than
GET /url?var=foo%20bar HTTP/1.1
You can do it like this:
row_id = 5;
row = $("body").find('#'+row_id);
As alluded to by Eric, you can use environ with ComputerName argument like so:
MsgBox Environ("USERNAME")
Some additional information that might be helpful for you to know:
Sub EnumSEVars()
Dim strVar As String
Dim i As Long
For i = 1 To 255
strVar = Environ$(i)
If LenB(strVar) = 0& Then Exit For
Debug.Print strVar
Next
End Sub
Unformatted and formatted:
$price = $product->getPrice();
$formatted = Mage::helper('core')->currency($price, true, false);
Or use:
Mage::helper('core')->formatPrice($price, true);
Using the base
package:
df <- data.frame(days = c(88, 11, 2, 5, 22, 1, 222, 2), name = c("Lynn", "Tom", "Chris", "Lisa", "Kyla", "Tom", "Lynn", "Lynn"))
# Three lines
target <- c("Tom", "Lynn")
index <- df$name %in% target
df[index, ]
# One line
df[df$name %in% c("Tom", "Lynn"), ]
Output:
days name
1 88 Lynn
2 11 Tom
6 1 Tom
7 222 Lynn
8 2 Lynn
Using sqldf
:
library(sqldf)
# Two alternatives:
sqldf('SELECT *
FROM df
WHERE name = "Tom" OR name = "Lynn"')
sqldf('SELECT *
FROM df
WHERE name IN ("Tom", "Lynn")')
ngOnInit() {
const $ = window["$"];
$('.flexslider').flexslider({
animation: 'slide',
start: function (slider) {
$('body').removeClass('loading')
}
})
}
If you decide to learn both (and as other people have mentioned, there's no explicit need to learn both), learn C first. Going from C to C++ feels like a natural progression; going the other way feels like deliberately tying one hand behind your back. :-)
Also, if someone need the Infs' coordinates, can do this:
library(rlist)
list.clean(apply(df, 2, function(x){which(is.infinite(x))}), function(x) length(x) == 0L, TRUE)
Result:
$colname1
[1] row1 row2 ...
$colname2
[2] row1 row2 ...
With this information, you can replace the Inf values in particular places with the mean, median, or whatever operator that you want.
For example (for element 01):
repInf = list.clean(apply(df, 2, function(x){which(is.infinite(x))}), function(x) length(x) == 0L, TRUE)
df[repInf[[1]], names(repInf)[[1]]] = median or mean(is.finite(df[ ,names(repInf)[[1]]]), na.rm = TRUE)
In loop:
for (nonInf in 1:length(repInf)) {
df[repInf[[nonInf]], names(repInf)[[nonInf]]] = mean(is.finite(df[ , names(repInf)[[nonInf]]]))
}
I think it is jar file version problem. I had the same issue and I fixed it by changing the commons-codec-1.6.jar file from the build path. Earlier I was using latest version 1.10. Gradually I decreased the versions and 1.6 version fixed my issue.
Like this:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
The $(this)
refers to the current .target
which will be looped through. Within this .target
I'm looking for the .scrolling img
and get the width. And then keep on going...
Images with different widths
If you want to calculate the width of all images (when they have different widths) you can do it like this:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
This is how i registered my domain:
sudo letsencrypt --apache -d mydomain.com
Then it was possible to use the same command with additional domains and follow the instructions:
sudo letsencrypt --apache -d mydomain.com,x.mydomain.com,y.mydomain.com
Math.min
uses a simple comparison to do its thing. The only advantage to not using Math.min is to save the extra function calls, but that is a negligible saving.
If you have more than just three numbers, having a minimum
method for any number of double
s might be valuable and would look something like:
public static double min(double ... numbers) {
double min = numbers[0];
for (int i=1 ; i<numbers.length ; i++) {
min = (min <= numbers[i]) ? min : numbers[i];
}
return min;
}
For three numbers this is the functional equivalent of Math.min(a, Math.min(b, c));
but you save one method invocation.
Thanks Jason Rogers's answer first.
In Android && cpp should be this:
const char *nativeString = env->GetStringUTFChars(javaString, nullptr);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
Can fix this errors:
1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'
2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'
3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'
4.add "env->DeleteLocalRef(nativeString);" at end.
Extra ( ) brackets may create problems in else if flow. This also creates Syntax error (missing operator) in query expression.
do you mean empty or null, two different things,
if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null
Here's a code implementation of @tatarize's answer, using PIXI.js. I have a viewport looking at part of a very big image (e.g. google maps style).
$canvasContainer.on('wheel', function (ev) {
var scaleDelta = 0.02;
var currentScale = imageContainer.scale.x;
var nextScale = currentScale + scaleDelta;
var offsetX = -(mousePosOnImage.x * scaleDelta);
var offsetY = -(mousePosOnImage.y * scaleDelta);
imageContainer.position.x += offsetX;
imageContainer.position.y += offsetY;
imageContainer.scale.set(nextScale);
renderer.render(stage);
});
$canvasContainer
is my html container.imageContainer
is my PIXI container that has the image in it.mousePosOnImage
is the mouse position relative to the entire image (not just the view port).Here's how I got the mouse position:
imageContainer.on('mousemove', _.bind(function(ev) {
mousePosOnImage = ev.data.getLocalPosition(imageContainer);
mousePosOnViewport.x = ev.data.originalEvent.offsetX;
mousePosOnViewport.y = ev.data.originalEvent.offsetY;
},self));
You have to use $_POST['date']
instead of $date
if it's coming from a POST request ($_GET if it's a GET request).
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
For my case, I had to right click the solution and click "Retarget Projects".
In my case I retargetted to Windows SDK version 10.0.1777.0 and Platform Toolset v142. I also had to change "Windows.h"
to<windows.h>
I am running Visual Studio 2019 version 16.25 on a windows 10 machine
To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.
Open the properties for the project, go to the Build
tab and check the Allow unsafe code
checkbox.
For those who want to change disable, checked and enabled states you cat do the following steps:
<!-- Or androidX radio button or material design radio button -->
<android.support.v7.widget.AppCompatRadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="@color/black"
android:text="Radiobutton1"
app:buttonTint="@color/radio_button_color" />
then in color res folder make a file named "radio_button_color.xml":
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/yellow900" android:state_selected="true" />
<item android:color="@color/yellow800" android:state_checked="true" />
<item android:color="@color/gray800" android:state_enabled="false" />
<item android:color="@color/yellow800" android:state_enabled="true" />
</selector>
Use \D
to match non-digit characters.
preg_replace('~\D~', '', $str);
I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.
For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.
If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.
SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD
In my experience, just pick a relatively high number (between 1024-65535) that you think is unlikely to be used by anything else. For example, port # 8080 and # 5555 are ones that I routinely use. Just pick a port number like this as opposed to just making the code randomly select it and then having to find the port number later is much easier for me.
For example, in my current ChatBot project:
port = 8080
I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity
, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.
Sample use:
<input type="number" formControlName="num" placeholder="0" ntvFormValidity>
Directive definition:
import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';
@Directive({
selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {
constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }
/*
- Angular doesn't fire "change" events for invalid <input type="number">
- We have to check the DOM object for browser native invalid state
- Add custom validator that checks native invalidity
*/
ngAfterViewInit() {
var control: FormControl = this.cn.control;
// Bridge native invalid to ng-invalid via Validators
const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
const v_fn = control.validator;
control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
setTimeout(()=>control.updateValueAndValidity(), 0);
}
}
The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.
On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".
I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.
Something like this:
<my-input-number formControlName="num" placeholder="0">
PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers
on the declaration, please let me know so I can update my Directive (and this answer).
This is how I would do it
myArray.splice( myArray.indexOf('bar') , 1)
The correct character (comma or colon) depends on the purpose.
Comma (,
) will sum only the two cells in question.
Colon (:
) will sum all the cells within the range with corners defined by those two cells.
I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.
The Problem: you trying to create new container while in background container with same name is running and this situation causes conflicts.
The error would be like:
Cannot create continer for service X :Conflict. The name X is already in use by container abc123xyz. You have to remove ot delete (or rename) that container to be able to reuse that name.
Solution rename the service name in docker-compose.yml
or delete the running container and rebuild it again (this solution related to Unix/Linux/macOS systems):
sudo docker ps -a
sudo docker stop <container_id>
sudo docker rm <container_id>
or
sudo docker rm --force <container_id>
I think this is the best method how to do that
Array Push Example
public void ArrayPush<T>(ref T[] table, object value)
{
Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
table.SetValue(value, table.Length - 1); // Setting the value for the new element
}
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
Even easier: via the requests module.
import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)
To send data that is not form-encoded, send it serialised as a string (example taken from the documentation):
import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
Collections.singletonList(object)
the list created by this method is immutable.
Store your results in variables, and use them in your HTML and add the necessary styling.
$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];
And in the HTML, you could do:
<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>
Now, you can simply add the styles for country
class in your CSS, like so:
#userdetails {
/* styles go here */
}
Alternatively, you could also use this in your HTML:
<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>
Hope this helps!
The accepted answer by Kev to this question doesn't actually give any code, it just points to other resources that I don't have access to. So here's my best attempt at the function. It actually checks that the permission it's looking at is a "Write" permission and that the current user belongs to the appropriate group.
It might not be complete with regard to network paths or whatever, but it's good enough for my purpose, checking local configuration files under "Program Files" for writability:
using System.Security.Principal;
using System.Security.AccessControl;
private static bool HasWritePermission(string FilePath)
{
try
{
FileSystemSecurity security;
if (File.Exists(FilePath))
{
security = File.GetAccessControl(FilePath);
}
else
{
security = Directory.GetAccessControl(Path.GetDirectoryName(FilePath));
}
var rules = security.GetAccessRules(true, true, typeof(NTAccount));
var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool result = false;
foreach (FileSystemAccessRule rule in rules)
{
if (0 == (rule.FileSystemRights &
(FileSystemRights.WriteData | FileSystemRights.Write)))
{
continue;
}
if (rule.IdentityReference.Value.StartsWith("S-1-"))
{
var sid = new SecurityIdentifier(rule.IdentityReference.Value);
if (!currentuser.IsInRole(sid))
{
continue;
}
}
else
{
if (!currentuser.IsInRole(rule.IdentityReference.Value))
{
continue;
}
}
if (rule.AccessControlType == AccessControlType.Deny)
return false;
if (rule.AccessControlType == AccessControlType.Allow)
result = true;
}
return result;
}
catch
{
return false;
}
}
Perhaps manager app does not exist look if you the manager application is on $APACHE_HOME/server/webapps directory. on this directory you must have : docs,examples, host-manager,manager, ROOT.
On CentOS 5.x, installing curl-devel fixed the problem for me.
With parent::$bb;
you try to retrieve the static constant defined with the value of $bb
.
Instead, do:
echo $this->bb;
Note: you don't need to call parent::_construct
if B is the only class that calls it. Simply don't declare __construct in B class.
Update: Bespin is now ACE, which is mentioned by the highest rated answer here. Use ACE instead.
Gotta go with Bespin by Mozilla. It's built using HTML5 features (so it's quick and fast, but doesn't support legacy browsers though), but definitely amazing to use and beats everything I've come across - probably beacause it's Mozilla backing it, and they develop Firefox so yeah... There's also a jQuery Plugin which contains a extension for it to make it a bit easier to use with jQuery.
You can do something like this:
$('.notice')
.fadeIn()
.animate({opacity: '+=0'}, 2000) // Does nothing for 2000ms
.fadeOut('fast');
Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.