Running assembly Code on Mac is just 3 steps away from you. It could be done using XCODE but better is to use NASM Command Line Tool. For My Ease I have already installed Xcode, if you have Xcode installed its good.
But You can do it without XCode as well.
Just Follow:
brew install nasm
nasm -f macho64 myFile.asm
ld -macosx_version_min 10.7.0 -lSystem -o OutPutFile myFile.o && ./64
Simple Text File named myFile.asm is written below for your convenience.
global start
section .text
start:
mov rax, 0x2000004 ; write
mov rdi, 1 ; stdout
mov rsi, msg
mov rdx, msg.len
syscall
mov rax, 0x2000001 ; exit
mov rdi, 0
syscall
section .data
msg: db "Assalam O Alaikum Dear", 10
.len: equ $ - msg
I had the same problem and tried all possible solution. But finally I came to know from the documentation that ngRoute
module is now separated. Have a look to this link
Solution: Add the cdn angular-route.js after angular.min.js script
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
same for Terminator
Ctrl + Shift + V
Look at your terminal key-bindings if any if that doesn't work
Encountered this issue in chrome. Resolved by cleaning up related cookies. Note that you don't have to cleanup ALL your cookies.
I ran into this while I was learning Go 2 years ago, so I declared my own function.
// UNUSED allows unused variables to be included in Go programs
func UNUSED(x ...interface{}) {}
And then you can use it like so:
UNUSED(x)
UNUSED(x, y)
UNUSED(x, y, z)
The great thing about it is, you can pass anything into UNUSED.
Is it better than the following?
_, _, _ = x, y, z
That's up to you.
If Zip Code
allows characters and digits (alphanumeric), below regex would be used where it matches, 5 or 9 or 10 alphanumeric characters with one hypen (-
):
^([0-9A-Za-z]{5}|[0-9A-Za-z]{9}|(([0-9a-zA-Z]{5}-){1}[0-9a-zA-Z]{4}))$
I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.
ul li{
text-indent: -1em;
}
I have found solution by editing code as per following. There is no need to set Binding property first False then True.
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d != null && d is Control)
{
var _Control = d as Control;
if ((bool)e.NewValue)
{
// To set false value to get focus on control. if we don't set value to False then we have to set all binding
//property to first False then True to set focus on control.
OnLostFocus(_Control, null);
_Control.Focus(); // Don't care about false values.
}
}
}
private static void OnLostFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control)
{
(sender as Control).SetValue(IsFocusedProperty, false);
}
}
}
I juste wrote a proxy in nodejs that take care of HTTPS with optional decoding of the message. This proxy also can add proxy-authentification header in order to go through a corporate proxy. You need to give as argument the url to find the proxy.pac file in order to configurate the usage of corporate proxy.
To render any json in tabular format:
<table>
<thead>
<tr>
<th ng-repeat="(key, value) in vm.records[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in vm.records">
<td ng-repeat="(key, value) in value">
{{value}}
</td>
</tr>
</tbody>
</table>
As far as best practices, keep an eye for recursive functions. In my case I ran into issues with recursion (where there didn't need to be). A simplified example of what I was doing:
def my_function():
# lots of memory intensive operations
# like operating on images or huge dictionaries and lists
.....
my_flag = True
if my_flag: # restart the function if a certain flag is true
my_function()
def main():
my_function()
operating in this recursive manner won't trigger the garbage collection and clear out the remains of the function, so every time through memory usage is growing and growing.
My solution was to pull the recursive call out of my_function() and have main() handle when to call it again. this way the function ends naturally and cleans up after itself.
def my_function():
# lots of memory intensive operations
# like operating on images or huge dictionaries and lists
.....
my_flag = True
.....
return my_flag
def main():
result = my_function()
if result:
my_function()
Atom is open source (has been for a few hours by now), whereas Sublime Text is not.
Try
but.addEventListener('click', yourFunction)
Note the absence of parantheses ()
after the function name. This is because you are assigning the function, not calling it.
Well, this is easy to achieve .
Just build a GradientDrawable
that comes from black and goes to a transparent color, than use parent relationship to place your shape close to the View that you want to have a shadow, then you just have to give any values to height or width .
Here is an example, this file have to be created inside res/drawable
, I name it as shadow.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#9444"
android:endColor="#0000"
android:type="linear"
android:angle="90"> <!-- Change this value to have the correct shadow angle, must be multiple from 45 -->
</gradient>
</shape>
Place the following code above from a LinearLayout
, for example, set the android:layout_width
and android:layout_height
to fill_parent
and 2.3dp
, you'll have a nice shadow effect on your LinearLayout
.
<View
android:id="@+id/shadow"
android:layout_width="fill_parent"
android:layout_height="2.3dp"
android:layout_above="@+id/id_from_your_LinearLayout"
android:background="@drawable/shadow">
</View>
Note 1: If you increase android:layout_height
more shadow will be shown .
Note 2: Use android:layout_above="@+id/id_from_your_LinearLayout"
attribute if you are placing this code inside a RelativeLayout, otherwise ignore it.
Hope it help someone.
I like the answers from The Aelfinn and aheld. I can improve them only by shortening a bit more, removing superfluous pieces, using a real data source, making it 2.x & 3.x-compatible, and maintaining the high-level of memory-efficiency seen elsewhere:
import csv
import requests
CSV_URL = 'http://web.cs.wpi.edu/~cs1004/a16/Resources/SacramentoRealEstateTransactions.csv'
with requests.get(CSV_URL, stream=True) as r:
lines = (line.decode('utf-8') for line in r.iter_lines())
for row in csv.reader(lines):
print(row)
Too bad 3.x is less flexible CSV-wise because the iterator must emit Unicode strings (while requests
does bytes
) while the 2.x-only version—for row in csv.reader(r.iter_lines()):
—is more Pythonic (shorter and easier-to-read). Anyhow, note the 2.x/3.x solution above won't handle the situation described by the OP where a NEWLINE is found unquoted in the data read.
For the part of the OP's question regarding downloading (vs. processing) the actual CSV file, here's another script that does that, 2.x & 3.x-compatible, minimal, readable, and memory-efficient:
import os
import requests
CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'
with open(os.path.split(CSV_URL)[1], 'wb') as f, \
requests.get(CSV_URL, stream=True) as r:
for line in r.iter_lines():
f.write(line+'\n'.encode())
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
or:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);
I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.
abstract class Base
{
protected int myInt;
protected abstract void setMyInt();
}
class Derived : Base
{
override protected void setMyInt()
{
myInt = 3;
}
}
By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.
abstract class Father
{
abstract public int MyInt { get; }
}
class Son : Father
{
public override int MyInt
{
get { return 1; }
}
}
You could try letting the stream throw an exception on failure:
std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);
try {
f.open(fileName);
}
catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
e.what()
, however, does not seem to be very helpful:
strerror(errno)
gives "No such file or directory."If e.what()
does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition
(C++11 only):
catch (std::ios_base::failure& e) {
if ( e.code() == std::make_error_condition(std::io_errc::stream) )
std::cerr << "Stream error!\n";
else
std::cerr << "Unknown failure opening file.\n";
}
I was looking for a solution to enumerate an array of an unknown at compile time rank with an access to every element indices set. I saw solutions with yield but here is another implementation with no yield. It is in old school minimalistic way. In this example AppendArrayDebug() just prints all the elements into StringBuilder buffer.
public static void AppendArrayDebug ( StringBuilder sb, Array array )
{
if( array == null || array.Length == 0 )
{
sb.Append( "<nothing>" );
return;
}
int i;
var rank = array.Rank;
var lastIndex = rank - 1;
// Initialize indices and their boundaries
var indices = new int[rank];
var lower = new int[rank];
var upper = new int[rank];
for( i = 0; i < rank; ++i )
{
indices[i] = lower[i] = array.GetLowerBound( i );
upper[i] = array.GetUpperBound( i );
}
while( true )
{
BeginMainLoop:
// Begin work with an element
var element = array.GetValue( indices );
sb.AppendLine();
sb.Append( '[' );
for( i = 0; i < rank; ++i )
{
sb.Append( indices[i] );
sb.Append( ' ' );
}
sb.Length -= 1;
sb.Append( "] = " );
sb.Append( element );
// End work with the element
// Increment index set
// All indices except the first one are enumerated several times
for( i = lastIndex; i > 0; )
{
if( ++indices[i] <= upper[i] )
goto BeginMainLoop;
indices[i] = lower[i];
--i;
}
// Special case for the first index, it must be enumerated only once
if( ++indices[0] > upper[0] )
break;
}
}
For example the following array will produce the following output:
var array = new [,,]
{
{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } },
{ { 13, 14, 15 }, { 16, 17, 18 }, { 19, 20, 21 }, { 22, 23, 24 } }
};
/*
Output:
[0 0 0] = 1
[0 0 1] = 2
[0 0 2] = 3
[0 1 0] = 4
[0 1 1] = 5
[0 1 2] = 6
[0 2 0] = 7
[0 2 1] = 8
[0 2 2] = 9
[0 3 0] = 10
[0 3 1] = 11
[0 3 2] = 12
[1 0 0] = 13
[1 0 1] = 14
[1 0 2] = 15
[1 1 0] = 16
[1 1 1] = 17
[1 1 2] = 18
[1 2 0] = 19
[1 2 1] = 20
[1 2 2] = 21
[1 3 0] = 22
[1 3 1] = 23
[1 3 2] = 24
*/
Modify the background image of the <td> itself.
Or apply some css to the div:
.thatSetsABackgroundWithAnIcon{
height:100%;
}
By the way, there is a pure-Python implementation of percentile function, in case one doesn't want to depend on scipy. The function is copied below:
## {{{ http://code.activestate.com/recipes/511478/ (r1)
import math
import functools
def percentile(N, percent, key=lambda x:x):
"""
Find the percentile of a list of values.
@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.
@return - the percentile of the values
"""
if not N:
return None
k = (len(N)-1) * percent
f = math.floor(k)
c = math.ceil(k)
if f == c:
return key(N[int(k)])
d0 = key(N[int(f)]) * (c-k)
d1 = key(N[int(c)]) * (k-f)
return d0+d1
# median is 50th percentile.
median = functools.partial(percentile, percent=0.5)
## end of http://code.activestate.com/recipes/511478/ }}}
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.
HTML:
<body>
<div id="content">...</div>
</body>
CSS:
#content {
max-width: 1000px;
margin: auto;
left: 1%;
right: 1%;
position: absolute;
}
JavaScript (using jQuery):
$(function() {
$(window).on('resize', function resize() {
$(window).off('resize', resize);
setTimeout(function () {
var content = $('#content');
var top = (window.innerHeight - content.height()) / 2;
content.css('top', Math.max(0, top) + 'px');
$(window).on('resize', resize);
}, 50);
}).resize();
});
Yes you can which is Peer-To-Peer Mode
Peer-To-Peer Mode
Bidirectional P2P connection to exchange data between devices
–Proximity triggered interactions
–Nexus S: Devices have to be placed back-to-back
Example of Applications
–Exchange of vCards
–Hand-over of Tickets & P2P Payment
–Web-page sharing, Youtube-video-sharing
–Application sharing
This task can be accomplished without blueprints and tricky imports using Centralized URL Map
app.py
import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
views.py
from flask import render_template
def index():
return render_template('index.html')
def other():
return render_template('other.html')
For PyCharm 2017
We can follow below: File >> Settings >> Editor >> Code Style.
Then provide values for Hard Wrap
& Visual Guides
for wrapping
while typing, tick the checkbox.
NB: look at other tabs as well, viz. Python, HTML, JSON etc.
A convenient way would be boost's string algorithms library.
#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
// ...
std::vector<std::string> words;
std::string s;
boost::split(words, s, boost::is_any_of(", "), boost::token_compress_on);
If you use phpMyAdmin, it can tell you this information.
Just go to "Databases" (menu on top) and click "Enable Statistics".
You will see something like this:
This will probably lose some accuracy as the sizes go up, but it should be accurate enough for your purposes.
People arguing about the corner radius being slightly increased but actually that's not the case.
From this blog:
A ‘secret’ of Apple’s physical products is that they avoid tangency (where a radius meets a line at a single point) and craft their surfaces with what’s called curvature continuity.
You don't need to apply corner radius to icons for iOS. Just provide square icons. But if you still want to know how, the actual shape is called Squircle and below is the formula:
Cody has it right, but I want to provide an example of what an inline function is.
Let's say you have this code:
private void OutputItem(string x)
{
Console.WriteLine(x);
//maybe encapsulate additional logic to decide
// whether to also write the message to Trace or a log file
}
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{ // let's pretend IEnumerable<T>.ToList() doesn't exist for the moment
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
OutputItem(y);
}
return result;
}
The compilerJust-In-Time optimizer could choose to alter the code to avoid repeatedly placing a call to OutputItem() on the stack, so that it would be as if you had written the code like this instead:
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
// full OutputItem() implementation is placed here
Console.WriteLine(y);
}
return result;
}
In this case, we would say the OutputItem() function was inlined. Note that it might do this even if the OutputItem() is called from other places as well.
Edited to show a scenario more-likely to be inlined.
You can add style for :after a like html code.
For example:
var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
you can use DbFunctions.TruncateTime() method for this.
e => DbFunctions.TruncateTime(e.FirstDate.Value) == DbFunctions.TruncateTime(SecondDate);
I found this to be a little more accurate:
SELECT
owner, table_name, TRUNC(sum(bytes)/1024/1024/1024) GB
FROM
(SELECT segment_name table_name, owner, bytes
FROM dba_segments
WHERE segment_type in ('TABLE','TABLE PARTITION')
UNION ALL
SELECT i.table_name, i.owner, s.bytes
FROM dba_indexes i, dba_segments s
WHERE s.segment_name = i.index_name
AND s.owner = i.owner
AND s.segment_type in ('INDEX','INDEX PARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.segment_name
AND s.owner = l.owner
AND s.segment_type IN ('LOBSEGMENT','LOB PARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.index_name
AND s.owner = l.owner
AND s.segment_type = 'LOBINDEX')
---WHERE owner in UPPER('&owner')
GROUP BY table_name, owner
HAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */
ORDER BY SUM(bytes) desc
I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.
It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.
Pick the values in a servlet ie.
String username = request.getParameter("username");
String password = request.getParameter("password");
Then Store the Values inside the Session:
HttpSession sess = request.getSession();
sess.setAttribute("username", username);
sess.setAttribute("password", password);
These values Will be available anywhere in the Application as long as the session is valid.
HttpSession sess = request.getSession(false); //use false to use the existing session
sess.getAttribute("username");//this will return username anytime in the session
sess.getAttribute("password");//this will return password Any time in the session
I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl
in the JSPs:
${username}//this will give you the username in the JSP
${password}// this will give you the password in the JSP
In MVC IP can be obtained by the following Code
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
You can use GLOBIGNORE environment variable in Bash.
Suppose you want to delete all files except php and sql, then you can do the following -
export GLOBIGNORE=*.php:*.sql
rm *
export GLOBIGNORE=
Setting GLOBIGNORE like this ignores php and sql from wildcards used like "ls *" or "rm *". So, using "rm *" after setting the variable will delete only txt and tar.gz file.
Also, you can try use CustomScrollView
CustomScrollView(
controller: _scrollController,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final OrderModel order = _orders[index];
return Container(
margin: const EdgeInsets.symmetric(
vertical: 8,
),
child: _buildOrderCard(order, size, context),
);
},
childCount: _orders.length,
),
),
SliverToBoxAdapter(
child: _buildPreloader(context),
),
],
);
Tip: _buildPreloader
return CircularProgressIndicator
or Text
In my case i want to show under ListView some widgets. Use Column
does't work me, because widgets around ListView inside Column showing always "up" on the screen, like "position absolute"
Sorry for my bad english
Inline styling would work in any case
<p-column field="Quantity" header="Qté" [style]="{'width':'48px'}">
I also use OleDbDataReader.IsDBNull()
if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
i was facing the same problem in the wp-admin section of the site. I enqueued the underscore script cdn and it fixed the problem.
function kk_admin_scripts() {
wp_enqueue_script('underscore', '//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js' );
}
add_action( 'admin_enqueue_scripts', 'kk_admin_scripts' );
Just to be sure that this is really the "conversion" you need, please note that jks
files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.
So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool
(but in a more accessible way).
Basically, what this error is saying is that if you are going to use the GROUP BY
clause, then your result is going to be a relation/table with a row for each group, so in your SELECT
statement you can only "select" the column that you are grouping by and use aggregate functions on that column because the other columns will not appear in the resulting table.
the origin server can create the resource with that URI
So you use POST and probably, but not necessary PUT for resource creation. You don't have to support both. For me POST is perfectly enough. So it is a design decision.
As your quote mentioned, you use PUT for creation of there is no resource assigned to an IRI, and you want to create a resource anyway. For example, PUT /users/123/password
usually replaces the old password with a new one, but you can use it to create a password if it does not exist already (for example, by freshly registered users or by restoring banned users).
I've mixed @mevius and @Boldewyn Code to Create this ultimate code for email verification using JavaScript.
function ValidateEmail(email){_x000D_
_x000D_
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;_x000D_
_x000D_
var input = document.createElement('input');_x000D_
_x000D_
input.type = 'email';_x000D_
input.value = email;_x000D_
_x000D_
return typeof input.checkValidity == 'function' ? input.checkValidity() : re.test(email);_x000D_
_x000D_
}
_x000D_
I have shared this code on my blog here.
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
package com.acn.demo.action;
public class RemoveCharFromString {
static String input = "";
public static void main(String[] args) {
input = "abadbbeb34erterb";
char token = 'b';
removeChar(token);
}
private static void removeChar(char token) {
// TODO Auto-generated method stub
System.out.println(input);
for (int i=0;i<input.length();i++) {
if (input.charAt(i) == token) {
input = input.replace(input.charAt(i), ' ');
System.out.println("MATCH FOUND");
}
input = input.replaceAll(" ", "");
System.out.println(input);
}
}
}
You can create a thread just like this:
Thread thread = new Thread(new Runnable() {
public void run() {
}
});
thread.start();
Also, you can use Runnable, Asyntask, Timer, TimerTaks and AlarmManager to excecute Threads.
Create a border view with the background color as the color of the border and size of your text view. set border view padding as the width of the border. Set text view background color as the color you want for the text view. Now add your text view inside the border view.
Just echo the javascript out inside the if function
<form name="testForm" id="testForm" method="POST" >
<input type="submit" name="btn" value="submit" autofocus onclick="return true;"/>
</form>
<?php
if(isset($_POST['btn'])){
echo "
<script type=\"text/javascript\">
var e = document.getElementById('testForm'); e.action='test.php'; e.submit();
</script>
";
}
?>
A friend showed me how to do this as follows:
"./" works when the file requesting the image (e.g., "example.js") is on the same level within the folder tree structure as the folder "images".
Under certain circumstances, IE6 will still cache files even when Cache-Control: no-cache
is in the response headers.
If the no-cache directive does not specify a field-name, then a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server.
In my application, if you visited a page with the no-cache
header, then logged out and then hit back in your browser, IE6 would still grab the page from the cache (without a new/validating request to the server). Adding in the no-store
header stopped it doing so. But if you take the W3C at their word, there's actually no way to control this behavior:
History buffers MAY store such responses as part of their normal operation.
General differences between browser history and the normal HTTP caching are described in a specific sub-section of the spec.
I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.
You can find it on Github
Here are the simple steps to creating and using custom iterators:
typedef blRawIterator< Type > iterator;
typedef blRawIterator< const Type > const_iterator;
iterator begin(){return iterator(&m_data[0]);};
const_iterator cbegin()const{return const_iterator(&m_data[0]);};
Finally, onto defining our custom iterator classes:
NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.
In this example, I define a random access iterator and a reverse random access iterator:
//-------------------------------------------------------------------
// Raw iterator with random access
//-------------------------------------------------------------------
template<typename blDataType>
class blRawIterator
{
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = blDataType;
using difference_type = std::ptrdiff_t;
using pointer = blDataType*;
using reference = blDataType&;
public:
blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
~blRawIterator(){}
blRawIterator<blDataType>& operator=(const blRawIterator<blDataType>& rawIterator) = default;
blRawIterator<blDataType>& operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
operator bool()const
{
if(m_ptr)
return true;
else
return false;
}
bool operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
bool operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
blRawIterator<blDataType>& operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
blRawIterator<blDataType>& operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
blRawIterator<blDataType>& operator++(){++m_ptr;return (*this);}
blRawIterator<blDataType>& operator--(){--m_ptr;return (*this);}
blRawIterator<blDataType> operator++(int){auto temp(*this);++m_ptr;return temp;}
blRawIterator<blDataType> operator--(int){auto temp(*this);--m_ptr;return temp;}
blRawIterator<blDataType> operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
blRawIterator<blDataType> operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
difference_type operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
blDataType& operator*(){return *m_ptr;}
const blDataType& operator*()const{return *m_ptr;}
blDataType* operator->(){return m_ptr;}
blDataType* getPtr()const{return m_ptr;}
const blDataType* getConstPtr()const{return m_ptr;}
protected:
blDataType* m_ptr;
};
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Raw reverse iterator with random access
//-------------------------------------------------------------------
template<typename blDataType>
class blRawReverseIterator : public blRawIterator<blDataType>
{
public:
blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
~blRawReverseIterator(){}
blRawReverseIterator<blDataType>& operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
blRawReverseIterator<blDataType>& operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
blRawReverseIterator<blDataType>& operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
blRawReverseIterator<blDataType>& operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
blRawReverseIterator<blDataType>& operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
blRawReverseIterator<blDataType>& operator++(){--this->m_ptr;return (*this);}
blRawReverseIterator<blDataType>& operator--(){++this->m_ptr;return (*this);}
blRawReverseIterator<blDataType> operator++(int){auto temp(*this);--this->m_ptr;return temp;}
blRawReverseIterator<blDataType> operator--(int){auto temp(*this);++this->m_ptr;return temp;}
blRawReverseIterator<blDataType> operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
blRawReverseIterator<blDataType> operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
difference_type operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
blRawIterator<blDataType> base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
};
//-------------------------------------------------------------------
Now somewhere in your custom container class:
template<typename blDataType>
class blCustomContainer
{
public: // The typedefs
typedef blRawIterator<blDataType> iterator;
typedef blRawIterator<const blDataType> const_iterator;
typedef blRawReverseIterator<blDataType> reverse_iterator;
typedef blRawReverseIterator<const blDataType> const_reverse_iterator;
.
.
.
public: // The begin/end functions
iterator begin(){return iterator(&m_data[0]);}
iterator end(){return iterator(&m_data[m_size]);}
const_iterator cbegin(){return const_iterator(&m_data[0]);}
const_iterator cend(){return const_iterator(&m_data[m_size]);}
reverse_iterator rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
reverse_iterator rend(){return reverse_iterator(&m_data[-1]);}
const_reverse_iterator crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
const_reverse_iterator crend(){return const_reverse_iterator(&m_data[-1]);}
.
.
.
// This is the pointer to the
// beginning of the data
// This allows the container
// to either "view" data owned
// by other containers or to
// own its own data
// You would implement a "create"
// method for owning the data
// and a "wrap" method for viewing
// data owned by other containers
blDataType* m_data;
};
public static decimal TruncateDecimalPlaces(this decimal value, int precision)
{
try
{
step = (decimal)Math.Pow(10, precision);
decimal tmp = Math.Truncate(step * value);
return tmp / step;
}
catch (OverflowException)
{
step = (decimal)Math.Pow(10, -1 * precision);
return value - (value % step);
}
}
I had a similar problem using Django. In my case, I could import the module from the Django shell, but not from a .py which imported the module.
The problem was that I was running the Django server (therefore, executing the .py) from a different virtualenv from which the module had been installed.
Instead, the shell instance was being run in the correct virtualenv. Hence, why it worked.
Had the same issue with arrays, here is how to do it if you're manipulating arrays too :
array_name="ARRAY_NAME"
ARRAY_NAME=("Val0" "Val1" "Val2")
ARRAY=$array_name[@]
echo "ARRAY=${ARRAY}"
ARRAY=("${!ARRAY}")
echo "ARRAY=${ARRAY[@]}"
echo "ARRAY[0]=${ARRAY[0]}"
echo "ARRAY[1]=${ARRAY[1]}"
echo "ARRAY[2]=${ARRAY[2]}"
This will output :
ARRAY=ARRAY_NAME[@]
ARRAY=Val0 Val1 Val2
ARRAY[0]=Val0
ARRAY[1]=Val1
ARRAY[2]=Val2
Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>
It's a ton more portable, easier to use and more feature packed too.
There's a RemoveDuplicates
method that you could use:
Sub DeleteRows()
With ActiveSheet
Set Rng = Range("A1", Range("B1").End(xlDown))
Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End With
End Sub
Regarding reporting, we use it on all of our reporting queries to prevent a query from bogging down databases. We can do that because we're pulling historical data, not up-to-the-microsecond data.
After you install the Android SDK in Eclipse
, it generates a debug signing certificate for you in a keystore called debug.keystore. The Eclipse plug-in uses this certificate to sign each application build that is generated.
Now, the problem with this debug certificate is that it is only valid for a year, or 365 days. If your Eclipse IDE uses an expired debug certificate, you will not be able to create and/or deploy an Android app
.
To fix this problem all you need to do is delete the debug.keystore file.
Go to Preferences
Android
Build
Default debug keystore
There you should see the folder where the file is located. Simply delete that file and you are good to go.
For more info. you can visit
http://developer.android.com/tools/publishing/app-signing.html
EDIT: don't use vc80 / Visual Studio 2005, but Visual Studio 2008 / vc90 versions of the CGAL library (maybe from here).
You could also compile with /Z7, so the pdb doesn't need to be used, or remove the /DEBUG linker option if you do not have .pdb files for the objects you are linking.
*This example is updated for ES6 classes and TypeScript.
First off, and factually, Javascript is a prototypal language, not class-based. Its true nature is expressed in the prototypial form below, which you may come to see that is very simple, prose-like, yet powerful.
const Person = {
name: 'Anonymous', // person has a name
greet: function() { console.log(`Hi, I am ${this.name}.`}
}
const jack = Object.create(Person) // jack is a person
jack.name = 'Jack' // and has a name 'Jack'
jack.greet() // outputs "Hi, I am Jack."
This absolves the sometimes convoluted constructor pattern. A new object inherits from the old one, but is able to have its own properties. If we attempt to obtain a member from the new object (#greet()
) which the new object jack
lacks, the old object Person
will supply the member.
You don't need constructors, no new
instantiation (read why you shouldn't use new
), no super
, no self-made __construct
. You simply create Objects and then extend or morph them.
This pattern also offers immutability (partial or full), and getters/setters.
The TypeScript equivalent looks the same:
interface Person {
name: string,
greet: Function
}
const Person = {
name: 'Anonymous',
greet: function(): void { console.log(`Hi, I am ${this.name}.` }
}
const jack: Person = Object.create(Person)
jack.name = 'Jack'
jack.greet()
Person
protoypeconst Person = {
//attributes
firstName : 'Anonymous',
lastName: 'Anonymous',
birthYear : 0,
type : 'human',
//methods
name() { return this.firstName + ' ' + this.lastName },
greet() {
console.log('Hi, my name is ' + this.name() + ' and I am a ' + this.type + '.' )
},
age() {
// age is a function of birth time.
}
}
const person = Object.create(Person). // that's it!
Clean and clear. It's simplicity does not compromise features. Read on.
Person
Note: The correct terms are
prototypes
, and theirdescendants/copies
. There are noclasses
, and no need forinstances
.
const Skywalker = Object.create(Person)
Skywalker.lastName = 'Skywalker'
const anakin = Object.create(Skywalker)
anakin.firstName = 'Anakin'
anakin.birthYear = '442 BBY'
anakin.gender = 'male' // you can attach new properties.
anakin.greet() // 'Hi, my name is Anakin Skywalker and I am a human.'
Person.isPrototypeOf(Skywalker) // outputs true
Person.isPrototypeOf(anakin) // outputs true
Skywalker.isPrototypeOf(anakin) // outputs true
If you feel less safe throwing away the constructors in-lieu of direct assignments, fair point. One common way is to attach a #create
method:
Skywalker.create = function(firstName, gender, birthYear) {
let skywalker = Object.create(Skywalker)
Object.assign(skywalker, {
firstName,
birthYear,
gender,
lastName: 'Skywalker',
type: 'human'
})
return skywalker
}
const anakin = Skywalker.create('Anakin', 'male', '442 BBY')
Person
prototype to Robot
When you branch the Robot
descendant from Person
prototype, you do not affect Skywalker
and anakin
:
// create a `Robot` prototype by extending the `Person` prototype:
const Robot = Object.create(Person)
Robot.type = 'robot'
Attach methods unique to Robot
Robot.machineGreet = function() {
/*some function to convert strings to binary */
}
// Mutating the `Robot` object doesn't affect `Person` prototype and its descendants
anakin.machineGreet() // error
Person.isPrototypeOf(Robot) // outputs true
Robot.isPrototypeOf(Skywalker) // outputs false
In TypeScript you would also need to extend the Person
interface:
interface Robot extends Person {
machineGreet: Function
}
const Robot: Robot = Object.create(Person)
Robot.machineGreet = function(): void { console.log(101010) }
const darthVader = Object.create(anakin)
// for brevity, property assignments are skipped because you get the point by now.
Object.assign(darthVader, Robot)
Darth Vader gets the methods of Robot
:
darthVader.greet() // inherited from `Person`, outputs "Hi, my name is Darth Vader..."
darthVader.machineGreet() // inherited from `Robot`, outputs 001010011010...
Along with other odd things:
console.log(darthVader.type) // outputs robot.
Robot.isPrototypeOf(darthVader) // returns false.
Person.isPrototypeOf(darthVader) // returns true.
Which elegantly reflects the "real-life" subjectivity:
"He's more machine now than man, twisted and evil." - Obi-Wan Kenobi
"I know there is good in you." - Luke Skywalker
function Person (firstName, lastName, birthYear, type) {
this.firstName = firstName
this.lastName = lastName
this.birthYear = birthYear
this.type = type
}
// attaching methods
Person.prototype.name = function() { return firstName + ' ' + lastName }
Person.prototype.greet = function() { ... }
Person.prototype.age = function() { ... }
function Skywalker(firstName, birthYear) {
Person.apply(this, [firstName, 'Skywalker', birthYear, 'human'])
}
// confusing re-pointing...
Skywalker.prototype = Person.prototype
Skywalker.prototype.constructor = Skywalker
const anakin = new Skywalker('Anakin', '442 BBY')
// #isPrototypeOf won't work
Person.isPrototypeOf(anakin) // returns false
Skywalker.isPrototypeOf(anakin) // returns false
If you want to increase code readability, you have to go for ES6 classes, which has increased in adoptation and browser compatibility (or a non-concern with babel):
class Person {
constructor(firstName, lastName, birthYear, type) {
this.firstName = firstName
this.lastName = lastName
this.birthYear = birthYear
this.type = type
}
name() { return this.firstName + ' ' + this.lastName }
greet() { console.log('Hi, my name is ' + this.name() + ' and I am a ' + this.type + '.' ) }
}
class Skywalker extends Person {
constructor(firstName, birthYear) {
super(firstName, 'Skywalker', birthYear, 'human')
}
}
const anakin = new Skywalker('Anakin', '442 BBY')
// prototype chain inheritance checking is partially fixed.
Person.isPrototypeOf(anakin) // returns false!
Skywalker.isPrototypeOf(anakin) // returns true
Admittedly, some of these problems are eradicated by the ES6 classes. When I wrote my answer five years ago, ES6 classes were budding, and has now matured for use.
But underneath the hood of ES6 classes is the obscured true prototypial nature of Javascript. So I was naturally disappointed of its implementation.
Nonetheless, that's not to say ES6 classes are bad. It provides a lot of new features and standardised a manner that is reasonably readable. Though it really should have not used the operator class
and new
to confuse the whole issue.
Writability, Configurability and Free Getters and Setters!
For free getters and setters, or extra configuration, you can use Object.create()'s second argument a.k.a propertiesObject. It is also available in #Object.defineProperty, and #Object.defineProperties.
To illustrate its usefulness, suppose we want all Robot
to be strictly made of metal (via writable: false
), and standardise powerConsumption
values (via getters and setters).
const Robot = Object.create(Person, {
// define your property attributes
madeOf: {
value: "metal",
writable: false,
configurable: false,
enumerable: true
},
// getters and setters
powerConsumption: {
get() { return this._powerConsumption },
set(value) {
if (value.indexOf('MWh')) return this._powerConsumption = value.replace('M', ',000k')
this._powerConsumption = value
throw new Error('Power consumption format not recognised.')
}
}
})
const newRobot = Object.create(Robot)
newRobot.powerConsumption = '5MWh'
console.log(newRobot.powerConsumption) // outputs 5,000kWh
And all prototypes of Robot
cannot be madeOf
something else:
const polymerRobot = Object.create(Robot)
polymerRobot.madeOf = 'polymer'
console.log(polymerRobot.madeOf) // outputs 'metal'
Here the code to use your app.js
input specifies file name
res.download(__dirname+'/'+input);
This worked. C:\Program Files\Android\Android Studio\gradle\gradle-3.2
If you want a quick-and-dirty one liner, use this:
fs.existsSync("directory") || fs.mkdirSync("directory");
If
should be if
. Your program should look like this:
answer = raw_input("Is the information correct? Enter Y for yes or N for no")
if answer.upper() == 'Y':
print("this will do the calculation")
else:
exit()
Note also that the indentation is important, because it marks a block in Python.
On top of previous answers, I'd like to raise awareness about the fact that you should use the RAII (Resource Acquisition Is Initialisation) idiom to be safe about handler destruction.
Here is a complete working example:
Interface declaration: Interface.hpp
:
class Base {
public:
virtual ~Base() {}
virtual void foo() const = 0;
};
using Base_creator_t = Base *(*)();
Shared library content:
#include "Interface.hpp"
class Derived: public Base {
public:
void foo() const override {}
};
extern "C" {
Base * create() {
return new Derived;
}
}
Dynamic shared library handler: Derived_factory.hpp
:
#include "Interface.hpp"
#include <dlfcn.h>
class Derived_factory {
public:
Derived_factory() {
handler = dlopen("libderived.so", RTLD_NOW);
if (! handler) {
throw std::runtime_error(dlerror());
}
Reset_dlerror();
creator = reinterpret_cast<Base_creator_t>(dlsym(handler, "create"));
Check_dlerror();
}
std::unique_ptr<Base> create() const {
return std::unique_ptr<Base>(creator());
}
~Derived_factory() {
if (handler) {
dlclose(handler);
}
}
private:
void * handler = nullptr;
Base_creator_t creator = nullptr;
static void Reset_dlerror() {
dlerror();
}
static void Check_dlerror() {
const char * dlsym_error = dlerror();
if (dlsym_error) {
throw std::runtime_error(dlsym_error);
}
}
};
Client code:
#include "Derived_factory.hpp"
{
Derived_factory factory;
std::unique_ptr<Base> base = factory.create();
base->foo();
}
Note:
.hpp
and .cpp
files.new
/delete
overload.Two clear articles to get more details:
For SQL Server 2005+, if there is no insert trigger, then change the insert statement (all one line, split for clarity here) to this
INSERT INTO aspnet_GameProfiles(UserId,GameId)
OUTPUT INSERTED.ID
VALUES(@UserId, @GameId)
For SQL Server 2000, or if there is an insert trigger:
INSERT INTO aspnet_GameProfiles(UserId,GameId)
VALUES(@UserId, @GameId);
SELECT SCOPE_IDENTITY()
And then
Int32 newId = (Int32) myCommand.ExecuteScalar();
It seems like an IllegalArgumentException
is called for if you don't want null
to be an allowed value, and the NullPointerException
would be thrown if you were trying to use a variable that turns out to be null
.
There are lots of good reasons for setting the size of a frame. One is to remember the last size the user set, and restore those settings. I have this code which seems to work for me:
package javatools.swing;
import java.util.prefs.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class FramePositionMemory {
public static final String WIDTH_PREF = "-width";
public static final String HEIGHT_PREF = "-height";
public static final String XPOS_PREF = "-xpos";
public static final String YPOS_PREF = "-ypos";
String prefix;
Window frame;
Class<?> cls;
public FramePositionMemory(String prefix, Window frame, Class<?> cls) {
this.prefix = prefix;
this.frame = frame;
this.cls = cls;
}
public void loadPosition() {
Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
// Restore the most recent mainframe size and location
int width = prefs.getInt(prefix + WIDTH_PREF, frame.getWidth());
int height = prefs.getInt(prefix + HEIGHT_PREF, frame.getHeight());
System.out.println("WID: " + width + " HEI: " + height);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int xpos = (screenSize.width - width) / 2;
int ypos = (screenSize.height - height) / 2;
xpos = prefs.getInt(prefix + XPOS_PREF, xpos);
ypos = prefs.getInt(prefix + YPOS_PREF, ypos);
frame.setPreferredSize(new Dimension(width, height));
frame.setLocation(xpos, ypos);
frame.pack();
}
public void storePosition() {
Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
prefs.putInt(prefix + WIDTH_PREF, frame.getWidth());
prefs.putInt(prefix + HEIGHT_PREF, frame.getHeight());
Point loc = frame.getLocation();
prefs.putInt(prefix + XPOS_PREF, (int)loc.getX());
prefs.putInt(prefix + YPOS_PREF, (int)loc.getY());
System.out.println("STORE: " + frame.getWidth() + " " + frame.getHeight() + " " + loc.getX() + " " + loc.getY());
}
}
public class Main {
void main(String[] args) {
JFrame frame = new Frame();
// SET UP YOUR FRAME HERE.
final FramePositionMemory fm = new FramePositionMemory("scannacs2", frame, Main.class);
frame.setSize(400, 400); // default size in the absence of previous setting
fm.loadPosition();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
fm.storePosition();
}
});
frame.setVisible(true);
}
}
}
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
For Winforms
private void listBox1_DoubleClick(object sender, MouseEventArgs e)
{
int index = this.listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
MessageBox.Show(listBox1.SelectedItem.ToString());
}
}
and
public Form()
{
InitializeComponent();
listBox1.MouseDoubleClick += new MouseEventHandler(listBox1_DoubleClick);
}
that should also, prevent for the event firing if you select an item then click on a blank area.
Building on answer by user462990
To be notified when the user responds to the permission request dialog, use this: (code in kotlin)
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
when (requestCode) {
MY_PERMISSIONS_REQUEST_READ_CONTACTS -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return
}
// Add other 'when' lines to check for other
// permissions this app might request.
else -> {
// Ignore all other requests.
}
}
}
SQL Server does not track licensing. Customers are responsible for tracking the assignment of licenses to servers, following the rules in the Licensing Guide.
check if the array is null first so you would avoid a null pointer exception
logic in any language: if array is null or is empty :do ....
Problem is not in installer
replace nodejs with node or change the path from /usr/bin/nodejs to /usr/bin/node
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
X = iris['data']
y = iris['target']
iris_df = pd.DataFrame(X, columns = iris['feature_names'])
iris_df.head()
If you can accept Double Objects than this post is helpful: Initialization of an ArrayList in one line
List<Double> y = Arrays.asList(null, 1.0, 2.0);
Double x = y.get(1);
The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.
You can call generic methods with types only known at execution time, but you have to use reflection:
// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
.MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });
Ick.
Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?
If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.
use HTML instead of javascript
<html>_x000D_
<head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
<body>_x000D_
<h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
<svg_x000D_
xmlns="http://www.w3.org/2000/svg"_x000D_
viewBox="0 0 300 300"_x000D_
x="0" y="0" height="300" width="300"_x000D_
>_x000D_
_x000D_
<circle_x000D_
r="142" cx="150" cy="150"_x000D_
fill="none" stroke="#000000" stroke-width="2"_x000D_
/>_x000D_
_x000D_
<foreignObject_x000D_
x="50" y="50" width="200" height="200"_x000D_
>_x000D_
<div_x000D_
xmlns="http://www.w3.org/1999/xhtml"_x000D_
style="_x000D_
width: 196px; height: 196px;_x000D_
border: solid 2px #000000;_x000D_
font-size: 32px;_x000D_
overflow: auto; /* scroll */_x000D_
"_x000D_
>_x000D_
<p>this is html in svg 1</p>_x000D_
<p>this is html in svg 2</p>_x000D_
<p>this is html in svg 3</p>_x000D_
<p>this is html in svg 4</p>_x000D_
</div>_x000D_
</foreignObject>_x000D_
_x000D_
</svg>_x000D_
_x000D_
</body></html>
_x000D_
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])
EDIT2- Yea auto fills the DOM SOZ!
#img_box{
width:90%;
height:90%;
min-width: 400px;
min-height: 400px;
}
check out this fiddle
http://jsfiddle.net/ppumkin/4qjXv/2/
http://jsfiddle.net/ppumkin/4qjXv/3/
and this page
http://www.webmasterworld.com/css/3828593.htm
Removed original answer because it was wrong.
The width is ok- but the height resets to 0
so
min-height: 400px;
As a non-java selenium user, here is the python equivalent to Margus's answer:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class ChromeConsoleLogging(object):
def __init__(self, ):
self.driver = None
def setUp(self, ):
desired = DesiredCapabilities.CHROME
desired ['loggingPrefs'] = { 'browser':'ALL' }
self.driver = webdriver.Chrome(desired_capabilities=desired)
def analyzeLog(self, ):
data = self.driver.get_log('browser')
print(data)
def testMethod(self, ):
self.setUp()
self.driver.get("http://mypage.com")
self.analyzeLog()
Edit: Keeping Python answer in this thread because it is very similar to the Java answer and this post is returned on a Google search for the similar Python question
You can set a property on the form to do this for you if you have a button on the form that closes the form already.
Set the CancelButton
property of the form to that button.
Gets or sets the button control that is clicked when the user presses the Esc key.
If you don't have a cancel button then you'll need to add a KeyDown
handler and check for the Esc key in that:
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
You will also have to set the KeyPreview
property to true.
Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.
However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the ProcessDialogKey
method as follows:
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
I have been using SQLite Database Browser to see the content SQLite DB in Android development. You have to pull the database file from the device first, then open it in SQLite DB Browser.
As of mid-2015, I believe this is the best solution:
<input type="number" pattern="[0-9]*" inputmode="numeric">
This will give you the numeric keypad on both Android and iOS:
It also gives you the expected desktop behavior with the up/down arrow buttons and keyboard friendly up/down arrow key incrementing:
Try it in this code snippet:
<form>_x000D_
<input type="number" pattern="[0-9]*" inputmode="numeric">_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
By combining both type="number"
and pattern="[0-9]*
, we get a solution that works everywhere. And, its forward compatible with the future HTML 5.1 proposed inputmode
attribute.
Note: Using a pattern will trigger the browser's native form validation. You can disable this using the novalidate
attribute, or you can customize the error message for a failed validation using the title
attribute.
If you need to be able to enter leading zeros, commas, or letters - for example, international postal codes - check out this slight variant.
Credits and further reading:
http://www.smashingmagazine.com/2015/05/form-inputs-browser-support-issue/ http://danielfriesen.name/blog/2013/09/19/input-type-number-and-ios-numeric-keypad/
If you want to split a string into more than two columns based on a delimiter you can omit the 'maximum splits' parameter.
You can use:
df['column_name'].str.split('/', expand=True)
This will automatically create as many columns as the maximum number of fields included in any of your initial strings.
A simple example to calculate the memory usage of a block of codes / function using memory_profile, while returning result of the function:
import memory_profiler as mp
def fun(n):
tmp = []
for i in range(n):
tmp.extend(list(range(i*i)))
return "XXXXX"
calculate memory usage before running the code then calculate max usage during the code:
start_mem = mp.memory_usage(max_usage=True)
res = mp.memory_usage(proc=(fun, [100]), max_usage=True, retval=True)
print('start mem', start_mem)
print('max mem', res[0][0])
print('used mem', res[0][0]-start_mem)
print('fun output', res[1])
calculate usage in sampling points while running function:
res = mp.memory_usage((fun, [100]), interval=.001, retval=True)
print('min mem', min(res[0]))
print('max mem', max(res[0]))
print('used mem', max(res[0])-min(res[0]))
print('fun output', res[1])
Credits: @skeept
Once you started the Emulator from one shell, login to another shell & type
adb shell
You should see # prompt
displayed, this is your device(emulator) shell. Now , type following command at adb shell.
mount -o remount rw /sdcard
This will now remount /sdcard
with rw(read-write)
permission & now you can push your files into /sdcard
by using following command from your host shell.
`adb push filename.mp3 /sdcard,`
where filename.mp3 could be any file that you want to push into Android Emulator.
Hope this helps :)
just two commands save my life
1. This will list down all previous HEADs
git reflog
2. This will revert the HEAD to commit that you deleted.
git reset --hard <your deleted commit>
ex. git reset --hard b4b2c02
I had a similar experience.
The error was triggered when I initialize a variable on the driver (master), but then tried to use it on one of the workers. When that happens, Spark Streaming will try to serialize the object to send it over to the worker, and fail if the object is not serializable.
I solved the error by making the variable static.
Previous non-working code
private final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Working code
private static final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Credits:
I would change the query in the following ways:
group by
.left outer join
to ensure that all data is available.count(<fieldname>)
you can eliminate the comparisons to is null
. This is important for the second and third calculated values.mde
table. These use mde.mdeid
.The following version follows your example by using union all
:
SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
SUM(TOTALMAILED) as TotalMailed,
SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
from MailDataExtract
where SentDate is not null
group by SentDate
) union all
(select MDE.ReturnMailDate AS ReceiptDate, 0,
COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by MDE.ReturnMailDate;
)
) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;
The following does something similar using full outer join
:
SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
from MailDataExtract
where SentDate is not null
group by cast(SentDate as date)
) sd full outer join
(select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by cast(MDE.ReturnMailDate as date)
) mde
on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;
<!doctype html>
<html>
<script>
window.print();
</script>
<?php
date_default_timezone_set('Asia/Kolkata');
include 'db.php';
$tot=0;
$id=$_GET['id'];
$sqlinv="SELECT * FROM `sellform` WHERE `id`='$id' ";
$resinv=mysqli_query($conn,$sqlinv);
$rowinv=mysqli_fetch_array($resinv);
?>
<table width="100%">
<tr>
<td style='text-align:center;font-sie:1px'>Veg/NonVeg</td>
</tr>
<tr>
<th style='text-align:center;font-sie:4px'><b>HARYALI<b></th>
</tr>
<tr>
<td style='text-align:center;font-sie:1px'>Ac/NonAC</td>
</tr>
<tr>
<td style='text-align:center;font-sie:1px'>B S Yedurappa Marg,Near Junne Belgaon Naka,P B Road,Belgaum - 590003</td>
</tr>
</table>
<br>
<table width="100%">
<tr>
<td style='text-align:center;font-sie:1'>-----------------------------------------------</td>
</tr>
</table>
<table width="100%" cellspacing='6' cellpadding='0'>
<tr>
<th style='text-align:center;font-sie:1px'>ITEM</th>
<th style='text-align:center;font-sie:1px'>QTY</th>
<th style='text-align:center;font-sie:1px'>RATE</th>
<th style='text-align:center;font-sie:1px'>PRICE</th>
<th style='text-align:center;font-sie:1px' >TOTAL</th>
</tr>
<?php
$sqlitems="SELECT * FROM `sellitems` WHERE `invoice`='$rowinv[0]'";
$resitems=mysqli_query($conn,$sqlitems);
while($rowitems=mysqli_fetch_array($resitems)){
$sqlitems1="SELECT iname FROM `itemmaster` where icode='$rowitems[2]'";
$resitems1=mysqli_query($conn,$sqlitems1);
$rowitems1=mysqli_fetch_array($resitems1);
echo "<tr>
<td style='text-align:center;font-sie:3px' >$rowitems1[0]</td>
<td style='text-align:center;font-sie:3px' >$rowitems[5]</td>
<td style='text-align:center;font-sie:3px' >".number_format($rowitems[4],2)."</td>
<td style='text-align:center;font-sie:3px' >".number_format($rowitems[6],2)."</td>
<td style='text-align:center;font-sie:3px' >".number_format($rowitems[7],2)."</td>
</tr>";
$tot=$tot+$rowitems[7];
}
echo "<tr>
<th style='text-align:right;font-sie:1px' colspan='4'>GRAND TOTAL</th>
<th style='text-align:center;font-sie:1px' >".number_format($tot,2)."</th>
</tr>";
?>
</table>
<table width="100%">
<tr>
<td style='text-align:center;font-sie:1px'>-----------------------------------------------</td>
</tr>
</table>
<br>
<table width="100%">
<tr>
<th style='text-align:center;font-sie:1px'>Thank you Visit Again</th>
</tr>
</table>
<script>
window.close();
</script>
</html>
Print and close new tab window with php and javascript with single button click
How about the PATINDEX function?
The pattern matching in TSQL is not a complete regex library, but it gives you the basics.
(From Books Online)
Wildcard Meaning
% Any string of zero or more characters.
_ Any single character.
[ ] Any single character within the specified range
(for example, [a-f]) or set (for example, [abcdef]).
[^] Any single character not within the specified range
(for example, [^a - f]) or set (for example, [^abcdef]).
You can also just simply do the regular apt-get update
and then, as per the manual, do:
apt-get -V upgrade
-V Show verbose version numbers
Which will show you the current package vs the one which will be upgraded in a format similar to the one bellow:
~# sudo apt-get -V upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
curl (7.38.0-4+deb8u14 => 7.38.0-4+deb8u15)
php5 (5.6.40+dfsg-0+deb8u2 => 5.6.40+dfsg-0+deb8u3)
2 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 12.0 MB of archives.
After this operation, 567 kB of additional disk space will be used.
Do you want to continue? [Y/n]
Use this to search whole page
if($('*').hasClass('mydivclass')){
// Do Stuff
}
It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.
node{
def exists = fileExists 'foo'
if (!exists){
new File('foo').mkdir()
}
dir ('foo') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'bar'
if (!exists){
new File('bar').mkdir()
}
dir ('bar') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'baz'
if (!exists){
new File('baz').mkdir()
}
dir ('baz') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
}
Use the Stringify.Library nuget package
//Default delimiter is ,
var split = new StringConverter().ConvertTo<List<string>>(names);
//You can also have your custom delimiter for e.g. ;
var split = new StringConverter().ConvertTo<List<string>>(names, new ConverterOptions { Delimiter = ';' });
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
model.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
y_pred=model.predict(test_x,batch_size=15)
cm =confusion_matrix(test_y.argmax(axis=1), y_pred.argmax(axis=1))
index = ['neutral','happy','sad']
columns = ['neutral','happy','sad']
cm_df = pd.DataFrame(cm,columns,index)
plt.figure(figsize=(10,6))
sns.heatmap(cm_df, annot=True)
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();
dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);
document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script src="https://momentjs.com/downloads/moment.js"></script>
</body>
</html>
_x000D_
The answer provided by vsync works as long as you don't have accented letters in the input string.
I don't know the reason, but apparently the \b
in regexp matches also accented letters (tested on IE8 and Chrome), so a string like "località"
would be wrongly capitalized converted into "LocalitÀ"
(the à
letter gets capitalized cause the regexp thinks it's a word boundary)
A more general function that works also with accented letters is this one:
String.prototype.toCapitalize = function()
{
return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}
You can use it like this:
alert( "hello località".toCapitalize() );
I have found that the best solution is to branch off your stash and do a resolution afterwards.
git stash branch <branch-name>
if you drop of clear your stash, you may lose your changes and you will have to recur to the reflog.
I have nothing against:
Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
new Array(5+1).join('0').split('').map(parseFloat);
suggested by Zertosh, but in a new ES6 array extensions allow you to do this natively with fill
method. Now IE edge, Chrome and FF supports it, but check the compatibility table
new Array(3).fill(0)
will give you [0, 0, 0]
. You can fill the array with any value like new Array(5).fill('abc')
(even objects and other arrays).
On top of that you can modify previous arrays with fill:
arr = [1, 2, 3, 4, 5, 6]
arr.fill(9, 3, 5) # what to fill, start, end
which gives you: [1, 2, 3, 9, 9, 6]
At top of main file add:
mainDir = __dirname;
Then use it in any file you need:
console.log('mainDir ' + mainDir);
mainDir
is defined globally, if you need it only in current file - use __dirname
instead.main.js
, index.js
, gulpfile.js
.Sorry for comment in an old post but if you want to use an else if statement this will help you
{% if title == source %}
Do This
{% elif title == value %}
Do This
{% else %}
Do This
{% endif %}
For more info see Django Documentation
It might be a good practice to define variables like below:
v_departmentid departments.department_id%TYPE;
NOT like below:
v_departmentid NUMBER(4)
var popupWindow=null;
function popup()
{
popupWindow = window.open('child_page.html','name','width=200,height=200');
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
and then declare these functions in the body tag of parent window
<body onFocus="parent_disable();" onclick="parent_disable();">
As you requested here is the complete html code of the parent window
<html>
<head>
<script type="text/javascript">
var popupWindow=null;
function child_open()
{
popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
<a href="javascript:child_open()">Click me</a>
</body>
</html>
Content of new.jsp below
<html>
<body>
I am child
</body>
</html>
Edit December 2018: Apple seem to have finally added a button for removing the app in certain situations, including apps that never went on sale (thanks to @iwill for pointing that out), basically making the below answer irrelevant.
Edit: turns out the deleted apps still appear in Xcode -> Organizer -> Archives and there is no way to delete them from there even if there are no archives! So more looks like a fake delete of sorts.
Currently (Edit: as of July 2016) there is no way of deleting your app if it never went on sale.
However, all information except for SKU can be edited and thus reused for a new app, including the app name, Bundle ID, icon, etc etc. Because SKU can be anything (some people say they use numbers 1, 2, 3 for example) then it shouldn't be a big deal to use something unrelated for your new app.
(Honestly though I'm hoping Apple will fix this soon. I almost hear some Apple devs finding excuses for not implementing it (you know, it will break the database and will kill innocent pandas) and some managers telling the devs to just frigging do it regardless.)
TLDR:
hostname=XXX
port=443
trust_cert_file_location=`curl-config --ca`
sudo bash -c "echo -n | openssl s_client -showcerts -connect $hostname:$port -servername $hostname \
2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' \
>> $trust_cert_file_location"
Long answer
The basic reason is that your computer doesn't trust the certificate authority that signed the certificate used on the Gitlab server. This doesn't mean the certificate is suspicious, but it could be self-signed or signed by an institution/company that isn't in the list of your OS's list of CAs. What you have to do to circumvent the problem on your computer is telling it to trust that certificate - if you don't have any reason to be suspicious about it.
You need to check the web certificate used for your gitLab server, and add it to your </git_installation_folder>/bin/curl-ca-bundle.crt
.
To check if at least the clone works without checking said certificate, you can set:
export GIT_SSL_NO_VERIFY=1
#or
git config --global http.sslverify false
But that would be for testing only, as illustrated in "SSL works with browser, wget, and curl, but fails with git", or in this blog post.
Check your GitLab settings, a in issue 4272.
To get that certificate (that you would need to add to your curl-ca-bundle.crt
file), type a:
echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpsGitlabPort \
2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
(with 'yourserver.com
' being your GitLab server name, and YourHttpsGitlabPort
is the https port, usually 443
)
To check the CA (Certificate Authority issuer), type a:
echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpsGilabPort \
2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' \
| openssl x509 -noout -text | grep "CA Issuers" | head -1
Note: Valeriy Katkov suggests in the comments to add -servername
option to the openssl command, otherwise the command isn't showed certificate for www.github.com in Valeriy's case.
openssl s_client -showcerts -servername www.github.com -connect www.github.com:443
Findekano adds in the comments:
to identify the location of
curl-ca-bundle.crt
, you could use the command
curl-config --ca
Also, see my more recent answer "github: server certificate verification failed": you might have to renistall those certificates:
sudo apt-get install --reinstall ca-certificates
sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates
git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt
You can use forceUpdate() for more details check (forceUpdate()).
// Shifting bytes is more efficient // You can use this one too
public static String getHexString (String s)
{
byte[] buf = s.getBytes();
StringBuffer sb = new StringBuffer();
for (byte b:buf)
{
sb.append(String.format("%x", b));
}
return sb.toString();
}
Quick Answer with Main Points
Pretty much the same answer as the best chosen answer from @Joum, to quicken your quest of trying to achieve the answer to the posted question and save time from deciphering whats going on in the syntax --
Answer
Set position attribute to fixed, set the top and bottom attributes to your liking for the element or div that you want to have an "auto" size of in comparison to its parent element and then set overflow to hidden.
.YourClass && || #YourId{
position:fixed;
top:10px;
bottom:10px;
width:100%; //Do not forget width
overflow-y:auto;
}
Wallah! This is all you need for your special element that you want to have a dynamic height according to screen size and or dynamic incoming content while maintaining the opportunity to scroll.
I had the same problem. This worked better:
Identify which level you want to modify: levels(iris$Species)
"setosa" "versicolor" "virginica"
So, setosa
is the first.
Then, write this:
levels(iris$Species)[1] <-"new name"
You separate the values you want to return by commas:
def get_name():
# you code
return first_name, last_name
The commas indicate it's a tuple, so you could wrap your values by parentheses:
return (first_name, last_name)
Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas
name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
Not to hammer on this or anything but for ES5-compliant browsers why not just:
function isDOM(e) {
return (/HTML(?:.*)Element/).test(Object.prototype.toString.call(e).slice(8, -1));
}
Won't work on TextNodes and not sure about Shadow DOM or DocumentFragments etc. but will work on almost all HTML tag elements.
There are many options to consume a SOAP web service with Stub or Java classes created based on WSDL. But if anyone wants to do this without any Java class created, this article is very helpful. Code Snippet from the article:
public String someMethod() throws MalformedURLException, IOException {
//Code to make a webservice HTTP request
String responseString = "";
String outputString = "";
String wsURL = "<Endpoint of the webservice to be consumed>";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = "entire SOAP Request";
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "<SOAP action of the webservice to be consumed>";
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
//Write the content of the request to the outputstream of the HTTP Connection.
out.write(b);
out.close();
//Ready with sending the request.
//Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
//Write the SOAP message response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.
Document document = parseXmlFile(outputString); // Write a separate method to parse the xml input.
NodeList nodeLst = document.getElementsByTagName("<TagName of the element to be retrieved>");
String elementValue = nodeLst.item(0).getTextContent();
System.out.println(elementValue);
//Write the SOAP message formatted to the console.
String formattedSOAPResponse = formatXML(outputString); // Write a separate method to format the XML input.
System.out.println(formattedSOAPResponse);
return elementValue;
}
For those who're looking for a similar kind of solution with file upload while consuming a SOAP API, please refer to this post: How to attach a file (pdf, jpg, etc) in a SOAP POST request?
The callbacks attached to done()
will be fired when the deferred is resolved. The callbacks attached to fail()
will be fired when the deferred is rejected.
Prior to jQuery 1.8, then()
was just syntactic sugar:
promise.then( doneCallback, failCallback )
// was equivalent to
promise.done( doneCallback ).fail( failCallback )
As of 1.8, then()
is an alias for pipe()
and returns a new promise, see here for more information on pipe()
.
success()
and error()
are only available on the jqXHR
object returned by a call to ajax()
. They are simple aliases for done()
and fail()
respectively:
jqXHR.done === jqXHR.success
jqXHR.fail === jqXHR.error
Also, done()
is not limited to a single callback and will filter out non-functions (though there is a bug with strings in version 1.8 that should be fixed in 1.8.1):
// this will add fn1 to 7 to the deferred's internal callback list
// (true, 56 and "omg" will be ignored)
promise.done( fn1, fn2, true, [ fn3, [ fn4, 56, fn5 ], "omg", fn6 ], fn7 );
Same goes for fail()
.
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
I'm answering this question from the larger question:
When I add $locationProvider.html5Mode(true), my site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?
When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:
For Express Rewrites with AngularJS, you can solve this with the following updates:
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
and
<!-- FOR ANGULAR ROUTING -->
<base href="/">
and
app.use('/',express.static(__dirname + '/public'));
Use the .css()
jQuery manipulators, or better yet just call .show()
/.hide()
on the image once you've obtained a handle to it (e.g. $('#img' + id)
).
BTW, you should not write javascript handlers with the "javascript:" prefix.
In my case, removing the 'encoding="UTF-8"' attribute altogether worked.
It looks like a character set encoding issue, maybe because your file isn't really in UTF-8.
Just adding this answer to help Google save some punter the hours I have spent to get here. I used ILMerge on my .Net 4.0 project, without the /targetplatform option set, assuming it would be detected correctly from my main assembly. I then had complaints from users only on Windows XP aka WinXP. This now makes sense as XP will never have > .Net 4.0 installed whereas most newer OSes will. So if your XP users are having issues, see the fixes above.
Trying to work through Roman Pekar's solution step-by-step to understand it better, I came up with my own solution, which uses melt
to avoid some of the confusing stacking and index resetting. I can't say that it's obviously a clearer solution though:
items_as_cols = df.apply(lambda x: pd.Series(x['samples']), axis=1)
# Keep original df index as a column so it's retained after melt
items_as_cols['orig_index'] = items_as_cols.index
melted_items = pd.melt(items_as_cols, id_vars='orig_index',
var_name='sample_num', value_name='sample')
melted_items.set_index('orig_index', inplace=True)
df.merge(melted_items, left_index=True, right_index=True)
Output (obviously we can drop the original samples column now):
samples subject trial_num sample_num sample
0 [1.84, 1.05, -0.66] 1 1 0 1.84
0 [1.84, 1.05, -0.66] 1 1 1 1.05
0 [1.84, 1.05, -0.66] 1 1 2 -0.66
1 [-0.24, -0.9, 0.65] 1 2 0 -0.24
1 [-0.24, -0.9, 0.65] 1 2 1 -0.90
1 [-0.24, -0.9, 0.65] 1 2 2 0.65
2 [1.15, -0.87, -1.1] 1 3 0 1.15
2 [1.15, -0.87, -1.1] 1 3 1 -0.87
2 [1.15, -0.87, -1.1] 1 3 2 -1.10
3 [-0.8, -0.62, -0.68] 2 1 0 -0.80
3 [-0.8, -0.62, -0.68] 2 1 1 -0.62
3 [-0.8, -0.62, -0.68] 2 1 2 -0.68
4 [0.91, -0.47, 1.43] 2 2 0 0.91
4 [0.91, -0.47, 1.43] 2 2 1 -0.47
4 [0.91, -0.47, 1.43] 2 2 2 1.43
5 [-1.14, -0.24, -0.91] 2 3 0 -1.14
5 [-1.14, -0.24, -0.91] 2 3 1 -0.24
5 [-1.14, -0.24, -0.91] 2 3 2 -0.91
Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.
The thing is: think carefully about what your app must do and can accept. Build something robust.
If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.
As an example of something that will explode if you follow some advices here not carefully.
var getLastChar = function (str) {
if (str.length > 0)
return str.charAt(str.length - 1)
}
getLastChar('hello')
=> "o"
getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'
So, I'd stick with
if (myVar === '')
...
In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,
default_days = 1000 # How long to certify for
defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:
openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.
You will have to pass one of the valid Identity
values like DN
, domain\user
etc to the Set-Mailbox
cmdlet. Currently you are not passing anything.
The way I am doing is using Emacs with docker
package installed. I would recommend Spacemacs version of Emacs. I would follow the following steps:
1) Install Emacs (Instruction) and install Spacemacs (Instruction)
2) Add docker
in your .spacemacs
file
3) Start Emacs
4) Find file (SPC+f+f
) and type /docker:<container-id>:/<path of dir/file in the container>
5) Now your emacs will use the container environment to edit the files
Getting updatedb to work in cron on Cygwin -- debugging steps
1) Make sure cron is installed.
a) Type 'cron' tab tab and look for completion help.
You should see crontab.exe, cron-config, etc. If not install cron using setup.
2) Run cron-config. Be sure to read all the ways to diagnose cron.
3) Run crontab -e
a) Create a test entry of something simple, e.g.,
"* * * * * echo $HOME >> /tmp/mycron.log" and save it.
4) cat /tmp/mycron.log. Does it show cron environment variable HOME
every minute?
5) Is HOME correct? By default mine was /home/myusername; not what I wanted.
So, I added the entry
"HOME='/cygdrive/c/documents and settings/myusername'" to crontab.
6) Once assured the test entry works I moved on to 'updatedb' by
adding an entry in crontab.
7) Since updatedb is a script, errors of sed and find showed up in
my cron.log file. In the error line, the absolute path of sed referenced
an old version of sed.exe and not the one in /usr/bin. I tried changing my
cron PATH environment variable but because it was so long crontab
considered the (otherwise valid) change to be an error. I tried an
explicit much-shorter PATH command, including what I thought were the essential
WINDOWS paths but my cron.log file was empty. Eventually I left PATH alone and
replaced the old sed.exe in the other path with sed.exe from /usr/bin.
After that updatedb ran to completion. To reduce the number of
permission error lines I eventually ended up with this:
"# Run updatedb at 2:10am once per day skipping Sat and Sun'
"10 2 * * 1-5 /usr/bin/updatedb --localpaths='/cygdrive/c' --prunepaths='/cygdrive/c/WINDOWS'"
Notes: I ran cron-config several times throughout this process
to restart the cygwin cron daemon.
We have a similar problem: the click event on a button doesn't work, as long as the user has not scrolled the page. The bug appears only on iOS.
We solved it by scrolling the page a little bit:
$('#modal-window').animate({scrollTop:$("#next-page-button-anchor").offset().top}, 500);
(It doesn't answer the ultimate cause, though. Maybe some kind of bug in Safari mobile ?)
I created a jQuery function in order to make this task a bit easier. Probably now there is a better solution... either way, here's my 2cents. :)
Just add this to your JS file:
$.fn.dialogButtons = function(name, state){
var buttons = $(this).next('div').find('button');
if(!name)return buttons;
return buttons.each(function(){
var text = $(this).text();
if(text==name && state=='disabled') {$(this).attr('disabled',true).addClass('ui-state-disabled');return this;}
if(text==name && state=='enabled') {$(this).attr('disabled',false).removeClass('ui-state-disabled');return this;}
if(text==name){return this;}
if(name=='disabled'){$(this).attr('disabled',true).addClass('ui-state-disabled');return buttons;}
if(name=='enabled'){$(this).attr('disabled',false).removeClass('ui-state-disabled');return buttons;}
});};
Disable button 'Ok' on dialog with class 'dialog':
$('.dialog').dialogButtons('Ok', 'disabled');
Enable all buttons:
$('.dialog').dialogButtons('enabled');
Enable 'Close' button and change color:
$('.dialog').dialogButtons('Close', 'enabled').css('color','red');
Text on all buttons red:
$('.dialog').dialogButtons().css('color','red');
Hope this helps :)
Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
Thanks to this post, my full css for cross browser happiness is:
<style>
.backgroundpic {
background-image: url('img/home.jpg');
background-size: cover;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='img/home.jpg',
sizingMethod='scale');
}
</style>
It's been so long since I've worked on this piece of code, but I'd like to add for more browser compatibility I've appended this to my CSS for more browser compatibility:
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
Sometimes a dependency added with ng add
will add more than one package, typing npm uninstall lib1 lib2
could be error prone and slow, so just remove the not needed libraries from package.json
and run npm i
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec
callback.
Hope this helps! Happy coding :)
I realize this post is old, but there's a more compact approach that is slightly different than what was asked, but may be a very helpful alternative. You can essentially declare the function in-line when calling the method (Foo
's save()
in this case). It would look something like this:
class Foo {
save(callback: (n: number) => any) : void {
callback(42)
}
multipleCallbacks(firstCallback: (s: string) => void, secondCallback: (b: boolean) => boolean): void {
firstCallback("hello world")
let result: boolean = secondCallback(true)
console.log("Resulting boolean: " + result)
}
}
var foo = new Foo()
// Single callback example.
// Just like with @RyanCavanaugh's approach, ensure the parameter(s) and return
// types match the declared types above in the `save()` method definition.
foo.save((newNumber: number) => {
console.log("Some number: " + newNumber)
// This is optional, since "any" is the declared return type.
return newNumber
})
// Multiple callbacks example.
// Each call is on a separate line for clarity.
// Note that `firstCallback()` has a void return type, while the second is boolean.
foo.multipleCallbacks(
(s: string) => {
console.log("Some string: " + s)
},
(b: boolean) => {
console.log("Some boolean: " + b)
let result = b && false
return result
}
)
The multipleCallback()
approach is very useful for things like network calls that may succeed or fail. Again assuming a network call example, when multipleCallbacks()
is called, behavior for both a success and failure can be defined in one spot, which lends itself to greater clarity for future code readers.
Generally, in my experience, this approach lends itself to being more concise, less clutter, and greater clarity overall.
Good luck all!
How about this:
times['days_since'] = max(list(df.index.values))
times['days_since'] = times['days_since'] - times['months']
times
You have a space delimited file, so use the module designed for reading delimited values files, csv
.
import csv
with open('path/to/file.txt') as inf:
reader = csv.reader(inf, delimiter=" ")
second_col = list(zip(*reader))[1]
# In Python2, you can omit the `list(...)` cast
The zip(*iterable)
pattern is useful for converting rows to columns or vice versa. If you're reading a file row-wise...
>>> testdata = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
>>> for line in testdata:
... print(line)
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
...but need columns, you can pass each row to the zip
function
>>> testdata_columns = zip(*testdata)
# this is equivalent to zip([1,2,3], [4,5,6], [7,8,9])
>>> for line in testdata_columns:
... print(line)
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
To access the memory of an object directly (to do a "core dump") you'll need to head into unsafe code.
If you want something more compact than BinaryWriter or a raw memory dump will give you, then you need to write some custom serialisation code that extracts the critical information from the object and packs it in an optimal way.
edit P.S. It's very easy to wrap the BinaryWriter approach into a DeflateStream to compress the data, which will usually roughly halve the size of the data.
Based on mathematical concepts, I understand that:
n
, having 0
as remainder, are all multiples of n
Therefore, the following calculation also applies as a solution (multiples between 1 and 100):
>>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
>>> multiples_5
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
For further reading:
I used grep for something similar:
grep "" *.txt
It does not give you a 'header', but prefixes every line with the filename.
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
I have this same requirement - we want to put logs in a specific root directory that should exist within the environment.
public static readonly string DefaultLogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
If I want to combine this with a sub-directory, I should be able to use Path.Combine( ... )
.
The GetFolderPath
method has an overload for special folder options which allows you to control whether the specified path be created or simply verified.
As some other answers have already pointed out, there are many reasons why celery would silently ignore tasks, including dependency issues but also any syntax or code problem.
One quick way to find them is to run:
./manage.py check
Many times, after fixing the errors that are reported, the tasks are recognized by celery.
Decorate the model property with the DisplayName attribute.
That was a stroll down memory lane...
I replaced awk by perl a long time ago.
Apparently the AWK regular expression engine does not capture its groups.
you might consider using something like :
perl -n -e'/test(\d+)/ && print $1'
the -n flag causes perl to loop over every line like awk does.
tableColumns
null
for all columns as in SELECT * FROM ...
new String[] { "column1", "column2", ... }
for specific columns as in SELECT column1, column2 FROM ...
- you can also put complex expressions here:new String[] { "(SELECT max(column1) FROM table1) AS max" }
would give you a column named max
holding the max value of column1
whereClause
WHERE
without that keyword, e.g. "column1 > 5"
?
for things that are dynamic, e.g. "column1=?"
-> see whereArgs
whereArgs
?
in whereClause
in the order they appearthe others
whereClause
the statement after the keyword or null
if you don't use it.Example
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
is equivalent to the following raw query
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '
.
Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";
because if value contains a '
your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--"
might even drop your table since the statement would become two statements and a comment:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
using the args version XYZ'; DROP TABLE table1;--
would be escaped to 'XYZ''; DROP TABLE table1;--'
and would only be treated as a value. Even if the '
is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int
and other primitives directly into whereClause
though)
Here's a compact version of using applymap
with a straightforward lambda expression to call strip
only when the value is of a string type:
df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
A more complete example:
import pandas as pd
def trim_all_columns(df):
"""
Trim whitespace from ends of each value across all series in dataframe
"""
trim_strings = lambda x: x.strip() if isinstance(x, str) else x
return df.applymap(trim_strings)
# simple example of trimming whitespace from data elements
df = pd.DataFrame([[' a ', 10], [' c ', 5]])
df = trim_all_columns(df)
print(df)
>>>
0 1
0 a 10
1 c 5
Here's a working example hosted by trinket: https://trinket.io/python3/e6ab7fb4ab
use with responsive website (view in mobile or ipad)
jQuery(window).height(); // return height of browser viewport
jQuery(window).width(); // return width of browser viewport
rarely use
jQuery(document).height(); // return height of HTML document
jQuery(document).width(); // return width of HTML document
>>> a=$("#communitymode")[0]
<input id="communitymode" type="checkbox" name="communitymode">
>>> a.type
"checkbox"
Or, more of the style of jQuery:
$("#myinput").attr('type') == 'checkbox'
Since React Native 0.4.3 you can read your local JSON file like this:
const customData = require('./customData.json');
and then access customData like a normal JS object.
you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual
When I tried to create something simillar to inbox floating action button i thought about creating own custom component.
It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.
There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)
I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer
My problem was when converting .p12 certificate to .pem. I used:
openssl pkcs12 -in cert.p12 -out cert.pem
This converts and exports all certificates (CA + CLIENT) together with a private key into one file.
The problem was when I tried to verify if the hashes of certificate and key are matching by running:
// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5
// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5
This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/
I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.
So the solution was to export only CLIENT certificate together with private key:
openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``
Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5
HASHES MATCHED !!!
So I was able to make a curl request by running
curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com
without problems!!!
That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:
curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
Follow these basic steps to fix this problem,
Step 1: Go to Dashboard,
Step 2: Go to "App Review" tab,
Step 3: Enable the "Make test public?" option, Like Below image,
You might be interested in pyp. Citing my other answer:
"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.
First, Hungarian Notation is the practice of using a prefix to display a parameter's data type or intended use. Microsoft's naming conventions for says no to Hungarian Notation http://en.wikipedia.org/wiki/Hungarian_notation http://msdn.microsoft.com/en-us/library/ms229045.aspx
Using UPPERCASE is not encouraged as stated here: Pascal Case is the acceptable convention and SCREAMING CAPS. http://en.wikibooks.org/wiki/C_Sharp_Programming/Naming
Microsoft also states here that UPPERCASE can be used if it is done to match the the existed scheme. http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx
This pretty much sums it up.
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
The 'git branch -d' subcommand can delete more than one branch. So, simplifying @sblom's answer but adding a critical xargs:
git branch -D `git branch --merged | grep -v \* | xargs`
or, further simplified to:
git branch --merged | grep -v \* | xargs git branch -D
Importantly, as noted by @AndrewC, using git branch
for scripting is discouraged. To avoid it use something like:
git for-each-ref --format '%(refname:short)' refs/heads | grep -v master | xargs git branch -D
Caution warranted on deletes!
$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
Story-123-a
Story-123-b
Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).
We can import single table using CMD as below:
D:\wamp\bin\mysql\mysql5.5.24\bin>mysql -h hostname -u username -p passowrd databasename < filepath
I know my answer it's too late, but it might helpful to other's
Try,
Void Main()
{
string filename = @"test.txt";
string filePath= AppDomain.CurrentDomain.BaseDirectory + filename ;
Console.WriteLine(filePath);
}
Have you tried the classic, waiting for the load to complete using jQuery's builtin ready function?
$(document).ready(function() {
$('some selector', frames['nameOfMyIframe'].document).doStuff()
} );
K
Necromancing here.
Obviously, x *= -1;
is far too simple.
Instead, we could use a trivial binary complement:
number = ~(number - 1) ;
Like this:
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int iPositive = 15;
int iNegative = ( ~(iPositive - 1) ) ; // Use extra brackets when using as C preprocessor directive ! ! !...
System.out.println(iNegative);
iPositive = ~(iNegative - 1) ;
System.out.println(iPositive);
iNegative = 0;
iPositive = ~(iNegative - 1);
System.out.println(iPositive);
}
}
That way we can ensure that mediocre programmers don't understand what's going on ;)
Check the trees.config file which located in config folder... sometimes (I don't know why) this file became to be empty like someone delete the content inside... keep backup up of this file in your local pc then when this error appear - replace the server file with your local file. This is what i do when this error happened.
check the available space on the server. sometimes this is the problem.
Good luck.
System.Diagnostics.Process.GetCurrentProcess()
gets the currently running process. You can use the ProcessName
property to figure out the name. Below is a sample console app.
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Process.GetCurrentProcess().ProcessName);
Console.ReadLine();
}
}
Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,
Other notes,
Use Int32.TryParse
as follows.
int test;
bool result = Int32.TryParse(value, out test);
if (result)
{
Console.WriteLine("Sucess");
}
else
{
if (value == null) value = "";
Console.WriteLine("Failure");
}
Let's say N = 5 and your model is Message
, you can do something like this:
Message.order(id: :asc).from(Message.all.order(id: :desc).limit(5), :messages)
Look at the sql:
SELECT "messages".* FROM (
SELECT "messages".* FROM "messages" ORDER BY "messages"."created_at" DESC LIMIT 5
) messages ORDER BY "messages"."created_at" ASC
The key is the subselect. First we need to define what are the last messages we want and then we have to order them in ascending order.
If you use the JQuery library you can use the .hover() event which merges the mouseover and mouseout event and helps you with the timing and child elements:
$(this).hover(function(){},function(){});
The first function is the start of the hover and the next is the end. Read more at: http://docs.jquery.com/Events/hover
In my case i was returning string value from my api eg: "35" and in my HTML i was using
<mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
<mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
{{ state.stateName }}
</mat-option>
</mat-select>
Like others mentioned in the comment value will only accept integer values i guess. So what I did is I converted my string value to integer in my component class like below
var x = user.state;
var y: number = +x;
and then assigned it like
this.EditProfileForm.get('states').setValue(y);
Now the correct values is getting setting by default.
I found this question by searching Google for "mysql workbench export database sql file". The answers here did not help me, but I eventually did find the answer, so I am posting it here for future generations to find:
Answer
In MySQLWorkbench 6.0, do the following:
Here is a screenshot for reference:
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
Or something like this:
private static String myRemComa(String input) {
String[] exploded = input.split(",");
input="";
boolean start = true;
for(String str : exploded) {
str=str.trim();
if (str.length()>0) {
if (start) {
input = str;
start = false;
} else {
input = input + "," + str;
}
}
}
return input;
}
This steps are used in spring boot with self signed ssl certificate implementation
if SSL turns off then HTTPS call will be worked as expected.
https://localhost:8443/test/hello
These are the steps we have to follow,
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650
after key generation has done then copy that file in to the resource foder in your project
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
now verify the url: https://localhost:8443/test/hello
strtok()
is a bad ideaDo not use strtok()
in normal code, strtok()
uses static
variables which have some problems. There are some use cases on embedded microcontrollers where static
variables make sense but avoid them in most other cases. strtok()
behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok()
.
Consider this example:
#include <stdio.h>
#include <string.h>
//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
char *p = strtok(input, "/");
while(p)
{
printf("%s, ",p);
p = strtok(NULL, "/");
}
}
int main(void)
{
char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
char *p = strtok(buffer, ":");
while(p)
{
printContent(p);
puts(""); //print newline
p = strtok(NULL, ":");
}
return 0;
}
You may expect the output:
abc, def, ghi,
ABC, DEF, GHI,
But you will get
abc, def, ghi,
This is because you call strtok()
in printContent()
resting the internal state of strtok()
generated in main()
. After returning, the content of strtok()
is empty and the next call to strtok()
returns NULL
.
You could use strtok_r()
when you use a POSIX system, this versions does not need static
variables. If your library does not provide strtok_r()
you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.
Using $emit and $broadcast, (as mentioned by walv in the comments above)
To fire an event upwards (from child to parent)
$scope.$emit('myTestEvent', 'Data to send');
To fire an event downwards (from parent to child)
$scope.$broadcast('myTestEvent', {
someProp: 'Sending you some data'
});
and finally to listen
$scope.$on('myTestEvent', function (event, data) {
console.log(data);
});
For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
Enjoy :)
This should be placed in the method that calls the ViewController titled "NewTitle". Right before the push or popViewController statement.
UIBarButtonItem *newBackButton =
[[UIBarButtonItem alloc] initWithTitle:@"NewTitle"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
[[self navigationItem] setBackBarButtonItem:newBackButton];
[newBackButton release];
The app is stored in %LocalAppData%
in your %UserProfile%
. So the full path could be:
C:\Users\username\AppData\Local\GitHub
I recommend:
And of course, alphabetical order within each section, where possible.
Always use forward declarations to avoid unnecessary #include
s in your header files.
Lets assume df
is a pandas DataFrame.
Then,
df.isnull().sum(axis = 0)
This will give number of NaN values in every column.
If you need, NaN values in every row,
df.isnull().sum(axis = 1)
I had difficulty with the answers above, potentially because I set the checkStyle warnings to be errors. What did work was SuppressionFilter: http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter
The drawback of this is that the line range is stored in a separate suppresssions.xml file, so an unfamiliar developer may not immediately make the connection.
For a field named isCurrent
, the correct getter / setter naming is setCurrent()
/ isCurrent()
(at least that's what Eclipse thinks), which is highly confusing and can be traced back to the main problem:
Your field should not be called isCurrent
in the first place. Is is a verb and verbs are inappropriate to represent an Object's state. Use an adjective instead, and suddenly your getter / setter names will make more sense:
private boolean current;
public boolean isCurrent(){
return current;
}
public void setCurrent(final boolean current){
this.current = current;
}
ng g c folderName/SubFolder/.../componentName --spec=false
Seems to work for me:
String s = " a b c";
System.out.println("\"" + s.replaceAll("\\s\\s", " ") + "\"");
will print:
" a b c"
I think you intended to do this instead of your code:
Pattern whitespace = Pattern.compile("\\s\\s");
Matcher matcher = whitespace.matcher(s);
String result = "";
if (matcher.find()) {
result = matcher.replaceAll(" ");
}
System.out.println(result);
You could subscribe for the .click event for the links and change the contents of the div using the .html
method:
$('.click').click(function() {
// get the contents of the link that was clicked
var linkText = $(this).text();
// replace the contents of the div with the link text
$('#content-container').html(linkText);
// cancel the default action of the link by returning false
return false;
});
Note however that if you replace the contents of this div the click handler that you have assigned will be destroyed. If you intend to inject some new DOM elements inside the div for which you need to attach event handlers, this attachments should be performed inside the .click handler after inserting the new contents. If the original selector of the event is preserved you may also take a look at the .delegate
method to attach the handler.
You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.
HttpStatusCode GetHttpStatusCode(WebException we)
{
if (we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
return response.StatusCode;
}
return null;
}
Just use https://graph.facebook.com/(your_username or page name) to get your page ID and after you can see all the detain and your ID
after in your IOS app use :
NSURL *url = [NSURL URLWithString:@"fb://profile/[your ID]"];
[[UIApplication sharedApplication] openURL:url];
In case you were struggling to change linetypes
, the following answer should be helpful. (This is an addition to the solution by Andy W.)
We will try to extend the learned pattern:
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) + #red
geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) + #blue
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_linetype_manual(values=line_types)+
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
However, what we get is the following result:
The problem is that the linetype
is not merged in the main legend.
Note that we did not give any name to the method scale_linetype_manual
.
The trick which works here is to give it the same name as what you used for naming scale_colour_manual
.
More specifically, if we change the corresponding line to the following we get the desired result:
scale_linetype_manual(name="Error Bars",values=line_types)
Now, it is easy to change the size of the line with the same idea.
Note that the geom_bar
has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar
with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
If you want numbers from 1 up to 100:
100|[1-9]\d?
You don't need to install sqlite3
module. It is included in the standard library (since Python 2.5).
Another approach would be to leverage the INSERT ALL
syntax from oracle,
INSERT ALL
INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
(SELECT '[email protected]' email,100 campaign_id
FROM dual
UNION ALL
SELECT '[email protected]' email,200 campaign_id
FROM dual)
SELECT email
,campaign_id
FROM source_data src
WHERE NOT EXISTS (SELECT 1
FROM table1 dest
WHERE src.email = dest.email
AND src.campaign_id = dest.campaign_id);
INSERT ALL
also allow us to perform a conditional insert into multiple tables based on a sub query as source.
There are some really clean and nice examples are there to refer.
If you want to include both - accept on enter and accept on click then do -
<div class="form-group">
<input class="form-control" type="text"
name="search" placeholder="Enter Search Text"
[(ngModel)]="filterdata"
(keyup.enter)="searchByText(filterdata)">
<button type="submit"
(click)="searchByText(filterdata)" >
</div>
No need to get too complicated. If all you need is ² then use the unicode representation.
http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts
(which is how I assume you got the ² to appear in your question. )
As per June 2020, I suppose this version (pip install -U opencv-contrib-python==3.4.2.16
) is still working. so install it and enjoy.
if A:
will prove false if A is 0, False, empty string, empty list or None, which can lead to undesired results.