If adapter
is set to AutoCompleteTextView
then notifyDataSetChanged()
doesn't work.
Need this to update adapter:
myAutoCompleteAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line, myList);
myAutoComplete.setAdapter(myAutoCompleteAdapter);
Refer: http://android-er.blogspot.in/2012/10/autocompletetextview-with-dynamic.html
I found a more complete listing at user agent string. BTW, this site has more than just iOS user agent strings. Also, the home page will "break down" the user agent string of your current browser for you.
Did you just try
$('#datebox li a').on('click', function(){
//$('#datebox').val($(this).text());
alert($(this).text());
});
It works for me :)
In HTML codes:
<form action="POST" onsubmit="ajax_submit();return false;">
<b>First Name:</b> <input type="text" name="firstname" id="firstname">
<br>
<b>Last Name:</b> <input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="send" onclick="ajax_submit();">
</form>
In Js codes:
function ajax_submit()
{
$.ajax({
url: "submit.php",
type: "POST",
data: {
firstname: $("#firstname").val(),
lastname: $("#lastname").val()
},
dataType: "JSON",
success: function (jsonStr) {
// another codes when result is success
}
});
}
@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
return "Response!";
}
@ResponseBody
?It's telling that the method returns some text and not to interpret it as a view etc.
produces="text/plain"
?It's just a good practice as it tells what will be returned from the method :)
Add a Button
and on click of the Button
add this code:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
Useful links:
You can use UNION ALL instead.
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.MainTable AS mt
Union ALL
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.OtherTable AS ot
use the following inside the body tag
<body onclick="theFunction(event)">
then use in javascript the following function to get the ID
<script>
function theFunction(e)
{ alert(e.target.id);}
You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.
Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.
You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.
You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.
Because you can't print a character with string formating. You can also think of adding a format with something like this
#define PRINTC(c,f,s) printf ("\033[%dm" f "\033[0m", 30 + c, s)
f
is format as in printf
PRINTC (4, "%s\n", "bar")
will print blue bar
PRINTC (1, "%d", 'a')
will print red 97
Your json string is wrapped within square brackets ([]
), hence it is interpreted as array instead of single RetrieveMultipleResponse
object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse
, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
1. In the loop you are assigning value rather than comparing value so
i=((Main.size())-1) -> i=(-1) since Main.size()
Main[i] will yield "Vector Subscript out of Range" coz i = -1.
2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked")
to get all checkboxes and radio buttons that are checked.
Use the traceback module:
import sys
import traceback
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
print('An error occurred on line {} in statement {}'.format(line, text))
exit(1)
You can get the default Template
, modify it by overlaying a TextBlock
, and use a Style
to add triggers that hide and show it in the right states.
public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private static final String LOGSERVICE = "#######";
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
Log.i(LOGSERVICE, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOGSERVICE, "onStartCommand");
if (!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
return START_STICKY;
}
@Override
public void onConnected(Bundle bundle) {
Log.i(LOGSERVICE, "onConnected" + bundle);
Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (l != null) {
Log.i(LOGSERVICE, "lat " + l.getLatitude());
Log.i(LOGSERVICE, "lng " + l.getLongitude());
}
startLocationUpdate();
}
@Override
public void onConnectionSuspended(int i) {
Log.i(LOGSERVICE, "onConnectionSuspended " + i);
}
@Override
public void onLocationChanged(Location location) {
Log.i(LOGSERVICE, "lat " + location.getLatitude());
Log.i(LOGSERVICE, "lng " + location.getLongitude());
LatLng mLocation = (new LatLng(location.getLatitude(), location.getLongitude()));
EventBus.getDefault().post(mLocation);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOGSERVICE, "onDestroy - Estou sendo destruido ");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(LOGSERVICE, "onConnectionFailed ");
}
private void initLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(2000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void startLocationUpdate() {
initLocationRequest();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
private void stopLocationUpdate() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
}
This is the simplest answer:
<?php
$img = get_the_post_thumbnail_url($postID, 'post-thumbnail');
?>
To start server locally paste the below code in package.json and run npm start in command line.
"scripts": {
"start": "http-server -c-1 -p 8081"
},
I'm aware this is not a fast solution. Posting as hopefully easier to understand slow solution.
public static long largestPrimeFactor(long n) {
// largest composite factor must be smaller than sqrt
long sqrt = (long)Math.ceil(Math.sqrt((double)n));
long largest = -1;
for(long i = 2; i <= sqrt; i++) {
if(n % i == 0) {
long test = largestPrimeFactor(n/i);
if(test > largest) {
largest = test;
}
}
}
if(largest != -1) {
return largest;
}
// number is prime
return n;
}
Many designs start by using Factory Method (less complicated and more customizable via subclasses) and evolve toward Abstract Factory, Prototype, or Builder (more ?exible, but more complicated).
Builder focuses on constructing complex objects step by step.
Implementing it:
Abstract Factory specializes in creating families of related objects. Abstract Factory returns the product immediately, whereas Builder lets you run some additional construction steps before fetching the product.
You can use Abstract Factory along with Bridge. This pairing is useful when some abstractions defined by Bridge can only work with specific implementations. In this case, Abstract Factory can encapsulate these relations and hide the complexity from the client code.
Use datetime.replace
:
from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)
awk -F '\t' '{ a[$1]++ } END { for (n in a) print n, a[n] } ' test.csv
Replace
Into seems like an option. Or you can check with
IF NOT EXISTS(QUERY) Then INSERT
This will insert or delete then insert. I tend to go for a IF NOT EXISTS
check first.
There are many methods to convert an array to comma separated list
From MDN
The join() method joins all elements of an array (or an array-like object) into a string.
The code
var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.join(",");_x000D_
console.log(arr);
_x000D_
From MDN
The toString() method returns a string representing the specified array and its elements.
The code
var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.toString();_x000D_
console.log(arr);
_x000D_
The []+ or +[] will convert it into a string
([]+[] === [].toString())
will output true
console.log([]+[] === [].toString());
_x000D_
var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = []+arr;_x000D_
console.log(arr);
_x000D_
var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr + [];_x000D_
console.log(arr);
_x000D_
If certain position of the string is needed, this code comes to place in Swift 3.0:
let string = "This is my string"
let substring = "my"
let position = string.range(of: substring)?.lowerBound
You can also use SimpleDateFormat, as in DateTimeFormat
Date startDate = null;
Date endDate = null;
try {
if (validDateStart!= null) startDate = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH).parse(validDateStart + " " + validDateStartTime);
if (validDateEnd!= null) endDate = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH).parse(validDateEnd + " " + validDateEndTime);
} catch (ParseException e) {
e.printStackTrace();
}
your elemId
as its name suggests, is an Id
attribute, these are all you can do to check if it exists:
Vanilla JavaScript: in case you have more advanced selectors:
//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}
To check the accurate usage for your services be it is free (as per always free or 12 months free) or Pay-As-You-Go, it is important to monitor the usage so that you know upfront on the cost incurred or when to upgrade your service tier.
To check your free service usage and its limits, Go to search in Portal, search with "Subscription" and click on it. you will see the details of each service that you have used.
In case of free azure from Microsoft, you get to see the cost incurred for each one.
Visit Check usage of free services included with your Azure free account
Hope this helps someone!
First customize your search dialog. Ctrl+H. Click on the Customize button and select inly File Search while deselecting all the others. Close the dialog.
Now you can search by selecting the word and hitting the Ctrl+H and then Enter.
You can also use a combination of cat
and paste0
cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))
I find this to be more useful when incorporating variables into the printout. For example:
file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))
You can also modify your theme using theme Editor by clicking :
Tools -> Android -> Theme Editor
Then, you don't even need to put some extra content in your .xml or .class files.
I used the below method to migrate my GIT Stash to GitLab by maintaining all branches and commit history.
Clone the old repository to local.
git clone --bare <STASH-URL>
Create an empty repository in GitLab.
git push --mirror <GitLab-URL>
Use the tee
command:
echo "hello" | tee logfile.txt
kennytm quoted man bash
, but most of that is also POSIX 7: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_04 :
The redirection operators "<<" and "<<-" both allow redirection of lines contained in a shell input file, known as a "here-document", to the input of a command.
The here-document shall be treated as a single word that begins after the next and continues until there is a line containing only the delimiter and a , with no characters in between. Then the next here-document starts, if there is one. The format is as follows:
[n]<<word here-document delimiter
where the optional n represents the file descriptor number. If the number is omitted, the here-document refers to standard input (file descriptor 0).
If any character in word is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.
If no characters in word are quoted, all lines of the here-document shall be expanded for parameter expansion, command substitution, and arithmetic expansion. In this case, the in the input behaves as the inside double-quotes (see Double-Quotes). However, the double-quote character ( '"' ) shall not be treated specially within a here-document, except when the double-quote appears within "$()", "``", or "${}".
If the redirection symbol is "<<-", all leading
<tab>
characters shall be stripped from input lines and the line containing the trailing delimiter. If more than one "<<" or "<<-" operator is specified on a line, the here-document associated with the first operator shall be supplied first by the application and shall be read first by the shell.When a here-document is read from a terminal device and the shell is interactive, it shall write the contents of the variable PS2, processed as described in Shell Variables, to standard error before reading each line of input until the delimiter has been recognized.
Some examples not yet given.
Without quotes:
a=0
cat <<EOF
$a
EOF
Output:
0
With quotes:
a=0
cat <<'EOF'
$a
EOF
or (ugly but valid):
a=0
cat <<E"O"F
$a
EOF
Outputs:
$a
Without hyphen:
cat <<EOF
<tab>a
EOF
where <tab>
is a literal tab, and can be inserted with Ctrl + V <tab>
Output:
<tab>a
With hyphen:
cat <<-EOF
<tab>a
<tab>EOF
Output:
a
This exists of course so that you can indent your cat
like the surrounding code, which is easier to read and maintain. E.g.:
if true; then
cat <<-EOF
a
EOF
fi
Unfortunately, this does not work for space characters: POSIX favored tab
indentation here. Yikes.
Following method is deprecated
sslSocketFactory(SSLSocketFactory sslSocketFactory)
Consider updating it to
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
i use these three lines of code to print out the column names which contain at least one null value:
for column in dataframe:
if dataframe[column].isnull().any():
print('{0} has {1} null values'.format(column, dataframe[column].isnull().sum()))
I had a similar error with a different artifact.
<...> was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
None of the above described solutions worked for me. I finally resolved this in IntelliJ IDEA by File > Invalidate Caches / Restart ... > Invalidate and Restart.
I really recommend you read about Information Theory, bayesian methods and MaxEnt. The place to start is this (freely available online) book by David Mackay:
http://www.inference.phy.cam.ac.uk/mackay/itila/
Those inference methods are really far more general than just text mining and I can't really devise how one would learn how to apply this to NLP without learning some of the general basics contained in this book or other introductory books on Machine Learning and MaxEnt bayesian methods.
The connection between entropy and probability theory to information processing and storing is really, really deep. To give a taste of it, there's a theorem due to Shannon that states that the maximum amount of information you can pass without error through a noisy communication channel is equal to the entropy of the noise process. There's also a theorem that connects how much you can compress a piece of data to occupy the minimum possible memory in your computer to the entropy of the process that generated the data.
I don't think it's really necessary that you go learning about all those theorems on communication theory, but it's not possible to learn this without learning the basics about what is entropy, how it's calculated, what is it's relationship with information and inference, etc...
We also had to develop a solution which would even work with APIs requiring authentication (see this article)
Using AngularJS in a nutshell here is how we did it:
Step 1: Create a dedicated directive
// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
restrict: 'E',
templateUrl: '/path/to/pdfDownload.tpl.html',
scope: true,
link: function(scope, element, attr) {
var anchor = element.children()[0];
// When the download starts, disable the link
scope.$on('download-start', function() {
$(anchor).attr('disabled', 'disabled');
});
// When the download finishes, attach the data to the link. Enable the link and change its appearance.
scope.$on('downloaded', function(event, data) {
$(anchor).attr({
href: 'data:application/pdf;base64,' + data,
download: attr.filename
})
.removeAttr('disabled')
.text('Save')
.removeClass('btn-primary')
.addClass('btn-success');
// Also overwrite the download pdf function to do nothing.
scope.downloadPdf = function() {
};
});
},
controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
$scope.downloadPdf = function() {
$scope.$emit('download-start');
$http.get($attrs.url).then(function(response) {
$scope.$emit('downloaded', response.data);
});
};
}]
});
Step 2: Create a template
<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>
Step 3: Use it
<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>
This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.
Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.
In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None
and usecols=[3,6]
for the 4th and 7th columns:
df = pd.read_csv(file_path, header=None, usecols=[3,6])
See the docs
Usually this is due to python version set on your Environment Variables. Check PATH (or Path) for both System and Client variables.
If its pointing to "path/to/python-installation/Python3.x-32", change it to "path/to/python-installation/Python3.x"
Again check value on both System and Client Environment Variables
re> |(?<=\w)/.+(?=\.\w+$)| Compile time 0.0011 milliseconds Memory allocation (code space): 32 Study time 0.0002 milliseconds Capturing subpattern count = 0 No options First char = '/' No need char Max lookbehind = 1 Subject length lower bound = 2 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0007 milliseconds 0: /manual/en/function.preg-match
re> |//[^/]*(.*)\.\w+$| Compile time 0.0010 milliseconds Memory allocation (code space): 28 Study time 0.0002 milliseconds Capturing subpattern count = 1 No options First char = '/' Need char = '.' Subject length lower bound = 4 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0005 milliseconds 0: //php.net/manual/en/function.preg-match.php 1: /manual/en/function.preg-match
re> |/[^/]+(.*)\.| Compile time 0.0008 milliseconds Memory allocation (code space): 23 Study time 0.0002 milliseconds Capturing subpattern count = 1 No options First char = '/' Need char = '.' Subject length lower bound = 3 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0005 milliseconds 0: /php.net/manual/en/function.preg-match. 1: /manual/en/function.preg-match
re> |/[^/]+\K.*(?=\.)| Compile time 0.0009 milliseconds Memory allocation (code space): 22 Study time 0.0002 milliseconds Capturing subpattern count = 0 No options First char = '/' No need char Subject length lower bound = 2 No set of starting bytes data> http://php.net/manual/en/function.preg-match.php Execute time 0.0005 milliseconds 0: /manual/en/function.preg-match
re> |\w+\K/.*(?=\.)| Compile time 0.0009 milliseconds Memory allocation (code space): 22 Study time 0.0003 milliseconds Capturing subpattern count = 0 No options No first char Need char = '/' Subject length lower bound = 2 Starting byte set: 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ a b c d e f g h i j k l m n o p q r s t u v w x y z data> http://php.net/manual/en/function.preg-match.php Execute time 0.0011 milliseconds 0: /manual/en/function.preg-match
For me the issue was the IP address that charles was telling me to route to in my proxy settings was incorrect. To solve I ended up going to ifconfig
in the terminal and the trying the different IP addresses (listed next to inet
) at port 8888
for the current active connections
I made a dynamic proc which turns any random query into an HTML table, so you don't have to hardcode columns like in the other responses.
-- Description: Turns a query into a formatted HTML table. Useful for emails.
-- Any ORDER BY clause needs to be passed in the separate ORDER BY parameter.
-- =============================================
CREATE PROC [dbo].[spQueryToHtmlTable]
(
@query nvarchar(MAX), --A query to turn into HTML format. It should not include an ORDER BY clause.
@orderBy nvarchar(MAX) = NULL, --An optional ORDER BY clause. It should contain the words 'ORDER BY'.
@html nvarchar(MAX) = NULL OUTPUT --The HTML output of the procedure.
)
AS
BEGIN
SET NOCOUNT ON;
IF @orderBy IS NULL BEGIN
SET @orderBy = ''
END
SET @orderBy = REPLACE(@orderBy, '''', '''''');
DECLARE @realQuery nvarchar(MAX) = '
DECLARE @headerRow nvarchar(MAX);
DECLARE @cols nvarchar(MAX);
SELECT * INTO #dynSql FROM (' + @query + ') sub;
SELECT @cols = COALESCE(@cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET @cols = ''SET @html = CAST(( SELECT '' + @cols + '' FROM #dynSql ' + @orderBy + ' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''
EXEC sys.sp_executesql @cols, N''@html nvarchar(MAX) OUTPUT'', @html=@html OUTPUT
SELECT @headerRow = COALESCE(@headerRow + '''', '''') + ''<th>'' + name + ''</th>''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET @headerRow = ''<tr>'' + @headerRow + ''</tr>'';
SET @html = ''<table border="1">'' + @headerRow + @html + ''</table>'';
';
EXEC sys.sp_executesql @realQuery, N'@html nvarchar(MAX) OUTPUT', @html=@html OUTPUT
END
GO
Usage:
DECLARE @html nvarchar(MAX);
EXEC spQueryToHtmlTable @html = @html OUTPUT, @query = N'SELECT * FROM dbo.People', @orderBy = N'ORDER BY FirstName';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Foo',
@recipients = '[email protected];',
@subject = 'HTML email',
@body = @html,
@body_format = 'HTML',
@query_no_truncate = 1,
@attach_query_result_as_file = 0;
Related: Here is similar code to turn any arbitrary query into a CSV string.
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
Documentation: Convert JSON to a Type
DOMContentLoaded
==window.onDomReady()
Load
==window.onLoad()
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside
$(document).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside$(window).load(function() { ... })
will run once the entire page (images or iframes), not just the DOM, is ready.
with open(fname) as f:
next(f)
for line in f:
#do something
Well, I got it. One way is to override the QWidget::closeEvent
(QCloseEvent *event)
method in your class definition and add your code into that function. Example:
class foo : public QMainWindow
{
Q_OBJECT
private:
void closeEvent(QCloseEvent *bar);
// ...
};
void foo::closeEvent(QCloseEvent *bar)
{
// Do something
bar->accept();
}
Have modified @user919216 code .. and made it compatible with WebView
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
WITH uniq AS (
SELECT DISTINCT posts.id as post_id
FROM posts
JOIN votes ON votes.post_id = posts.id
-- GROUP BY not needed anymore
-- GROUP BY posts.id
)
SELECT COUNT(*)
FROM uniq;
printf(...)
is equivalent to fprintf(stdout,...)
.
fprintf
is used to output to stream.
sprintf(buffer,...)
is used to format a string to a buffer.
Note there is also vsprintf
, vfprintf
and vprintf
arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.
notify is optional, depends on conditions.
You can do like
HTML in PHP :
<?php
echo "<table>";
echo "<tr>";
echo "<td>Name</td>";
echo "<td>".$name."</td>";
echo "</tr>";
echo "</table>";
?>
Or You can write like.
PHP in HTML :
<?php /*Do some PHP calculation or something*/ ?>
<table>
<tr>
<td>Name</td>
<td><?php echo $name;?></td>
</tr>
</table>
<?php /*Do some PHP calculation or something*/ ?>
Means:
You can open a PHP tag with <?php
, now add your PHP code, then close the tag with ?>
and then write your html code. When needed to add more PHP, just open another PHP tag with <?php
.
In Java you would do something similar to:
Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.
What worked for me was to create a new report from scratch.
This done and the new report working, I will compare the 2 .rdl files in Visual Studio. These are in XML format and I am hoping a quick WindDiff or something would reveal what the issue was.
An initial look shows there are 700 lines of code or a bit more difference between both files, with the larger of the 2 being the faulty file. A cursory look at the TablixHeader tags didn't reveal anything obvious.
But in my case it was a corrupted .rdl file. This was originally copied from a working report so in the process of removing what wasn't re-used, this could have corrupted it. However, other reports where this same process was done, the headers could repeat when the correct settings were made in Properties.
Hope this helps. If you've got a complex report, this isn't the quick fix but it works.
Perhaps comparing known good XML files to faulty ones on your end would make a good forum post. I'll be trying that on my end.
go to Start->Run
type inetmgr and press OK. If you get an IIS
configuration screen. It is installed, otherwise it isn't.
You can also check ControlPanel->Add Remove Programs
, Click Add Remove Windows Components
and look for IIS in the list of installed components.
EDIT
To Reinstall IIS.
Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Uncheck IIS box
Click next and follow prompts to UnInstall IIS
.
Insert your windows disc into the appropriate drive.
Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Check IIS box
Click next and follow prompts to Install IIS
.
just to add a detail to what Tamlyn wrote,
instead of
$('form').get(0).setAttribute('action', 'baz'); //this works
$('form')[0].setAttribute('action', 'baz');
works equally well
You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.
Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly')
in expression field and a good constraint name in (Name) field.
You are done.
find . -depth -name '* *' \
| while IFS= read -r f ; do mv -i "$f" "$(dirname "$f")/$(basename "$f"|tr ' ' _)" ; done
failed to get it right at first, because I didn't think of directories.
If you are in a domain environment, you can also use:
winrs -r:PCNAME cmd
This will open a remote command shell.
I am sure I am late to the party but below worked for me.
<paths>
<root-path name="root" path="." />
</paths>
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
$('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
$('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>
I found the source cause!
In my case, I add a jar file include some java source file, but I think the java source is bad, in Intellij Idea dependency library it add the source automatic, so in Editor the import is BAD, JUST remove the source code in "Project Structure" -> "Library", it works for me.
not sure if it'll work in your scenario, but try adding the following to your web.config
under <system.web>
:
<system.web>
<customErrors mode="Off" />
...
</system.web>
works in my instance.
also see:
Meanwhile, all the values above will only restrict the values to integer, so i use
/^[1-9][0-9\.]{0,15}$/
to allow float values too.
$(function () {
//declare function
$.fn.myfunction = function () {
return true;
};
});
$(document).ready(function () {
//call function
$("#my_div").myfunction();
});
You have add this code:
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
And Enabling Allow less secure apps: "will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"
This work for me!
Run eventvwr from the command line to see if it has recorded any Application errors.
This might give you an actual error message that is more useful.
First override equals()
method:
@Override
public boolean equals(Object obj)
{
if(obj == null) return false;
else if(obj instanceof MyObject && getTitle() == obj.getTitle() && getAuthor() == obj.getAuthor() && getURL() == obj.getURL() && getDescription() == obj.getDescription()) return true;
else return false;
}
and then use:
List<MyObject> list = new ArrayList<MyObject>;
for(MyObject obj1 : list)
{
for(MyObject obj2 : list)
{
if(obj1.equals(obj2)) list.remove(obj1); // or list.remove(obj2);
}
}
UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;
In Xcode 4.x press
(or click Menubar
> Product
> Scheme
> Edit Scheme
)
select the "Diagnostics" tab and click "Enable Zombie Objects":
This turns released objects into NSZombie instances that print console warnings when used again. This is a debugging aid that increases memory use (no object is really released) but improves error reporting.
A typical case is when you over-release an object and you don't know which one:
-[UITableView release]: message sent to deallocated instance
This Xcode setting is ignored when you archive the application for App Store submission. You don't need to touch anything before releasing your application.
Pressing ??R is the same as selecting Product > Run while keeping the Alt key pressed.
Clicking the "Enable Zombie Objects" checkbox is the same as manually adding "NSZombieEnabled = YES" in the section "Environment Variables" of the tab Arguments.
Try wrapping the image with a linearlayout, and set it's background to the border color you want around the text. Then set the padding on the textview to be the thickness you want for your border.
Actually the XSD is XML itself. Its purpose is to validate the structure of another XML document. The XSD is not mandatory for any XML, but it assures that the XML could be used for some particular purposes. The XML is only containing data in suitable format and structure.
You can use the Invoke-Sqlcmd
cmdlet
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputer\MyInstance"
you can use pass inside if statement.
If you want to pass just the index.php ( no other php file will be passed to fastcgi ) to fastcgi in case you have routes like this in a framework like codeigniter
$route["/download.php"] = "controller/method";
location ~ index\.php$ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi.conf;
}
Try with array_merge_recursive
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
$c = array_merge_recursive($A,$B);
echo "<pre>";
print_r($c);
echo "</pre>";
will return
Array
(
[a] => 1
[b] => 2
[c] => Array
(
[0] => 3
[1] => 4
)
[d] => 5
)
Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.
C# and the .net CLR have not implemented MI because they have not concluded how it would inter-operate between C#, VB.net and the other languages yet, not because "it would make source more complex"
MI is a useful concept, the un-answered questions are ones like:- "What do you do when you have multiple common base classes in the different superclasses?
Perl is the only language I've ever worked with where MI works and works well. .Net may well introduce it one day but not yet, the CLR does already support MI but as I've said, there are no language constructs for it beyond that yet.
Until then you are stuck with Proxy objects and multiple Interfaces instead :(
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
Login using the system maintenance user and password created when you installed phpMyAdmin.
It can be found in the debian.cnf file at /etc/mysql then you will have total access.
cd /etc/mysql
sudo nano debian.cnf
Just look - don't change anything!
[mysql_upgrade]
host = localhost
user = debian-sys-maint <----use this user
password = s0meRaND0mChar$s <----use this password
socket = /var/run/mysqld/mysqld.sock
Worked for me.
just indent your code correctly:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
return 0
else:
return period
You need to understand that the break
statement in your example will exit the infinite loop you've created with while True
. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break
statement by a return
statement.
Following your idea to use an infinite loop, this is the best way to write it:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
period = 0
break
return period
Seems like you've already got your answer but I figured I'd chime in. This is what I do in some scripts on an Ubuntu (or debian server)
#!/usr/bin/perl
use warnings;
use strict;
#I've gotten into the habit of setting this on all my scripts, prevents weird path issues if the script is not being run by root
$ENV{'PATH'} = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
#Fill this with the perl modules required for your project
my @perl = qw(LWP::Simple XML::LibXML MIME::Lite DBI DateTime Config::Tiny Proc::ProcessTable);
chomp(my $curl = `which curl`);
if(!$curl){ system('apt-get install curl -y > /dev/null'); }
chomp(my $cpanm = system('/bin/bash', '-c', 'which cpanm &>/dev/null'));
#installs cpanm if missing
if($cpanm){ system('curl -s -L http://cpanmin.us | perl - --sudo App::cpanminus'); }
#loops through required modules and installs them if missing
foreach my $x (@perl){
eval "use $x";
if($@){
system("cpanm $x");
eval "use $x";
}
}
This works well for me, maybe there is something here you can use.
Try this if the 0.0.0.0 method doesn't work
Boring Stuff
I personally battled a lot to get my app accessible to other devices(laptops and mobile phones) through a local-server. I tried the 0.0.0.0 method, but no luck. Then I tried changing the port, but it just didn't work. So, after trying a bunch of different combinations, I arrived to this one, and it solved my problem of deploying my app on a local server.
Steps
ipconfig
on Windows and ifconfig
on Linux
and Mac.Please note: The above step is to be performed on the machine you are serving the app on, and on not the machine on which you are accessing it. Also note, that the IPv4 address might change if you disconnect and reconnect to the network.
Now, simply run the flask app with the acquired IPv4 address.
flask run -h 192.168.X.X
E.g. In my case (see the image), I ran it as:
flask run -h 192.168.1.100
On my mobile device
Optional Stuff
If you are performing this procedure on Windows and using Power Shell as the CLI, and you still aren't able to access the website, try a CTRL + C command in the shell that's running the app. Power Shell gets frozen up sometimes and it needs a pinch to revive. Doing this might even terminate the server, but it sometimes does the trick.
That's it. Give a thumbs up if you found this helpful.
Some more optional stuff
I have created a short Powershell script that will get you your IP address whenever you need one:
$env:getIp = ipconfig
if ($env:getIp -match '(IPv4[\sa-zA-Z.]+:\s[0-9.]+)') {
if ($matches[1] -match '([^a-z\s][\d]+[.\d]+)'){
$ipv4 = $matches[1]
}
}
echo $ipv4
Save it to a file with .ps1 extension (for PowerShell), and run it on before starting your app. You can save it in your project folder and run it as:
.\getIP.ps1; flask run -h $ipv4
Note: I saved the above shellcode in getIP.ps1.
Cool.
No,that would be a security issue.
window.location.replace('pageName.html');
similar behavior as an HTTP redirect
Read How to redirect to another webpage in JavaScript/jQuery?
FOR SWIFT 3.1
func convertDateStringToDate(longDate: String) -> String{
/* INPUT: longDate = "2017-01-27T05:00:00.000Z"
* OUTPUT: "1/26/17"
* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: longDate)
if date != nil {
let formatter = DateFormatter()
formatter.dateStyle = .short
let dateShort = formatter.string(from: date!)
return dateShort
} else {
return longDate
}
}
NOTE: THIS WILL RETURN THE ORIGINAL STRING IF ERROR
have also a site where base - tag is used, and the problem described occured. ( after upgrading jquery ), was able to fix it by having tab urls like this:
<li><a href="{$smarty.server.REQUEST_URI}#tab_1"></li>
this makes them "local"
references i used:
http://bugs.jqueryui.com/ticket/7822 http://htmlhelp.com/reference/html40/head/base.html http://tjvantoll.com/2013/02/17/using-jquery-ui-tabs-with-the-base-tag/
i
iterates through char array words. j
keeps track of word length. "\b \b"
erases word while backing over line.
#include<stdio.h>
int main()
{
int i = 0, j = 0;
char words[] = "Hello Bye";
while(words[i]!='\0')
{
if(words[i] != ' ') {
printf("%c", words[i]);
fflush(stdout);
}
else {
//system("ping -n 1 127.0.0.1>NUL"); //For Microsoft OS
system("sleep 0.25");
while(j-->0) {
printf("\b \b");
}
}
i++;
j++;
}
printf("\n");
return 0;
}
The usual WPF timer is the DispatcherTimer
, which is not a control but used in code. It basically works the same way like the WinForms timer:
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
More on the DispatcherTimer can be found here
If you wish to inject pure function, instead of text, you can use this method:
function inject(){_x000D_
document.body.style.backgroundColor = 'blue';_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var actualCode = "("+inject+")()"; _x000D_
_x000D_
document.documentElement.setAttribute('onreset', actualCode);_x000D_
document.documentElement.dispatchEvent(new CustomEvent('reset'));_x000D_
document.documentElement.removeAttribute('onreset');
_x000D_
And you can pass parameters (unfortunatelly no objects and arrays can be stringifyed) to the functions. Add it into the baretheses, like so:
function inject(color){_x000D_
document.body.style.backgroundColor = color;_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var color = 'yellow';_x000D_
var actualCode = "("+inject+")("+color+")";
_x000D_
Use ` backticks for MYSQL reserved words...
table name "table" is reserved word for MYSQL...
so your query should be as follows...
$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";
Instead of
mount -o rw,remount /system/
use
mount -o rw,remount /system
mind the '/' at the end of the command. you ask why this matters? /system/ is the directory under /system while /system is the volume name.
The number of rows of a list of lists would be: len(A)
and the number of columns len(A[0])
given that all rows have the same number of columns, i.e. all lists in each index are of the same size.
In a parent component you can use @ViewChild() to access child component's method/variable.
@Component({
selector: 'app-number-parent',
templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
@ViewChild(NumberComponent)
private numberComponent: NumberComponent;
increase() {
this.numberComponent.increaseByOne();
}
decrease() {
this.numberComponent.decreaseByOne();
}
}
Update:
Angular 8 onwards -
@ViewChild(NumberComponent, { static: false })
You are trying to read xls
with explicit implementation poi classes for xlsx
.
G:\Selenium Jar Files\TestData\Data.xls
Either use HSSFWorkbook
and HSSFSheet
classes or make your implementation more generic by using shared interfaces, like;
Change:
XSSFWorkbook workbook = new XSSFWorkbook(file);
To:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
And Change:
XSSFSheet sheet = workbook.getSheetAt(0);
To:
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
If you compile the software in debug mode, many compilers will not inline the accessor functions of the vector. This will make the stl vector implementation much slower in circumstances where performance is an issue. It will also make the code easier to debug since you can see in the debugger how much memory was allocated.
In optimized mode, I would expect the stl vector to approach the efficiency of an array. This is since many of the vector methods are now inlined.
EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value
syntax is incorrect.
I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
error message. In 2008, the modified script is still successful.
declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)
To check mongodb version use the mongod command with --version
option.
To check MongoDB Server version, Open the command line via your terminal program and execute the following command:
Path :
C:\Program Files\MongoDB\Server\3.2\bin
Open Cmd and
execute the following command:
mongod --version
To Check MongoDB Shell version, Type:
mongo --version
I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here's the code:
var stopPolling;
var doIframePolling;
$scope.showIframe = true;
doIframePolling = $interval(function () {
if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
$interval.cancel(doIframePolling);
doIframePolling = undefined;
$timeout.cancel(stopPolling);
stopPolling = undefined;
$scope.showIframe = true;
}
},400);
stopPolling = $timeout(function () {
$interval.cancel(doIframePolling);
doIframePolling = undefined;
$timeout.cancel(stopPolling);
stopPolling = undefined;
$scope.showIframe = false;
},5000);
$scope.$on("$destroy",function() {
$timeout.cancel(stopPolling);
$interval.cancel(doIframePolling);
});
Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page. If nothing is present after 5 seconds there was some error (Cors policy) etc.. Show suitable message.Thanks. I hope it solves your problem.
You can use NSArray as
NSString *string1=@"This"
NSString *string2=@"is just"
NSString *string3=@"a test"
NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];
NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];
or
you can use
NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];
I found that only adding padding-top
pushed down the grey dropdown arrow box on the right, which was undesirable.
The method that worked for me was to go into the inspector and incrementally add padding
until the text was centered. This will also reduce the size of the dropdown icon, but it will be centered as well so it isn't as visually disturbing.
In case you don't want to use return statement for each case, try this:
Calculate(int left, int right, Operator op)
{
int result = 0;
switch(op)
{
case Operator.PLUS:
{
result = left + right;;
}
break;
....
}
return result;
}
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
arr = arr.filter(v => v);
as returned v
is implicity converted to truthy
If you haven't yet figured out a way, use the associative property of JavaScript objects to add an extend function to the Object.prototype
as shown below.
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
};
You can then use this function as shown below.
var o = { member: "some member" };
var x = { extension: "some extension" };
o.extend(x);
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
There is no =>
for if.
Use if %energy% GEQ %m2enc%
See if /?
for some other details.
Typescript implementation based on top rated answer
/** Represents the `setTimeout` with an ability to perform pause/resume actions */
export class Timer {
private _start: Date;
private _remaining: number;
private _durationTimeoutId?: NodeJS.Timeout;
private _callback: (...args: any[]) => void;
private _done = false;
get done () {
return this._done;
}
constructor(callback: (...args: any[]) => void, ms = 0) {
this._callback = () => {
callback();
this._done = true;
};
this._remaining = ms;
this.resume();
}
/** pauses the timer */
pause(): Timer {
if (this._durationTimeoutId && !this._done) {
this._clearTimeoutRef();
this._remaining -= new Date().getTime() - this._start.getTime();
}
return this;
}
/** resumes the timer */
resume(): Timer {
if (!this._durationTimeoutId && !this._done) {
this._start = new Date;
this._durationTimeoutId = setTimeout(this._callback, this._remaining);
}
return this;
}
/**
* clears the timeout and marks it as done.
*
* After called, the timeout will not resume
*/
clearTimeout() {
this._clearTimeoutRef();
this._done = true;
}
private _clearTimeoutRef() {
if (this._durationTimeoutId) {
clearTimeout(this._durationTimeoutId);
this._durationTimeoutId = undefined;
}
}
}
Basically, with prepared statements the data coming in from a potential hacker is treated as data - and there's no way it can be intermixed with your application SQL and/or be interpreted as SQL (which can happen when data passed in is placed directly into your application SQL).
This is because prepared statements "prepare" the SQL query first to find an efficient query plan, and send the actual values that presumably come in from a form later - at that time the query is actually executed.
More great info here:
To set thousand separator, say 123,456.78
you have to use DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
System.out.println(df.format(new BigDecimal(123456.75)));
System.out.println(df.format(new BigDecimal(123456.00)));
System.out.println(df.format(new BigDecimal(123456123456.78)));
Here is the result:
123,456.75
123,456.00
123,456,123,456.78
Although I set #,###.00
mask, it successfully formats the longer values too.
Note that the comma(,) separator in result depends on your locale. It may be just space( ) for Russian locale.
This works, been tested...
SELECT n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',
n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM Batches t
Cross Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)
One additional benefit to doing it in javascript is you can add / remove the hover effect at different points in time - e.g. hover over table rows changes color, click disables the hover effect and starts edit in place mode.
for version 11 download the Microsoft SQL Server 2012 Feature Pack https://www.microsoft.com/en-us/download/confirmation.aspx?id=43339
for version 12 download the Microsoft SQL Server 2014 SP2 Feature Pack https://www.microsoft.com/en-us/download/details.aspx?id=42295
This is more concise:
<?php echo get_post_field('post_content', $post->ID); ?>
and this even more:
<?= get_post_field('post_content', $post->ID) ?>
The CSS :active
state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.
To fix your problem you have to create a class and add it manually to the current page's menu:
a.active { color: #f00 }
<ul>
<li><a href="index.php" class="active">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
You can use CSS3 scale
property to resize image with css:
.image:hover {
-webkit-transform:scale(1.2);
transform:scale(1.2);
}
.image {
-webkit-transition: all 0.7s ease;
transition: all 0.7s ease;
}
Further Reading:
Just copy your images and select drawable then on the option of Paste or press shortcut ctrl v. images are added
In the browser's developer console (press F12 to open it), you can type the following,
angular.version.full
it will give you the full version, e.g. (depending on your current version). [It actually gets the full
property of angular.version
object.]
"1.4.3"
So, to see the full object, if you type
angular.version
It will give you the full version object containing version information like full, major, minor and also the codeName, e.g.
Object {full: "1.4.3", major: 1, minor: 4, dot: 3, codeName: "foam-acceleration"}
Right click on project -> maven -> download sources
You declared activity A with the standard launchMode
in the Android manifest. According to the documentation, that means the following:
The system always creates a new instance of the activity in the target task and routes the intent to it.
Therefore, the system is forced to recreate activity A (i.e. calling onCreate
) even if the task stack is handled correctly.
To fix this problem you need to change the manifest, adding the following attribute to the A activity declaration:
android:launchMode="singleTop"
Note: calling finish()
(as suggested as solution before) works only when you are completely sure that the activity B instance you are terminating lives on top of an instance of activity A. In more complex workflows (for instance, launching activity B from a notification) this might not be the case and you have to correctly launch activity A from B.
SELECT * FROM permlog ORDER BY id DESC LIMIT 0, 1
bool pointInRectangle(Point A, Point B, Point C, Point D, Point m ) {
Point AB = vect2d(A, B); float C1 = -1 * (AB.y*A.x + AB.x*A.y); float D1 = (AB.y*m.x + AB.x*m.y) + C1;
Point AD = vect2d(A, D); float C2 = -1 * (AD.y*A.x + AD.x*A.y); float D2 = (AD.y*m.x + AD.x*m.y) + C2;
Point BC = vect2d(B, C); float C3 = -1 * (BC.y*B.x + BC.x*B.y); float D3 = (BC.y*m.x + BC.x*m.y) + C3;
Point CD = vect2d(C, D); float C4 = -1 * (CD.y*C.x + CD.x*C.y); float D4 = (CD.y*m.x + CD.x*m.y) + C4;
return 0 >= D1 && 0 >= D4 && 0 <= D2 && 0 >= D3;}
Point vect2d(Point p1, Point p2) {
Point temp;
temp.x = (p2.x - p1.x);
temp.y = -1 * (p2.y - p1.y);
return temp;}
I just implemented AnT's Answer using c++. I used this code to check whether the pixel's coordination(X,Y) lies inside the shape or not.
try this:
select TITLE,
(length(DESCRIPTION )-length(replace(DESCRIPTION ,'value','')))/5 as COUNT
FROM <table>
This will get you close, the add button has been removed out of the table so you might want to consider this...
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
return false;
});
});
</script>
HTML markup looks like this
<a id="add">+</a></td>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td>Name</td>
</tr>
<tr class="person">
<td><input type="text" name="name" id="name" /></td>
</tr>
</tbody>
</table>
EDIT To empty a value of a textbox after insert..
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
return false;
EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this
$("#mytable tbody>tr:last").each(function() {this.reset();});
I will leave the rest to you!
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
Here is a DLL that shows:
* Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)
* Partition ID (volume serial number)
* CPU ID (unique hardware ID)
* CPU vendor
* CPU running speed
* CPU theoretic speed
* Memory Load ( Total memory used in percentage (%) )
* Total Physical ( Total physical memory in bytes )
* Avail Physical ( Physical memory left in bytes )
* Total PageFile ( Total page file in bytes )
* Available PageFile( Page file left in bytes )
* Total Virtual( Total virtual memory in bytes )
* Available Virtual ( Virtual memory left in bytes )
* Bios unique identification numberBiosDate
* Bios unique identification numberBiosVersion
* Bios unique identification numberBiosProductID
* Bios unique identification numberBiosVideo
(text grabbed from original web site)
It works with C#.
Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).
Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.
since basestring
isn't defined in Python3, this little trick might help to make the code compatible:
try: # check whether python knows about 'basestring'
basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
basestring=str
after that you can run the following test on both Python2 and Python3
isinstance(myvar, basestring)
You mean you want to do "aabbab".toCharArray(); ? Which will return an array of chars. Or do you actually want the resulting array to contain single character string objects?
This fixed version of code above remember the last element of CVS row ;-)
(tested with a CSV file with 5400 rows and 26 elements by row)
public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"') {
bool bolQuote = false;
StringBuilder bld = new StringBuilder();
List<string> retAry = new List<string>();
foreach (char c in r.ToCharArray())
if ((c == fieldSep && !bolQuote))
{
retAry.Add(bld.ToString());
bld.Clear();
}
else
if (c == stringSep)
bolQuote = !bolQuote;
else
bld.Append(c);
/* to solve the last element problem */
retAry.Add(bld.ToString()); /* added this line */
return retAry.ToArray();
}
For C++
If you are referring to ie an AbstractFactory I think that a registerCreatorFunc(..) method usually is better than requiring to add a case for each and every "new" statement that is needed. Then letting all classes create and register a creatorFunction(..) which can be easy implemented with a macro (if I dare to mention). I believe this is a common approach many framework do. I first saw it in ET++ and I think many frameworks that require a DECL and IMPL macro uses it.
You can use Scanner like so:
Scanner s= new Scanner(System.in);
char x = s.next().charAt(0);
By using the charAt function you are able to get the value of the first char without using external casting.
You can select dropdown option value by name
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
with and without api.
public class Reversal {
public static void main(String s[]){
String str= "hello world";
reversal(str);
}
static void reversal(String str){
String s[]=str.split(" ");
StringBuilder noapi=new StringBuilder();
StringBuilder api=new StringBuilder();
for(String r:s){
noapi.append(reversenoapi(r));
api.append(reverseapi(r));
}
System.out.println(noapi.toString());
System.out.println(api.toString());
}
static String reverseapi(String str){
StringBuilder sb=new StringBuilder();
sb.append(new StringBuilder(str).reverse().toString());
sb.append(' ');
return sb.toString();
}
static String reversenoapi(String str){
StringBuilder sb=new StringBuilder();
for(int i=str.length()-1;i>=0;i--){
sb.append(str.charAt(i));
}
sb.append(" ");
return sb.toString();
}
}
This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('/tmp/test.png')
EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show()
when you are ready to display the plots:
import matplotlib.pyplot as plt
# Turn interactive plotting off
plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')
# Display all "open" (non-closed) figures
plt.show()
Just another answer
Array.prototype.filter.call(
document.getElementsByTagName('span'),
function(el) {return el.getAttribute('property') == 'v.name';}
);
In future
Array.prototype.filter.call(
document.getElementsByTagName('span'),
(el) => el.getAttribute('property') == 'v.name'
)
Intro
The call() method calls a function with a given this value and arguments provided individually.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Given this html markup
<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>
you can use this javascript
function findSpan(){
var spans = document.getElementsByTagName('span');
var spansV = Array.prototype.filter.call(
spans,
function(el) {return el.getAttribute('property') == 'v:name';}
);
return spansV;
}
See demo
As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences
JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:
[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"},
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"},
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]
This attack can be achieved in 3 major steps:
Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.
<script src="http://<jsonsite>/json_server.php"></script>
The browser will make a GET request to json_server.php
and any authentication cookies of the user will be sent along with the request.
Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum
" property.
Object.prototype.__defineSetter__('ccnum',function(obj){
secrets =secrets.concat(" ", obj);
});
At this point the malicious site has successfully hijacked the sensitive financial data (ccnum)
returned byjson_server.php
JSON
It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty
There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159
) is returned instead of a JSON array.
There are several ways in which JSON Hijacking can be prevented:
Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.
Prevent the web browser from interpreting the JSON object as valid JavaScript code.
Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.
so as you can see While(1)
comes under the last option. In the most simple terms, while(1)
is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.
So in conclusion, the while(1)
loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.
However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)
*
dplyr::na_if()
is an option:
library(dplyr)
df <- data_frame(col1 = c(1, 2, 3, 0),
col2 = c(0, 2, 3, 4),
col3 = c(1, 0, 3, 0),
col4 = c('a', 'b', 'c', 'd'))
na_if(df, 0)
# A tibble: 4 x 4
col1 col2 col3 col4
<dbl> <dbl> <dbl> <chr>
1 1 NA 1 a
2 2 2 NA b
3 3 3 3 c
4 NA 4 NA d
You can change the number to whatever you wish in following line
length(which(numbers == 4))
The make
uses the $
for its own variable expansions. E.g. single character variable $A
or variable with a long name - ${VAR}
and $(VAR)
.
To put the $
into a command, use the $$
, for example:
all:
@echo "Please execute next commands:"
@echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'
Also note that to make
the ""
and ''
(double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @
sign to see what make
sends to shell.) To prevent the shell from expanding $PATH
, second line uses the ''
.
You cannot provide your own implementation for the setter when using automatic properties. In other words, you should either do:
public int Hour { get;set;} // Automatic property, no implementation
or provide your own implementation for both the getter and setter, which is what you want judging from your example:
public int Hour
{
get { return hour; }
set
{
if (value < MIN_HOUR)
{
hour = 0;
MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
"Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
//take the modulus to ensure always less than 24 hours
//works even if the value is already within range, or value equal to 24
hour = value % MAX_HOUR;
}
}
}
I wrote this so I could edit all tables and columns to null at once:
select
case
when sc.max_length = '-1' and st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(MAX) NULL'
when st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(' + cast(sc.max_length as varchar(4)) + ') NULL'
else
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + ' NULL'
end as query
from sys.columns sc
inner join sys.types st on st.system_type_id = sc.system_type_id
inner join sys.objects so on so.object_id = sc.object_id
where so.type = 'U'
and st.name <> 'timestamp'
order by st.name
So Nodejs comes with the default global variable called '__fileName'
that holds the current file being executed
My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic
Below, I make use of the fileName string and then split it based on the path.sep
. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.
You can write a service like this (Note this is in typescript , but you can very well write it in js )
export class AppLoggingConstants {
constructor(){
}
// Here make sure the fileName param is actually '__fileName'
getDefaultMedata(fileName: string, methodName: string) {
const appName = APP_NAME;
const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
//const actualFileName = fileName;
return appName+ ' -- '+actualFileName;
}
}
export const AppLoggingConstantsInstance = new AppLoggingConstants();
You could transform this dict a little to ensure that (as dicts aren't kept sorted internally), e.g.
pprint([(key, mydict[key]) for key in sorted(mydict.keys())])
Microsoft has a nice chart control. Download it here. Great video on this here. Example code is here. Happy coding!
Tried it today on a 1.3 GB text file. Amongst others every line is checked for existence of a '@' char. 17.000.000 calls to Contains/IndexOf are made. Result: 12.5 sec for all Contains('@') calls, 2.5 sec for all IndexOf('@') calls. => IndexOf performs 5 times faster!! (.Net 4.8)
Yes of course, there is nothing special with floats. You can use the format strings as you use in printf() for floats and anyother datatypes.
EDIT I tried this sample code:
float x = 0.61;
char buf[10];
sprintf(buf, "Test=%.2f", x);
printf(buf);
Output was : Test=0.61
For those who want to do this in pure javascript, look at:
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
I have put @Sharon's code together into the following, which works for me on the iPad with two-finger scrolling. The only thing you should have to change to get it working is the src attribute on the iframe (I used a PDF document).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Pdf Scrolling in mobile Safari</title>
</head>
<body>
<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="data/testdocument.pdf" />
</div>
<script type="text/javascript">
setTimeout(function () {
var startY = 0;
var startX = 0;
var b = document.body;
b.addEventListener('touchstart', function (event) {
parent.window.scrollTo(0, 1);
startY = event.targetTouches[0].pageY;
startX = event.targetTouches[0].pageX;
});
b.addEventListener('touchmove', function (event) {
event.preventDefault();
var posy = event.targetTouches[0].pageY;
var h = parent.document.getElementById("scroller");
var sty = h.scrollTop;
var posx = event.targetTouches[0].pageX;
var stx = h.scrollLeft;
h.scrollTop = sty - (posy - startY);
h.scrollLeft = stx - (posx - startX);
startY = posy;
startX = posx;
});
}, 1000);
</script>
</body>
</html>
Use the password_verify() function
if (password_vertify($inputpassword, $row['password'])) {
print "Logged in";
else {
print "Password Incorrect";
}
I would say you have two options:
to get all parent divs styled with 100%
height (including body and html)
to use absolute positioning for one of the parent divs (for example #content
) and then all child divs set to height 100%
Nothing seemd to work for me, but this did the trick
$(parent.window.document).scroll(function() {
alert("bottom!");
});
Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.
IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
ALTER TABLE Person
ADD ColumnName VARCHAR(MAX) NOT NULL
END
I also noticed yours is looking for where table does exist that is obviously just this
if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null
I have added few lines inside package.json:
"scripts": {
...
"clean": "rmdir /s /q node_modules",
"reinstall": "npm run clean && npm install",
"rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
...
}
If you want to clean
only you can use this rimraf node_modules
.
If you need a simple working solution, try using DefaultTableModel.
If you have created your own table model, that extends AbstractTableModel, then you should also implement removeRow() method. The exact implementation depends on the underlying structure, that you have used to store data.
For example, if you have used Vector, then it may be something like this:
public class SimpleTableModel extends AbstractTableModel {
private Vector<String> columnNames = new Vector<String>();
// Each value in the vector is a row; String[] - row data;
private Vector<String[]> data = new Vector<String[]>();
...
public String getValueAt(int row, int col) {
return data.get(row)[col];
}
...
public void removeRow(int row) {
data.removeElementAt(row);
}
}
If you have used List, then it would be very much alike:
// Each item in the list is a row; String[] - row data;
List<String[]> arr = new ArrayList<String[]>();
public void removeRow(int row) {
data.remove(row);
}
HashMap:
//Integer - row number; String[] - row data;
HashMap<Integer, String[]> data = new HashMap<Integer, String[]>();
public void removeRow(Integer row) {
data.remove(row);
}
And if you are using arrays like this one
String[][] data = { { "a", "b" }, { "c", "d" } };
then you're out of luck, because there is no way to dynamically remove elements from arrays. You may try to use arrays by storing separately some flags notifying which rows are deleted and which are not, or by some other devious way, but I would advise against it... That would introduce unnecessary complexity, and would in fact just be solving a problem by creating another. That's a sure-fire way to end up here. Try one of the above ways to store your table data instead.
For better understanding of how this works, and what to do to make your own model work properly, I strongly advise you to refer to Java Tutorial, DefaultTableModel API and it's source code.
$ cd Desktop
$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
Add icon: https://developer.android.com/studio/write/vector-asset-studio.html
set icon: setIcon(R.drawable.ic_incon_name)
It solved for me using
checkout scm: ([
$class: 'GitSCM',
userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
branches: [[name: 'refs/tags/${project_tag}']]
])
In the spirit of providing functionality, go to your .profile
or .bashrc
file located at /home/usr/
and at the bottom add the line:
alias enw='emacs -nw'
Now each time you open a terminal session you just type, for example, enw
and you have the Emacs no-window option with three letters :).
// jQuery Post
var arraydata = $('.selector').serialize();
// jquery.post serialized var - TO - PHP Array format
parse_str($_POST[arraydata], $searcharray);
print_r($searcharray); // Only for print array
// You get any same of that
Array (
[A] => 1
[B] => 2
[C] => 3
[D] => 4
[E] => 5
[F] => 6
[G] => 7
[H] => 8
)
Just posted my implementation of IndexWhere() extension method (with unit tests):
http://snipplr.com/view/53625/linq-index-of-item--indexwhere/
Example usage:
int index = myList.IndexWhere(item => item.Something == someOtherThing);
class Grandpa
{
public function __construct()
{
echo"Hello Kiddo";
}
}
class Papa extends Grandpa
{
public function __construct()
{
}
public function CallGranddad()
{
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
}
public function needSomethingFromGrandDad
{
parent::CallGranddad();
}
}
You can do it as follow:
#include < iostream >
using namespace std;
int main () {
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts) / 32; a++ ) { // 32 is the size of string data type
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
Try this rule before your other rules:
RewriteRule ^(admin|user)($|/) - [L]
This will end the rewriting process.
select distinct title, (
select count(title)
from kmovies as sub
where sub.title=kmovies.title) as cnt
from kmovies
group by title
order by cnt desc
The web host is not really playing foul. It's not strictly according to the rules - but compared with some some of the amazing inventions intended to prevent spam, its not a particularly bad one.
If you really do want to send mail from '@gmail.com' why not just use the gmail SMTP service? If you can't reconfigure the server where PHP is running, then there are lots of email wrapper tools out there which allow you to specify a custom SMTP relay phpmailer springs to mind.
C.
Idk anything about 16 character hex strings....
using System;
using System.Security.Cryptography;
using System.Text;
But here is mine for creating MD5 hash in one line.
string hash = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes("THIS STRING TO MD5"))).Replace("-","");
If you want a const string that contains Environment.NewLine in it you can do something like this:
const string stringWithNewLine =
@"first line
second line
third line";
Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:
As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n
Most problems are naturally expressed by recursion such as Fibonacci, Merge sorting and quick sorting. In this respect, the code is written for humans, not machines.
Iterative solutions often rely on varying temporary variables which makes the code hard to read. This can be avoided with recursion.
Recursion is not stack friendly. Stack can overflow when the recursion is not well designed or tail optimization is not supported.
Okay, seriously, in many cases at least, this is actually a bug. It shows up in VS Code as well, and it's the linter noticing that you've reached the end of the enclosing scope without closing the scanner object, but not recognizing that closing all open file descriptors is part of process termination. There's no resource leak because the resources are all cleaned up at termination, and the process goes away, leaving nowhere for the resource to be held.
I think this should depend on the situation.Take the following container as an example:
# docker run -it -d ubuntu
91262536f7c9a3060641448120bda7af5ca812b0beb8f3c9fe72811a61db07fc
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
91262536f7c9 ubuntu "/bin/bash" 5 seconds ago Up 4 seconds serene_goldstine
(1) Use "docker attach
" to attach the container:
Since "docker attach
" will not allocate a new tty, but reuse the original running tty, so if you run exit
command, it will cause the running container exit:
# docker attach 91262536f7c9
exit
exit
# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
91262536f7c9 ubuntu "/bin/bash" 39 minutes ago Exited (0) 3 seconds ago serene_goldstine
So unless you really want to make running container exit, you should use Ctrl+p + Ctrl+q.
(2) Use "docker exec
"
Since "docker exec
" will allocate a new tty, so I think you should use exit
instead of Ctrl+p + Ctrl+q.
The following is executing Ctrl+p + Ctrl+q to quit the container:
# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 18160 1908 ? Ss+ 04:03 0:00 /bin/bash
root 15 0.0 0.0 18164 1892 ? Ss 04:03 0:00 bash
root 28 0.0 0.0 15564 1148 ? R+ 04:03 0:00 ps -aux
root@91262536f7c9:/# echo $$
15
Then login container again, you will see the bash
process in preavious docker exec
command is still alive (PID is 15):
# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 18160 1908 ? Ss+ 04:03 0:00 /bin/bash
root 15 0.0 0.0 18164 1892 ? Ss+ 04:03 0:00 bash
root 29 0.0 0.0 18164 1888 ? Ss 04:04 0:00 bash
root 42 0.0 0.0 15564 1148 ? R+ 04:04 0:00 ps -aux
root@91262536f7c9:/# echo $$
29
You can use html2canvas plugin and jsPDF both. Process order: html to png & png to pdf
Example code:
jQuery('#part1').html2canvas({
onrendered: function( canvas ) {
var img1 = canvas.toDataURL('image/png');
}
});
jQuery('#part2').html2canvas({
onrendered: function( canvas ) {
var img2 = canvas.toDataURL('image/png');
}
});
jQuery('#part3').html2canvas({
onrendered: function( canvas ) {
var img3 = canvas.toDataURL('image/png');
}
});
var doc = new jsPDF('p', 'mm');
doc.addImage( img1, 'PNG', 0, 0, 210, 297); // A4 sizes
doc.addImage( img2, 'PNG', 0, 90, 210, 297); // img1 and img2 on first page
doc.addPage();
doc.addImage( img3, 'PNG', 0, 0, 210, 297); // img3 on second page
doc.save("file.pdf");
Use shuf
with the -n
option as shown below, to get N
random lines:
shuf -n N input > output
This seems impossible with the native enum class
, but probably you can mock a enum class
with a class
:
In this case,
enum class b
{
B1,
B2
};
would be equivalent to:
class b {
private:
int underlying;
public:
static constexpr int B1 = 0;
static constexpr int B2 = 1;
b(int v) : underlying(v) {}
operator int() {
return underlying;
}
};
This is mostly equivalent to the original enum class
. You can directly return b::B1
for in a function with return type b
. You can do switch case
with it, etc.
And in the spirit of this example you can use templates (possibly together with other things) to generalize and mock any possible object defined by the enum class
syntax.
All you have to do is add:
#include <string>
using namespace std;
at the top. (BTW I know this was posted in 2013 but I just wanted to answer)
onclick="window.open('your_html', '_blank')"
First you need to create package:
com.myCompany.executabe
(src > right click > new > package).
Follow these steps to move the Java files to your new package.
As other answers have mentioned, you're probably wanting it to be executed in sequence rather in parallel. Ie. run for first file, wait until it's done, then once it's done run for second file. That's not what will happen.
I think it's important to address why this doesn't happen.
Think about how forEach
works. I can't find the source, but I presume it works something like this:
const forEach = (arr, cb) => {
for (let i = 0; i < arr.length; i++) {
cb(arr[i]);
}
};
Now think about what happens when you do something like this:
forEach(files, async logFile(file) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
});
Inside forEach
's for
loop we're calling cb(arr[i])
, which ends up being logFile(file)
. The logFile
function has an await
inside it, so maybe the for
loop will wait for this await
before proceeding to i++
?
No, it won't. Confusingly, that's not how await
works. From the docs:
An await splits execution flow, allowing the caller of the async function to resume execution. After the await defers the continuation of the async function, execution of subsequent statements ensues. If this await is the last expression executed by its function execution continues by returning to the function's caller a pending Promise for completion of the await's function and resuming execution of that caller.
So if you have the following, the numbers won't be logged before "b"
:
const delay = (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
const logNumbers = async () => {
console.log(1);
await delay(2000);
console.log(2);
await delay(2000);
console.log(3);
};
const main = () => {
console.log("a");
logNumbers();
console.log("b");
};
main();
Circling back to forEach
, forEach
is like main
and logFile
is like logNumbers
. main
won't stop just because logNumbers
does some await
ing, and forEach
won't stop just because logFile
does some await
ing.
An out
parameter is a ref
parameter with a special Out()
attribute added. If a parameter to a C# method is declared as out
, the compiler will require that the parameter be written before it can be read and before the method can return. If C# calls a method whose parameter includes an Out()
attribute, the compiler will, for purposes of deciding whether to report "undefined variable" errors, pretend that the variable is written immediately before calling the method. Note that because other .net languages do not attach the same meaning to the Out()
attribute, it is possible that calling a routine with an out
parameter will leave the variable in question unaffected. If a variable is used as an out
parameter before it is definitely assigned, the C# compiler will generate code to ensure that it gets cleared at some point before it is used, but if such a variable leaves and re-enters scope, there's no guarantee that it will be cleared again.
Check here:
Note: Obviously, this is a simple example explaining just how to set up a CtrlC handler, but as always there are rules that need to be obeyed in order not to break something else. Please read the comments below.
The sample code from above:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
void INThandler(int);
int main(void)
{
signal(SIGINT, INThandler);
while (1)
pause();
return 0;
}
void INThandler(int sig)
{
char c;
signal(sig, SIG_IGN);
printf("OUCH, did you hit Ctrl-C?\n"
"Do you really want to quit? [y/n] ");
c = getchar();
if (c == 'y' || c == 'Y')
exit(0);
else
signal(SIGINT, INThandler);
getchar(); // Get new line character
}
This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)
char *words; // setting this to NULL would have prevented the issue
if (condition) {
words = malloc( 512 );
/* calling free sometime later works here */
free(words)
} else {
/* do not allocate words in this branch */
}
/* free(words); -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/
There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:
*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer
IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.
HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.
Session:
//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start();
statement on both these pages before you try to access the $_SESSION
array, and also before any output is sent to the browser.
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.
GET and POST
You can add the variable in the link to the next page:
<a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>
This will create a GET variable.
Another way is to include a hidden field in a form that submits to page two:
<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
And then on page two:
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Just change the method for the form to post
if you want to do it via post. Both are equally insecure, although GET is easier to hack.
The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.
Move the session_start();
to top of the page always.
<?php
@ob_start();
session_start();
?>
Thanks , but i found an alternative solution using ffmpeg:
def save():
os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")
But thank you for your help :)
If there is any tag with an id
(e.g., <div id="foo"
>), then you can simply append #foo
to the URL. Otherwise, you can't arbitrarily link to portions of a page.
Here's a complete example: <a href="http://example.com/page.html#foo">Jump to #foo on page.html</a>
Linking content on the same page example: <a href="#foo">Jump to #foo on same page</a>
It is called a URI fragment.
You might need to enable the table for full-text indexing.
Anaconda has not updated python internally to 3.6.
a) Method 1
conda update python
conda update anaconda
If you want to upgrade between major python version like 3.5 to 3.6, you'll have to do
conda install python=$pythonversion$
b) Method 2 - Create a new environment (Better Method)
conda create --name py36 python=3.6
c) To get the absolute latest python(3.6.5 at time of writing)
conda create --name py365 python=3.6.5 --channel conda-forge
You can see all this from here
Also, refer to this for force upgrading
EDIT: Anaconda now has a Python 3.6 version here
You can use boolval($strValue)
Examples:
<?php
echo '0: '.(boolval(0) ? 'true' : 'false')."\n";
echo '42: '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0: '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2: '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"": '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0": '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1": '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]: '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]: '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>
Documentation http://php.net/manual/es/function.boolval.php
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
Do you have to use the java 8 idioms (steams)? Perphaps a simple solution would be to move the complexity to a map alike data structure that holds numbers as key (without repeating) and the times it ocurrs as a value. You could them iterate that map an only do something with those numbers that are ocurrs > 1.
import java.lang.Math;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class RemoveDuplicates
{
public static void main(String[] args)
{
List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});
Map<Integer,Integer> countByNumber = new HashMap<Integer,Integer>();
for(Integer n:numbers)
{
Integer count = countByNumber.get(n);
if (count != null) {
countByNumber.put(n,count + 1);
} else {
countByNumber.put(n,1);
}
}
System.out.println(countByNumber);
Iterator it = countByNumber.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
}
Thanx, Alexander!
And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:
'swf': {'allowfullscreen':'true', 'wmode':'transparent'}
While the question is just a bit old, this might still help. I'm running into similar issues and using the option below has helped me. Not sure if this is a permanent solution, but it's fixing it for now.
OPTION (OPTIMIZE FOR UNKNOWN)
Then your query will be like this
select * from Table where Col = 'someval' OPTION (OPTIMIZE FOR UNKNOWN)
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
I solved this problem by doing the "subselect" like it:
string newQuery = "select * from (" + query + ") as temp";
When do it on mysql, all collunms properties (unique, non-null ...) will be cleared.