use the request()
helper instead. You don't have to worry about use
statements and thus this sort of problem wont happen again.
$input = request()->all();
simple
You can use dtype=np.int64
instead of dtype=int
First make sure the modal is not in any parent div. Then add $('#myModal').appendTo("body")
It worked fine for me.
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if($response === false) {
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.
I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?
Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,
There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.
The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).
Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.
Java native code necessities:
hope these points answers your question :)
With a null check on the dvdList
and your searchString
if (!StringUtils.isEmpty(searchString)) {
return Optional.ofNullable(dvdList)
.map(Collection::stream)
.orElse(Stream.empty())
.anyMatch(dvd >searchString.equalsIgnoreCase(dvd.getTitle()));
}
I tried using phyatt's AspectRatioPixmapLabel
class, but experienced a few problems:
QLabel::setPixmap(...)
inside the resizeEvent method, because QLabel
actually calls updateGeometry
inside setPixmap
, which may trigger resize events...heightForWidth
seemed to be ignored by the containing widget (a QScrollArea
in my case) until I started setting a size policy for the label, explicitly calling policy.setHeightForWidth(true)
QLabel
's implementation of minimumSizeHint()
does some magic for labels containing text, but always resets the size policy to the default one, so I had to overwrite itThat said, here is my solution. I found that I could just use setScaledContents(true)
and let QLabel
handle the resizing.
Of course, this depends on the containing widget / layout honoring the heightForWidth
.
aspectratiopixmaplabel.h
#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H
#include <QLabel>
#include <QPixmap>
class AspectRatioPixmapLabel : public QLabel
{
Q_OBJECT
public:
explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
virtual int heightForWidth(int width) const;
virtual bool hasHeightForWidth() { return true; }
virtual QSize sizeHint() const { return pixmap()->size(); }
virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};
#endif // ASPECTRATIOPIXMAPLABEL_H
aspectratiopixmaplabel.cpp
#include "aspectratiopixmaplabel.h"
AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
QLabel(parent)
{
QLabel::setPixmap(pixmap);
setScaledContents(true);
QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
policy.setHeightForWidth(true);
this->setSizePolicy(policy);
}
int AspectRatioPixmapLabel::heightForWidth(int width) const
{
if (width > pixmap()->width()) {
return pixmap()->height();
} else {
return ((qreal)pixmap()->height()*width)/pixmap()->width();
}
}
In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.
<form method="post" action="ServerFileToExecute.php">
<input type="submit" name="save" value="Click here to save" />
<input type="submit" name="delete" value="Click here to delete" />
</form>
The server side could look something like this if you use php:
<?php
if(isset($_POST['save']))
echo "Stored!";
else if(isset($_POST['delete']))
echo "Deleted!";
else
echo "Action is missing!";
?>
Might wxChart be an option? I have not used it myself however and it looks like it hasnt been updated for a while.
Just try to run the following command manually:
C:\wamp\bin\mysql\mysql5.6.17\bin\mysqld.exe --console
It worked for me :)
Simply it's work fine, in HTML:
<button type="button" id="btn_CommitAll"class="btn_CommitAll">save</button>
In JQuery side put this function for disable button:
function disableButton() {
$('.btn_CommitAll').prop("disabled", true);
}
For enable button:
function enableButton() {
$('.btn_CommitAll').prop("disabled", false);
}
That's all.
You can render the dependency tree with the command gradle dependencies
. For more information check the section 11.6.4 Listing project dependencies in the online user guide.
use ob_end_clean();
$pdf->Output($file, 'I'); to open pdf. It works for me
I got the same problem, and I solved just adding "return;" at the end of the FileInputStream.
Here is my JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"_x000D_
pageEncoding="ISO-8859-1"%>_x000D_
<%@ page import="java.io.*"%>_x000D_
<%@ page trimDirectiveWhitespaces="true"%>_x000D_
_x000D_
<%_x000D_
_x000D_
try {_x000D_
FileInputStream ficheroInput = new FileInputStream("C:\\export_x_web.pdf");_x000D_
int tamanoInput = ficheroInput.available();_x000D_
byte[] datosPDF = new byte[tamanoInput];_x000D_
ficheroInput.read(datosPDF, 0, tamanoInput);_x000D_
_x000D_
response.setHeader("Content-disposition", "inline; filename=export_sise_web.pdf");_x000D_
response.setContentType("application/pdf");_x000D_
response.setContentLength(tamanoInput);_x000D_
response.getOutputStream().write(datosPDF);_x000D_
_x000D_
response.getOutputStream().flush();_x000D_
response.getOutputStream().close();_x000D_
_x000D_
ficheroInput.close();_x000D_
return;_x000D_
_x000D_
} catch (Exception e) {_x000D_
_x000D_
}_x000D_
%>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
In the GSM specification 3GPP TS 11.11, there are 10 bytes set aside in the MSISDN EF (6F40) for 'dialing number'. Since this is the GSM representation of a phone number, and it's usage is nibble swapped, (and there is always the possibility of parentheses) 22 characters of data should be plenty.
In my experience, there is only one instance of open/close parentheses, that is my reasoning for the above.
You can use nil
about anywhere you can use null
. The main difference is that you can send messages to nil
, so you can use it in some places where null
cant work.
In general, just use nil
.
Here's a plain Javascript way of doing toggle:
<script>
var toggle = function() {
var mydiv = document.getElementById('newpost');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">
I recommend to use the Using jquery validation plugin and jquery ui date picker
jQuery.validator.addMethod("customDateValidator", function(value, element) {
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}
},
"Please enter a valid date format dd-mm-yyyy"
);
this.ui.form.validate({
debug: true,
rules : {
title : { required : true, minlength: 4 },
date : { required: true, customDateValidator: true }
}
}) ;
Using Jquery and date picker just create a function with
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}
You might use only the regular expression for validation
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
return re.test(value)
Of course the date format should be of your region
It's very simple....
import nltk
nltk.download()
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
Not only there is no need to declare it as false
first, I would add few other improvements:
use boolean
instead of Boolean
(which can also be null
for no reason)
assign during declaration:
boolean isMatch = email1.equals(email2);
...and use final
keyword if you can:
final boolean isMatch = email1.equals(email2);
Last but not least:
if (isMatch == true)
can be expressed as:
if (isMatch)
which renders the isMatch
flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...
The simplest way of doing this using an anchor tag would be this:
<a :href="$router.resolve({name: 'posts.show', params: {post: post.id}}).href" target="_blank">
Open Post in new tab
</a>
Update Sept 2017: fs-promise
has been deprecated in favour of fs-extra
.
I haven't used it, but you could look into fs-promise. It's a node module that:
Proxies all async fs methods exposing them as Promises/A+ compatible promises (when, Q, etc). Passes all sync methods through as values.
Days until Christmas:
>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86
More arithmetic here.
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionError
in particular.
assert
and throw new AssertionError()
are very similar and serve the same conceptual purpose, but there are differences.
throw new AssertionError()
will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -ea
switch).throw new AssertionError()
will exit the block, so using it will let you avoid certain compiler errors that assert
will not.For example:
{
boolean b = true;
final int n;
if ( b ) {
n = 5;
} else {
throw new AssertionError();
}
System.out.println("n = " + n);
}
{
boolean b = true;
final int n;
if ( b ) {
n = 5;
} else {
assert false;
}
System.out.println("n = " + n);
}
The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that n
has been initialized by the time the code tries to print it out.
You can use Bundle to get data :
Bundle extras = intent.getExtras();
String data = extras.getString("data"); // use your key
And again you can opass this data to next activity :
Intent intent = new Intent(this, next_Activity.class);
intent.putExtra("data", data);
startActivity(intent);
If you are using SQL Server try this:
SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())
Based on your update it would be:
SELECT * FROM FB WHERE Dte < DATEADD(month, -2, GETDATE())
This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.
As pointed out, the lubridate package has nice extraction functions.
For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.
Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.
For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings
and set Build Timing
option to 'yes
'. After that the time of every build will be displayed in the Output window.
The easiest way is to use a JsonResponse.
For a queryset, you should pass a list of the the values
for that queryset, like so:
from django.http import JsonResponse
queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})
Probably the shortest would be
str(s or '')
Because None is False, and "x or y" returns y if x is false. See Boolean Operators for a detailed explanation. It's short, but not very explicit.
Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html
CheckBox: use change event to call the function and pass the event.
<label class="container">
<input type="checkbox" [(ngModel)]="theCheckbox" data-md-icheck
(change)="toggleVisibility($event)"/>
Checkbox is <span *ngIf="marked">checked</span><span
*ngIf="!marked">unchecked</span>
<span class="checkmark"></span>
</label>
<div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>
Use overloaded version of indexOf()
, which takes the starting index (fromIndex) as 2nd parameter:
str.indexOf("is", str.indexOf("is") + 1);
Yes, Mid
.
Dim sub_str
sub_str = Mid(source_str, 10, 5)
The first parameter is the source string, the second is the start index, and the third is the length.
@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid
results in "invalid procedure call or argument Mid".
Include this code somewhere when you slide to your 'section' called blog.
$("#myLink").click(function() {
setTimeout(function() {
window.navigate("the url of the page you want to navigate back to");
}, 2000);
});
Where myLink
is the id of your href.
JS:
function createDateObj(date) {
var day = date.getDate(); // yields
var month = date.getMonth(); // yields month
var year = date.getFullYear(); // yields year
var hour = date.getHours(); // yields hours
var minute = date.getMinutes(); // yields minutes
var second = date.getSeconds(); // yields seconds
var millisec = date.getMilliseconds();
var jsDate = Date.UTC(year, month, day, hour, minute, second, millisec);
return jsDate;
}
JS:
var oRequirementEval = new Object();
var date = new Date($("#dueDate").val());
CS:
requirementEvaluations.DeadLine = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(Convert.ToDouble( arrayUpdateRequirementEvaluationData["DeadLine"]))
.ToLocalTime();
I had problems converting all columns to numeric with an apply()
call:
apply(data, 2, as.numeric)
The problem turns out to be because some of the strings had a comma in them -- e.g. "1,024.63" instead of "1024.63" -- and R does not like this way of formatting numbers. So I removed them and then ran as.numeric()
:
data = as.data.frame(apply(data, 2, function(x) {
y = str_replace_all(x, ",", "") #remove commas
return(as.numeric(y)) #then convert
}))
Note that this requires the stringr package to be loaded.
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
Try this one,
Create rounded_edittext.xml
file in your Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="15dp">
<solid android:color="#FFFFFF" />
<corners
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" />
<stroke android:width="1dip" android:color="#f06060" />
</shape>
Apply background for your EditText
in xml file
<EditText
android:id="@+id/edit_expiry_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="@drawable/rounded_edittext"
android:hint="@string/shop_name"
android:inputType="text" />
You will get output like this
On Mac OSX, sleep does not take minutes/etc, only seconds. So for two minutes,
sleep 120
Like this:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
Check the docs for more info: NetworkInterface.
This is not very difficult to implement yourself:
function reduceObj(obj, callback, initial) {
"use strict";
var key, lastvalue, firstIteration = true;
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function');
}
if (arguments.length > 2) {
// initial value set
firstIteration = false;
lastvalue = initial;
}
for (key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (firstIteration)
firstIteration = false;
lastvalue = obj[key];
continue;
}
lastvalue = callback(lastvalue, obj[key], key, obj);
}
if (firstIteration) {
throw new TypeError('Reduce of empty object with no initial value');
}
return lastvalue;
}
In action:
var o = {a: {value:1}, b: {value:2}, c: {value:3}};
reduceObj(o, function(prev, curr) { prev.value += cur.value; return prev;}, {value:0});
reduceObj(o, function(prev, curr) { return {value: prev.value + curr.value};});
// both == { value: 6 };
reduceObj(o, function(prev, curr) { return prev + curr.value; }, 0);
// == 6
You can also add it to the Object prototype:
if (typeof Object.prototype.reduce !== 'function') {
Object.prototype.reduce = function(callback, initial) {
"use strict";
var args = Array.prototype.slice(arguments);
args.unshift(this);
return reduceObj.apply(null, args);
}
}
Try this
box-sizing: border-box;
@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
lbl_cookie_value.Text = cook.Value;
}
else
{
lbl_cookie_value.Text = "Empty value";
}
Reference Click here
Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:
<?php
/////// SYNTAX ERROR CHECK ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');
//replace "pageToTest.php" with the file path that you want to test.
include('pageToTest.php');
?>
Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.
Visual studio’s smart indenting does automatically indenting, but we can select a block or all the code for indentation.
Select all the code: Ctrl+a
Use either of the two ways to indentation the code:
Shift+Tab,
Ctrl+k+f.
First, you need to import from inspect
and os
from inspect import getsourcefile
from os.path import abspath
Next, wherever you want to find the source file from you just use
abspath(getsourcefile(lambda:0))
In case the WebSocket server initiative disconnects the
ws
link after a few minutes there no messages sent between the server and client.
client sends a custom ping
message, to keep alive by using the keepAlive
function
server ignore the ping
message and response a custom pong
message
var timerID = 0;
function keepAlive() {
var timeout = 20000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
clearTimeout(timerId);
}
}
If you run SHOW VARIABLES
from a mysql console you can look for basedir.
When I run the following:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';
on my system I get /usr/local/mysql
as the Value returned.
(I am not using MAMP - I installed MySQL with homebrew.
mysqld
on my machine is in /usr/local/mysql/bin
so the basedir is where most everything will be installed to.
Also util:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir';
To find where the DBs are stored.
For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html
and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir
The usual way is to use zip()
:
for x, y in zip(a, b):
# x is from a, y is from b
This will stop when the shorter of the two iterables a
and b
is exhausted. Also worth noting: itertools.izip()
(Python 2 only) and itertools.izip_longest()
(itertools.zip_longest()
in Python 3).
What you are trying to achieve is equivalent to
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.
All containers from api
can join the front
default network with following config:
# api/docker-compose.yml
...
networks:
default:
external:
name: front_default
See docker compose guide: using a pre existing network (see at the bottom)
Your import has a subtle error:
import java.awt.List;
It should be:
import java.util.List;
The problem is that both awt
and Java's util package provide a class called List
. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList
extends java.util.List
, not java.awt.List
so if it wasn't for the generics, it would have still been a problem.
Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.
import org.omg.DynamicAny.NameValuePair;
should be
import org.apache.http.NameValuePair
nameValuePairs
now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity
, which is List<? extends NameValuePair>
, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair
did not extend org.apache.http.NameValuePair
and the shortened type name NameValuePair
evaluated to org.omg...
in your file, but org.apache...
in their code.
use ondragstart(event)
instead of ondrag(event)
iOS 10 update
Apple changed the method to open async on the main thread. However, from now it is only possible to open the app settings in native settings.
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
iOS 9 update
It is now possible to go directly to sub-settings menu. However, a URL scheme has to be created. It can be done using two ways:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>prefs</string>
</array>
</dict>
</array>
Then the code:
Swift
UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=General&path=Keyboard")!)
Objective-c
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General&path=Keyboard"]];
If you are just comparing numbers, I think there's no need to change syntax, just correct those lines, lines 6 and 9 brackets.
Line 6 before: if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]
After: if [ "$age" -le "7" -o "$age" -ge "65" ]
Line 9 before: elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]
After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
You can use the ScriptManager.RegisterStartupScript();
to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();
, you can do this:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
//----or alternatively and to be more proper
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}
To be exact for you, do this...
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
I've added some code to my project, so it's more convenient.
HtmlExtensions.cs:
namespace System.Web.Mvc.Html
{
public static class HtmlExtensions
{
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId)
{
return htmlHelper.BeginForm(null, null, FormMethod.Post, new { id = formId });
}
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId, FormMethod method)
{
return htmlHelper.BeginForm(null, null, method, new { id = formId });
}
}
}
MySignupForm.cshtml:
@using (Html.BeginForm("signupform"))
{
@* Some fields *@
}
API's are a published interface which defines how component A communicates with component B.
For example, Doubleclick have a published Java API which allows users to interrogate the database tables to get information about their online advertising campaign.
e.g. call GetNumberClicks (user name)
To implement the API, you have to add the Doubleclick .jar file to your class path. The call is local.
A web service is a form of API where the interface is defined by means of a WSDL. This allows remote calling of an interface over HTTP.
If Doubleclick implemented their interface as a web service, they would use something like Axis2 running inside Tomcat.
The remote user would call the web service
e.g. call GetNumberClicksWebService (user name)
and the GetNumberClicksWebService service would call GetNumberClicks locally.
I won't argue that it's a good idea (or the semantics of using nullptr
with things that aren't pointers), but it's relatively simple to create a class which would provide "nullable" semantics (see nullable_string).
However, this is a much better fit for C++17's std::optional:
#include <string>
#include <iostream>
#include <optional>
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b)
{
if (b)
return "Godzilla";
else
return {};
}
int main()
{
std::cout << "create(false) returned "
<< create(false).value_or("empty") << std::endl;
// optional-returning factory functions are usable as conditions of while and if
if (auto str = create(true))
{
std::cout << "create(true) returned " << *str << std::endl;
}
}
std::optional
, as shown in the example, is convertible to bool
, or you may use the has_value()
method, has exceptions for bad access, etc. This provides you with nullable semantics, which seems to be what Maria was trying to accomplish.
And if you don't want to wait around for C++17 compatibility, see this answer about Boost.Optional.
Tkinter is the "standard" GUI for Python, meaning it should be available with every Python installation.
In terms of learning it, and particularly learning how to use recent versions of Tkinter (which have improved a lot), I very highly recommend the TkDocs tutorial that I put together a while back - see http://www.tkdocs.com
Loaded with examples, covers basic concepts and all of the core widgets.
For my own future reference:
With cx_Oracle use cursor.setinputsize(...):
mycursor = connection.cursor();
mycursor.setinputsize( mytimestamp=cx_Oracle.TIMESTAMP );
params = { 'mytimestamp': timestampVar };
cusrsor.execute("INSERT INTO mytable (timestamp_field9 VALUES(:mytimestamp)", params);
No converting in the db needed. See Oracle Documentation
All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object
(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)
import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)
Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/
(Note that the use of var
for in
tests make a difference when in a scoped wrapper)
Code for reference:
(function(undefined) {
var definedButNotInitialized;
definedAndInitialized = 3;
someObject = {
firstProp: "1"
, secondProp: false
// , undefinedProp not defined
}
// var notDefined;
var tests = [
'definedButNotInitialized in window',
'definedAndInitialized in window',
'someObject.firstProp in window',
'someObject.secondProp in window',
'someObject.undefinedProp in window',
'notDefined in window',
'"definedButNotInitialized" in window',
'"definedAndInitialized" in window',
'"someObject.firstProp" in window',
'"someObject.secondProp" in window',
'"someObject.undefinedProp" in window',
'"notDefined" in window',
'typeof definedButNotInitialized == "undefined"',
'typeof definedButNotInitialized === typeof undefined',
'definedButNotInitialized === undefined',
'! definedButNotInitialized',
'!! definedButNotInitialized',
'typeof definedAndInitialized == "undefined"',
'typeof definedAndInitialized === typeof undefined',
'definedAndInitialized === undefined',
'! definedAndInitialized',
'!! definedAndInitialized',
'typeof someObject.firstProp == "undefined"',
'typeof someObject.firstProp === typeof undefined',
'someObject.firstProp === undefined',
'! someObject.firstProp',
'!! someObject.firstProp',
'typeof someObject.secondProp == "undefined"',
'typeof someObject.secondProp === typeof undefined',
'someObject.secondProp === undefined',
'! someObject.secondProp',
'!! someObject.secondProp',
'typeof someObject.undefinedProp == "undefined"',
'typeof someObject.undefinedProp === typeof undefined',
'someObject.undefinedProp === undefined',
'! someObject.undefinedProp',
'!! someObject.undefinedProp',
'typeof notDefined == "undefined"',
'typeof notDefined === typeof undefined',
'notDefined === undefined',
'! notDefined',
'!! notDefined'
];
var output = document.getElementById('results');
var result = '';
for(var t in tests) {
if( !tests.hasOwnProperty(t) ) continue; // bleh
try {
result = eval(tests[t]);
} catch(ex) {
result = 'Exception--' + ex;
}
console.log(tests[t], result);
output.innerHTML += "\n" + tests[t] + ": " + result;
}
})();
And results:
definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined
the following works for me,
mockMvc.perform(
MockMvcRequestBuilders.post("/api/test/url")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(createItemForm)))
.andExpect(status().isCreated());
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
EDIT: You should check out Needle. It does this for you and supports multipart data, and a lot more.
I figured out I was missing a header
var request = require('request');
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/test2.php',
body: "mes=heydude"
}, function(error, response, body){
console.log(body);
});
I spent some significant amount of time using the FileSystemWatcher, and some of the approaches here will not work. I really liked the disabling events approach, but unfortunately, it doesn't work if there is >1 file being dropped, second file will be missed most if not all times. So I use the following approach:
private void EventCallback(object sender, FileSystemEventArgs e)
{
var fileName = e.FullPath;
if (!File.Exists(fileName))
{
// We've dealt with the file, this is just supressing further events.
return;
}
// File exists, so move it to a working directory.
File.Move(fileName, [working directory]);
// Kick-off whatever processing is required.
}
This works for me.
private OnClickListener mDisconnectListener;
mDisconnectListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
};
...
... onCreateView(...){
mButtonDisconnect = (Button) rootView.findViewById(R.id.button_disconnect);
mButtonDisconnect.setOnClickListener(mDisconnectListener);
...
}
check if you are using more than one internet connection to your pc like one is LAN second one is Modem , so disable all lan or modem .
Not necessary to use \restylefloat
and destroys other options, like caption placement. just use [H]
or [!h]
after \begin{table}
.
I always use a Form Close method in my applications that catches alt + x from my exit Button, alt + f4 or another form closing event was initiated. All my classes have the class name defined as Private string mstrClsTitle = "grmRexcel"
in this case, an Exit method that calls the Form Closing Method and a Form Closing Method. I also have a statement for the Form Closing Method - this.FormClosing = My Form Closing Form Closing method name
.
The code for this:
namespace Rexcel_II
{
public partial class frmRexcel : Form
{
private string mstrClsTitle = "frmRexcel";
public frmRexcel()
{
InitializeComponent();
this.FormClosing += frmRexcel_FormClosing;
}
/// <summary>
/// Handles the Button Exit Event executed by the Exit Button Click
/// or Alt + x
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Handles the Form Closing event
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frmRexcel_FormClosing(object sender, FormClosingEventArgs e)
{
// ---- If windows is shutting down,
// ---- I don't want to hold up the process
if (e.CloseReason == CloseReason.WindowsShutDown) return;
{
// ---- Ok, Windows is not shutting down so
// ---- either btnExit or Alt + x or Alt + f4 has been clicked or
// ---- another form closing event was intiated
// *) Confirm user wants to close the application
switch (MessageBox.Show(this,
"Are you sure you want to close the Application?",
mstrClsTitle + ".frmRexcel_FormClosing",
MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
// ---- *) if No keep the application alive
//---- *) else close the application
case DialogResult.No:
e.Cancel = true;
break;
default:
break;
}
}
}
}
}
Note that the IEnumerable<T>
allready implemented by the System.Collections
so another approach is to derive your MyObjects
class from System.Collections
as a base class (documentation):
System.Collections: Provides the base class for a generic collection.
We can later make our own implemenation to override the virtual System.Collections
methods to provide custom behavior (only for ClearItems
, InsertItem
, RemoveItem
, and SetItem
along with Equals
, GetHashCode
, and ToString
from Object
). Unlike the List<T>
which is not designed to be easily extensible.
Example:
public class FooCollection : System.Collections<Foo>
{
//...
protected override void InsertItem(int index, Foo newItem)
{
base.InsertItem(index, newItem);
Console.Write("An item was successfully inserted to MyCollection!");
}
}
public static void Main()
{
FooCollection fooCollection = new FooCollection();
fooCollection.Add(new Foo()); //OUTPUT: An item was successfully inserted to FooCollection!
}
Please note that driving from collection
recommended only in case when custom collection behavior is needed, which is rarely happens. see usage.
For the Single line and double line break here are the following codes.
Single break: %0D0A
Double break: %0D0A%0D0A
SELECT CONVERT(DOUBLE PRECISION, [ColumnName])
The primary purpose is to avoid chained indexing and eliminate the SettingWithCopyWarning
.
Here chained indexing is something like dfc['A'][0] = 111
The document said chained indexing should be avoided in Returning a view versus a copy. Here is a slightly modified example from that document:
In [1]: import pandas as pd
In [2]: dfc = pd.DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})
In [3]: dfc
Out[3]:
A B
0 aaa 1
1 bbb 2
2 ccc 3
In [4]: aColumn = dfc['A']
In [5]: aColumn[0] = 111
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [6]: dfc
Out[6]:
A B
0 111 1
1 bbb 2
2 ccc 3
Here the aColumn
is a view and not a copy from the original DataFrame, so modifying aColumn
will cause the original dfc
be modified too. Next, if we index the row first:
In [7]: zero_row = dfc.loc[0]
In [8]: zero_row['A'] = 222
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [9]: dfc
Out[9]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time zero_row
is a copy, so the original dfc
is not modified.
From these two examples above, we see it's ambiguous whether or not you want to change the original DataFrame. This is especially dangerous if you write something like the following:
In [10]: dfc.loc[0]['A'] = 333
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [11]: dfc
Out[11]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time it didn't work at all. Here we wanted to change dfc
, but we actually modified an intermediate value dfc.loc[0]
that is a copy and is discarded immediately. It’s very hard to predict whether the intermediate value like dfc.loc[0]
or dfc['A']
is a view or a copy, so it's not guaranteed whether or not original DataFrame will be updated. That's why chained indexing should be avoided, and pandas generates the SettingWithCopyWarning
for this kind of chained indexing update.
Now is the use of .copy()
. To eliminate the warning, make a copy to express your intention explicitly:
In [12]: zero_row_copy = dfc.loc[0].copy()
In [13]: zero_row_copy['A'] = 444 # This time no warning
Since you are modifying a copy, you know the original dfc
will never change and you are not expecting it to change. Your expectation matches the behavior, then the SettingWithCopyWarning
disappears.
Note, If you do want to modify the original DataFrame, the document suggests you use loc
:
In [14]: dfc.loc[0,'A'] = 555
In [15]: dfc
Out[15]:
A B
0 555 1
1 bbb 2
2 ccc 3
use
select * from sys.procedures
to show all your procedures;
sp_helptext @objname = 'Procedure_name'
to get the code
and your creativity to build something to loop through them all and generate the export code :)
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
If you want to increase the memory usage of the node globally - not only single script, you can export environment variable, like this:
export NODE_OPTIONS=--max_old_space_size=4096
Then you do not need to play with files when running builds like
npm run build
.
Newtonsoft.JSON
is a good solution for these kind of situations. Also Newtonsof.JSON
is faster than others, such as JavaScriptSerializer
, DataContractJsonSerializer
.
In this sample, you can the following:
var jsonData = JObject.Parse("your JSON data here");
Then you can cast jsonData to JArray
, and you can use a for
loop to get data at each iteration.
Also, I want to add something:
for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
var data = jsonData[i - 1];
}
Working with dynamic object and using Newtonsoft serialize is a good choice.
If you have a class with an object property, or if your property actually casts to an object, you can reshape the object by reassigning its properties, as in:
MyClass varClass = new MyClass();
varClass.propObjectProperty = new { Id = 1, Description = "test" };
//if you need to treat the class as an object
var varObjectProperty = ((dynamic)varClass).propObjectProperty;
((dynamic)varClass).propObjectProperty = new { Id = varObjectProperty.Id, Description = varObjectProperty.Description, NewDynamicProperty = "new dynamic property description" };
//if your property is an object, instead
var varObjectProperty = varClass.propObjectProperty;
varClass.propObjectProperty = new { Id = ((dynamic)varObjectProperty).Id, Description = ((dynamic)varObjectProperty).Description, NewDynamicProperty = "new dynamic property description" };
With this approach, you basically rewrite the object property adding or removing properties as if you were first creating the object with the
new { ... }
syntax.
In your particular case, you're probably better off creating an actual object to which you assign properties like "dob" and "address" as if it were a person, and at the end of the process, transfer the properties to the actual "Person" object.
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//if you want to interrupt going to another location.
event.preventDefault(); });
Cookie is basically a global array accessed across web browsers. Many a times used to send/receive values. it acts as a storage mechanism to access values between forms. Cookies can be disabled by the browser which adds a constraint to their use in comparison to session.
Session can be defined as something between logging in and logging out. the time between the user logging in and logging out is a session. Session stores values only for the session time i.e before logging out. Sessions are used to track the activities of the user, once he logs on.
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.setAttribute("style","color:red;font-size:23px");
btn.appendChild(t);
document.body.appendChild(btn);
btn.setAttribute("onclick", alert("clicked"));
}
</script>
</body>
</html>
You shouldn't need a $watch. Just bind to resize event on window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E',
template: '<div>window size: {{width}}px</div>'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
angular.element($window).bind('resize', function(){
scope.width = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
}]);
I had a similar related question: What if you wanted the original object format back (with key names, e.g. FOO, BAR)?
Jq provides to_entries
and from_entries
to convert between objects and key-value pair arrays. That along with map
around the select
These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.
from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries, useful for doing some operation to all keys and values of an object. from_entries accepts key, Key, name, Name, value and Value as keys.
jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'
{
"FOO": {
"name": "Donald",
"location": "Stockholm"
},
"BAR": {
"name": "Walt",
"location": "Stockholm"
}
}
Using the with_entries
shorthand, this becomes:
jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
"FOO": {
"name": "Donald",
"location": "Stockholm"
},
"BAR": {
"name": "Walt",
"location": "Stockholm"
}
}
You just need to put a small timeout event before doing .click()
like this :
setTimeout(function(){ $('#btn').click()}, 100);
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
Modified version from @dovidev as his version loads the image externally instead of reading the local cache.
var cached_anchors = $$('a');_x000D_
document.body.innerHTML = '';_x000D_
for (var i in cached_anchors) {_x000D_
var ca = cached_anchors[i];_x000D_
if(ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.open("GET", ca.href);_x000D_
xhr.responseType = "document";_x000D_
xhr.onload = response;_x000D_
xhr.send();_x000D_
}_x000D_
}_x000D_
_x000D_
function response(e) {_x000D_
var hexdata = this.response.getElementsByTagName("pre")[2].innerHTML.split(/\r?\n/).slice(0,-1).map(e => e.split(/[\s:]+\s/)[1]).map(e => e.replace(/\s/g,'')).join('');_x000D_
var byteArray = new Uint8Array(hexdata.length/2);_x000D_
for (var x = 0; x < byteArray.length; x++){_x000D_
byteArray[x] = parseInt(hexdata.substr(x*2,2), 16);_x000D_
}_x000D_
var blob = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
var image = new Image();_x000D_
image.src = URL.createObjectURL(blob);_x000D_
document.body.appendChild(image);_x000D_
}
_x000D_
If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:
echo '<p style="color: red; text-align: center">
Request has been sent. Please wait for my reply!
</p>';
You can look at the headers or libs installed. pkg-config can tell you where they are:
pkg-config --cflags opencv
pkg-config --libs opencv
Alternatively you can write a simple program and print the following defs:
CV_MAJOR_VERSION
CV_MINOR_VERSION
A similar question has been also asked here:
I have experimented many of the backslash escape characters. \n
which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.
Code:
#include <stdio.h>
int main(void){
printf("Hello World!");
printf("Goodbye \a");
printf("Hi \b");
printf("Yo\f");
printf("What? \t");
printf("pewpew");
return 0;
}
differentiate a raw js object from a HTMLElement
function isDOM (x){
return /HTML/.test( {}.toString.call(x) );
}
use:
isDOM( {a:1} ) // false
isDOM( document.body ) // true
// OR
Object.defineProperty(Object.prototype, "is",
{
value: function (x) {
return {}.toString.call(this).indexOf(x) >= 0;
}
});
use:
o={}; o.is("HTML") // false
o=document.body; o.is("HTML") // true
I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:
ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }
If i´m adding a listener
this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
alert('Clicking the document');
})
I´d expect my function to execute what i intended, not the total opposite which is remove the listener.
// I´d expect an alert('Clicking the document');
this.listenToClick();
// what you actually get is removing the listener, so nothing...
In the given scenario, It´d actually make to more sense to name it like:
// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
console.log('Clicking the document', evt);
})
let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
console.log('Clicking the button', evt);
});
There must be a good reason for this but in my opinion it´s very misleading and not intuitive.
In Bootstrap 4 you can use the form-check-inline class.
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="queryFieldName" id="option1" value="1">
<label class="form-check-label" for="option1">First</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="queryFieldName" id="option2" value="2">
<label class="form-check-label" for="option2">Second</label>
</div>
ALTER TABLE
`table_name`
MODIFY COLUMN
`column_name2` enum(
'existing_value1',
'existing_value2',
'new_value1',
'new_value2'
)
NOT NULL AFTER `column_name1`;
I wound up here looking for a solution as well.
Depending on the high-end number of items you need to query against, and assuming your items are unique, you could split your query into batches queries of 1000 items, and combine the results on your end instead (pseudocode here):
//remove dupes
items = items.RemoveDuplicates();
//how to break the items into 1000 item batches
batches = new batch list;
batch = new batch;
for (int i = 0; i < items.Count; i++)
{
if (batch.Count == 1000)
{
batches.Add(batch);
batch.Clear()
}
batch.Add(items[i]);
if (i == items.Count - 1)
{
//add the final batch (it has < 1000 items).
batches.Add(batch);
}
}
// now go query the db for each batch
results = new results;
foreach(batch in batches)
{
results.Add(query(batch));
}
This may be a good trade-off in the scenario where you don't typically have over 1000 items - as having over 1000 items would be your "high end" edge-case scenario. For example, in the event that you have 1500 items, two queries of (1000, 500) wouldn't be so bad. This also assumes that each query isn't particularly expensive in of its own right.
This wouldn't be appropriate if your typical number of expected items got to be much larger - say, in the 100000 range - requiring 100 queries. If so, then you should probably look more seriously into using the global temporary tables solution provided above as the most "correct" solution. Furthermore, if your items are not unique, you would need to resolve duplicate results in your batches as well.
Try the MutationObserver:
browser support: http://caniuse.com/#feat=mutationobserver
<html>_x000D_
<!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
// Inspect the array of MutationRecord objects to identify the nature of the change_x000D_
function mutationObjectCallback(mutationRecordsList) {_x000D_
console.log("mutationObjectCallback invoked.");_x000D_
_x000D_
mutationRecordsList.forEach(function(mutationRecord) {_x000D_
console.log("Type of mutation: " + mutationRecord.type);_x000D_
if ("attributes" === mutationRecord.type) {_x000D_
console.log("Old attribute value: " + mutationRecord.oldValue);_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Create an observer object and assign a callback function_x000D_
var observerObject = new MutationObserver(mutationObjectCallback);_x000D_
_x000D_
// the target to watch, this could be #yourUniqueDiv _x000D_
// we use the body to watch for changes_x000D_
var targetObject = document.body; _x000D_
_x000D_
// Register the target node to observe and specify which DOM changes to watch_x000D_
_x000D_
_x000D_
observerObject.observe(targetObject, { _x000D_
attributes: true,_x000D_
attributeFilter: ["id", "dir"],_x000D_
attributeOldValue: true,_x000D_
childList: true_x000D_
});_x000D_
_x000D_
// This will invoke the mutationObjectCallback function (but only after all script in this_x000D_
// scope has run). For now, it simply queues a MutationRecord object with the change information_x000D_
targetObject.appendChild(document.createElement('div'));_x000D_
_x000D_
// Now a second MutationRecord object will be added, this time for an attribute change_x000D_
targetObject.dir = 'rtl';_x000D_
_x000D_
_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.
The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"
Just Disable the form submit button, like below code.
<form ... onsubmit="buttonName.disabled=true; return true;">
<input type="submit" name="buttonName" value="Submit">
</form>
It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.
htop
gives a nice overview of individual core usage
You can use a Javascript bookmark: https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/. Just create a bookmark to look like this:
Ex:
Name:
Test javascript bookmark in Chrome
URL:
javascript:alert('Hello world!');
Just precede the URL with javascript:
, followed by your Javascript code. No space after the colon is required.
Here's how it looks as I'm typing it in:
Now save and then click on your newly-created Javascript bookmark, and you'll see this:
You can do multi-line scripts too. If you include any comments, however, be sure to use the C-style multi-line comments ONLY (/* comment */
), and NOT the C++-style single-line comments (// comment
), as they will interfere. Here's an example:
URL:
javascript:
/* This is my javascript demo */
function multiply(a, b)
{
return a * b;
}
var a = 1.4108;
var b = 3.7654;
var result = multiply(a, b);
alert('The result of ' + a + ' x ' + b + ' = ' + result.toFixed(4));
And here's what it looks like as you edit the bookmark, after copying and pasting the above multi-line script into the URL field for the bookmark:
And here's the output when you click on it:
Even if your annotations are declared correctly to properly manage the one-to-many relationship you may still encounter this precise exception. When adding a new child object, Transaction
, to an attached data model you'll need to manage the primary key value - unless you're not supposed to. If you supply a primary key value for a child entity declared as follows before calling persist(T)
, you'll encounter this exception.
@Entity
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
....
In this case, the annotations are declaring that the database will manage the generation of the entity's primary key values upon insertion. Providing one yourself (such as through the Id's setter) causes this exception.
Alternatively, but effectively the same, this annotation declaration results in the same exception:
@Entity
public class Transaction {
@Id
@org.hibernate.annotations.GenericGenerator(name="system-uuid", strategy="uuid")
@GeneratedValue(generator="system-uuid")
private Long id;
....
So, don't set the id
value in your application code when it's already being managed.
I have faced same issue after install macOS Catalina. I had try below command and its working.
sudo gem update
The SQLite documentation is a great reference and the DateAndTimeFunctions page is a good one to bookmark.
It's also helpful to remember that it's pretty easy to play with queries with the sqlite command line utility:
sqlite> select julianday(datetime('now'));
2454788.09219907
sqlite> select datetime(julianday(datetime('now')));
2008-11-17 14:13:55
I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:
find . -type d -exec chmod 755 {} \+
but this also does the same thing:
chmod 755 `find . -type d`
and so does this:
chmod 755 $(find . -type d)
The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.
So I think in your case that the following will do what you want.
chmod 777 $(find "/Users/Test/Desktop/PATH")
Yes , Jared and Kelly Orr are right. I use the following code like in edit exception.
foreach (var issue in dinner.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
in stead of
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Firstly create app.js
file in the directory you want to publish.
var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
if (req.url != '/app.js') {
var url = __dirname + req.url;
fs.stat(url,function(err,stat){
if (err) {
res.writeHead(404,{'Content-Type':'text/html'});
res.end('Your requested URI('+req.url+') wasn\'t found on our server');
} else {
var type = mime.getType(url);
var fileSize = stat.size;
var range = req.headers.range;
if (range) {
var parts = range.replace(/bytes=/, "").split("-");
var start = parseInt(parts[0], 10);
var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
var chunksize = (end-start)+1;
var file = fs.createReadStream(url, {start, end});
var head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': type
}
res.writeHead(206, head);
file.pipe(res);
} else {
var head = {
'Content-Length': fileSize,
'Content-Type': type
}
res.writeHead(200, head);
fs.createReadStream(url).pipe(res);
}
}
});
} else {
res.writeHead(403,{'Content-Type':'text/html'});
res.end('Sorry, access to that file is Forbidden');
}
}).listen(8080);
Simply run node app.js
and your server shall be running on port 8080. Besides video it can stream all kinds of files.
My app worked on all simulators but not on my device. I tried just about all the steps from each comment and didn't have any luck. I went to my device settings and switched my "Personal Hotspot" from off to on. Then it was all good!
@
operatorFor undesired and redundant notices, one could use the dedicated @
operator to »hide« undefined variable/index messages.
$var = @($_GET["optional_param"]);
isset?:
or ??
super-supression however. Notices still can get logged. And one may resurrect @
-hidden notices with: set_error_handler("var_dump");
if (isset($_POST["shubmit"]))
in your initial code.@
or isset
only after verifying functionality.Fix the cause first. Not the notices.
@
is mainly acceptable for $_GET
/$_POST
input parameters, specifically if they're optional.And since this covers the majority of such questions, let's expand on the most common causes:
$_GET
/ $_POST
/ $_REQUEST
undefined inputFirst thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Secondly, if the notice doesn't have an obvious cause, use var_dump
or print_r
to verify all input arrays for their curent content:
var_dump($_GET);
var_dump($_POST);
//print_r($_REQUEST);
Both will reveal if your script was invoked with the right or any parameters at all.
Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:
POST parameters and GET input will be be shown separately.
For $_GET
parameters you can also peek at the QUERY_STRING
in
print_r($_SERVER);
PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well.
You can also look at supplied raw $_COOKIES
and other HTTP request headers that way.
More obviously look at your browser address bar for GET parameters:
http://example.org/script.php?id=5&sort=desc
The name=value
pairs after the ?
question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"]
and $_GET["sort"]
.
Finally check your <form>
and <input>
declarations, if you expect a parameter but receive none.
<input name=FOO>
id=
or title=
attribute does not suffice.method=POST
form ought to populate $_POST
.method=GET
(or leaving it out) would yield $_GET
variables.action=script.php?get=param
via $_GET and the remaining method=POST
fields in $_POST alongside.$_REQUEST['vars']
again, which mashes GET and POST params.If you are employing mod_rewrite, then you should check both the access.log
as well as enable the RewriteLog
to figure out absent parameters.
$_FILES
$_FILES["formname"]
.enctype=multipart/form-data
method=POST
in your <form>
declaration.$_COOKIE
$_COOKIE
array is never populated right after setcookie()
, but only on any followup HTTP request.C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
Alternative way with substring and regexpr:
substring(name, 1) <- toupper(substring(name, 1, 1))
pos <- regexpr(" ", name, perl=TRUE) + 1
substring(name, pos) <- toupper(substring(name, pos, pos))
There is a trick that allows anonymous class to update data in the outer scope.
private void f(Button b, final int a) {
final int[] res = new int[1];
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
res[0] = a * 5;
}
});
// But at this point handler is most likely not executed yet!
// How should we now res[0] is ready?
}
However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated
This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:
// ...
final int[] res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);
// ...
I prefer to work with the PSDrive WSMan:\
.
Get TrustedHosts
Get-Item WSMan:\localhost\Client\TrustedHosts
Set TrustedHosts
provide a single, comma-separated, string of computer names
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'
or (dangerous) a wild-card
Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'
to append to the list, the -Concatenate
parameter can be used
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate
I think that substr() throws an exception if str only contains the whitespace.
I would modify it to the following code:
string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
if (first == std::string::npos)
return "";
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}
The thing that worked for me:
Put your file inside of the folder specified in secure-file-priv
.
To find that type:
mysql> show variables like "secure_file_priv";
Check if you have local_infile = 1
.
Do that typing:
mysql> show variables like "local_infile";
If you get:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile | OFF |
+---------------+-------+
Then set it to one typing:
mysql> set global local_infile = 1;
Specify the full path for your file. In my case:
mysql> load data infile "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/file.txt" into table test;
I used this function to detect if the element is visible in view port
Code:
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
$(window).scroll(function(){
var scrollTop = $(window).scrollTop(),
elementOffset = $('.for-scroll').offset().top,
distance = (elementOffset - scrollTop);
if(distance < vh){
console.log('in view');
}
else{
console.log('not in view');
}
});
Try Error.captureStackTrace(targetObject[, constructorOpt]).
const myObj = {};
function c() {
// pass
}
function b() {
Error.captureStackTrace(myObj)
c()
}
function a() {
b()
}
a()
console.log(myObj.stack)
The function a
and b
are captured in error stack and stored in myObj
.
Try __FILE__
and __LINE__
.
You might also find __DATE__
and __TIME__
useful.
Though unless you have to debug a program on the clientside and thus need to log these informations you should use normal debugging.
You can use this to delete ALL Files Inside a Folder and Subfolders:
DEL "C:\Folder\*.*" /S /Q
Or use this to Delete Certain File Types Only:
DEL "C:\Folder\*.mp4" /S /Q
DEL "C:\Folder\*.dat" /S /Q
You can do the entire conversion in one line, using the following code:
String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));
The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.
assuming you wanted the strings in between a string which is located 10 characters from the last character and you need only 3 characters.
Let's say StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"
In the above, I need to extract the "273"
that I will use in database query
//find the length of the string
int streamLen=StreamSelected.Length;
//now remove all characters except the last 10 characters
string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));
//extract the 3 characters using substring starting from index 0
//show Result is a TextBox (txtStreamSubs) with
txtStreamSubs.Text = streamLessTen.Substring(0, 3);
The fork(),vfork() and clone() all call the do_fork() to do the real work, but with different parameters.
asmlinkage int sys_fork(struct pt_regs regs)
{
return do_fork(SIGCHLD, regs.esp, ®s, 0);
}
asmlinkage int sys_clone(struct pt_regs regs)
{
unsigned long clone_flags;
unsigned long newsp;
clone_flags = regs.ebx;
newsp = regs.ecx;
if (!newsp)
newsp = regs.esp;
return do_fork(clone_flags, newsp, ®s, 0);
}
asmlinkage int sys_vfork(struct pt_regs regs)
{
return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, ®s, 0);
}
#define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */
#define CLONE_VM 0x00000100 /* set if VM shared between processes */
SIGCHLD means the child should send this signal to its father when exit.
For fork, the child and father has the independent VM page table, but since the efficiency, fork will not really copy any pages, it just set all the writeable pages to readonly for child process. So when child process want to write something on that page, an page exception happen and kernel will alloc a new page cloned from the old page with write permission. That's called "copy on write".
For vfork, the virtual memory is exactly by child and father---just because of that, father and child can't be awake concurrently since they will influence each other. So the father will sleep at the end of "do_fork()" and awake when child call exit() or execve() since then it will own new page table. Here is the code(in do_fork()) that the father sleep.
if ((clone_flags & CLONE_VFORK) && (retval > 0))
down(&sem);
return retval;
Here is the code(in mm_release() called by exit() and execve()) which awake the father.
up(tsk->p_opptr->vfork_sem);
For sys_clone(), it is more flexible since you can input any clone_flags to it. So pthread_create() call this system call with many clone_flags:
int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SYSVSEM);
Summary: the fork(),vfork() and clone() will create child processes with different mount of sharing resource with the father process. We also can say the vfork() and clone() can create threads(actually they are processes since they have independent task_struct) since they share the VM page table with father process.
You can follow this Google JavaScript Style Guide
In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
EDIT: See nice collection of JavaScript Style Guides And Beautifiers.
Modules go in site-packages
and executables go in your system's executable path. For your environment, this path is /usr/local/bin/
.
To avoid having to deal with this, simply use easy_install
, distribute
or pip
. These tools know which files need to go where.
The PHP way of doing this is simple:
$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;
But you can achieve a much nicer effect with this CSS:
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
Now, assuming the element has a fixed width, the browser will automatically break off and add the ...
for you.
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
Another option - start a debugger where the test fails.
Try running your tests with Testoob (it will run your unittest suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.
Here's a terminal session on windows:
C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
1 from unittest import TestCase
2 class MyTests(TestCase):
3 def test_foo(self):
4 x = 1
5 y = 2
6 -> self.assertEqual(x, y)
[EOF]
(Pdb)
One option is to store them as optional function variables:
struct MyAwesomeStruct {
var myWonderfulFunction : Optional<(Int) -> Int> = nil
}
let squareCalculator =
MyAwesomeStruct(myWonderfulFunction: { input in return input * input })
let thisShouldBeFour = squareCalculator.myWonderfulFunction!(2)
This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.
In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.
Now sure why it worked, but it did.
$SQL_Part="("
$i=0;
while ($i<length($cat)-1)
{
$SQL_Part+=$cat[i]+",";
}
$SQL_Part=$SQL_Part+$cat[$i+1]+")"
$SQL="SELECT * FROM products WHERE catid IN "+$SQL_Part;
It's more generic and will fit for any array!!
"validate Email"-Solution for Swift 4: Create this class:
import Foundation
public class EmailAddressValidator {
public init() {
}
public func validateEmailAddress(_ email: String) -> Bool {
let emailTest = NSPredicate(format: "SELF MATCHES %@", String.emailValidationRegEx)
return emailTest.evaluate(with: email)
}
}
private extension String {
static let emailValidationRegEx = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
"z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" +
"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
"9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
}
and use it like this:
let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("[email protected]")
Try this:
Create a batch file with the following:
echo off
cd\
:start
echo %time% >> c:\somedirectory\pinghostname.txt
ping pinghostname >> c:\somedirectory\pinghostname.txt
goto start
You can add your own options to the ping command based on your requirements. This doesn't put the time stamp on the same line as the ping, but it still gets you the info you need.
An even better way is to use fping, go here http://www.kwakkelflap.com/fping.html to download it.
Use the wc utility with the print the byte counts (-c
) option:
$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
13
You'll have to use the do not output the trailing newline (-n
) option for echo
. Otherwise, the newline character will also be counted.
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
My awk-less, sed-less, Perl-less, Python-less POSIX-compliant alternative:
find . -type f | rev | cut -d. -f1 | rev | tr '[:upper:]' '[:lower:]' | sort | uniq --count | sort -rn
The trick is that it reverses the line and cuts the extension at the beginning.
It also converts the extensions to lower case.
Example output:
3689 jpg
1036 png
610 mp4
90 webm
90 mkv
57 mov
12 avi
10 txt
3 zip
2 ogv
1 xcf
1 trashinfo
1 sh
1 m4v
1 jpeg
1 ini
1 gqv
1 gcs
1 dv
Read Ricardo's response first. This worked for me.
However, there exists a scenario where this won't work if the running container was kicked off using docker-compose. This is because docker-compose (I'm running docker 1.17) creates a new network. The way to address this scenario would be
docker network ls
Then append the following
docker run -d --name sqlplus --link db:db -p 1521:1521 sqlplus --net network_name
Give another go at force removing the brewed version of git
brew uninstall --force git
Then cleanup any older versions and clear the brew cache
brew cleanup -s git
Remove any dead symlinks
brew cleanup --prune-prefix
Then try reinstalling git
brew install git
If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix
directory (/usr/local
by default), you can simply rm -rf $(brew --prefix)
. Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh
I created this little function that replaces string on string (case-sensitive) with limit, without the need of Regexp. It works fine.
function str_replace_limit($search, $replace, $string, $limit = 1) {
$pos = strpos($string, $search);
if ($pos === false) {
return $string;
}
$searchLen = strlen($search);
for ($i = 0; $i < $limit; $i++) {
$string = substr_replace($string, $replace, $pos, $searchLen);
$pos = strpos($string, $search);
if ($pos === false) {
break;
}
}
return $string;
}
Example usage:
$search = 'foo';
$replace = 'bar';
$string = 'foo wizard makes foo brew for evil foo and jack';
$limit = 2;
$replaced = str_replace_limit($search, $replace, $string, $limit);
echo $replaced;
// bar wizard makes bar brew for evil foo and jack
The standard MIME type is application/pdf
. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.
MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.
The use of x-pdf
predates the standardization of the MIME type for PDF. MIME types in the x-
namespace are considered experimental, just as those in the vnd.
namespace are considered vendor-specific. x-pdf
might be used for compatibility with old software.
Window->Show View->Other…->Android->LogCat
byte[] a = new byte[50];
char [] cArray= System.Text.Encoding.ASCII.GetString(a).ToCharArray();
From the URL thedixon posted
http://bytes.com/topic/c-sharp/answers/250261-byte-char
You cannot ToCharArray the byte without converting it to a string first.
To quote Jon Skeet there
There's no need for the copying here - just use Encoding.GetChars. However, there's no guarantee that ASCII is going to be the appropriate encoding to use.
If think this will work:
if(sizeof($response->records)>0)
$role_arr = getRole($response->records);
newly defined proprties included too.
I don't know how you created the syntax as I neved used svg in font declaration, but Font Squirel has a really good tool to create a bullet proof syntax font-face from just one font.
One can also do this with a compact version of @TomAugspurger's answer, like so:
df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])
echo "echo "we are now going to work with ${ser}" " >> $servfile
Escape all " within quotes with \. Do this with variables like \$servicetest too:
echo "echo \"we are now going to work with \${ser}\" " >> $servfile
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile
If you only want to develop a single web service and have it hosted on many different endpoints (i.e. SOAP + REST, with XML, JSON, CSV, HTML outputes). You should also consider using ServiceStack which I've built for exactly this purpose where every service you develop is automatically available on on both SOAP and REST endpoints out-of-the-box without any configuration required.
The Hello World example shows how to create a simple with service with just (no config required):
public class Hello {
public string Name { get; set; }
}
public class HelloResponse {
public string Result { get; set; }
}
public class HelloService : IService
{
public object Any(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
No other configuration is required, and this service is immediately available with REST in:
It also comes in-built with a friendly HTML output (when called with a HTTP client that has Accept:text/html e.g a browser) so you're able to better visualize the output of your services.
Handling different REST verbs are also as trivial, here's a complete REST-service CRUD app in 1 page of C# (less than it would take to configure WCF ;):
Its mid 2019 and I faced this error after a few years of developing with Django. Baffled me for an entire night! It wasn't allowed host (which should throw a 400), everything else checked out, finally did some error logging only to discover that some missing / or messed up static files manifest (after collectstatic) were screwing with the setup. Long story short, for those who are stumped AND SO HAPPEN ARE USING WHITENOISE OR THE DJANGO STATICFILE BACKEND WITH CACHE (manifest static files) , maybe this is for you.
Make sure you setup everything (as I did for the whitenoise backend...django backends read on nonetheless) http://whitenoise.evans.io/en/stable/django.html
If error code 500 still shoots you down, take note on your settings.STATICFILES_STORAGE.
Set it to either (for whitenoise backend with compression)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
or (leave as django default)
STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage
All in all, THE PROBLEM seemed to come from the fact that this whitenoise cache + compression backend -->
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
or the django's own caching backend -->
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
...didnt quite work well for me, since my css was referencing some other sources which may be mixed up during collectstatic / backend caching. This issue is also potentially highlighted in http://whitenoise.evans.io/en/stable/django.html#storage-troubleshoot
Console applications will exit when the main function has finished running. A "return" will achieve this.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:
System.Environment.Exit(-1);
Have a look at this very detailled article: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime
To get the percentage of CPU used, all you need is some simple maths:
MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();
// Call an expensive task, or sleep if you are monitoring a remote process
long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();
long percent;
if (nanoAfter > nanoBefore)
percent = ((cpuAfter-cpuBefore)*100L)/
(nanoAfter-nanoBefore);
else percent = 0;
System.out.println("Cpu usage: "+percent+"%");
Note: You must import com.sun.management.OperatingSystemMXBean
and not java.lang.management.OperatingSystemMXBean
.
advise the current "best practice" around
Date
andCalendar
is it best to always favour
Calendar
overDate
Avoid these legacy classes entirely. Use java.time classes instead.
Instant
Date
)ZonedDateTime
GregorianCalendar
)OffsetDateTime
LocalDateTime
The Answer by Ortomala Lokni is right to suggest using the modern java.time classes rather than the troublesome old legacy date-time classes (Date
, Calendar
, etc.). But that Answer suggests the wrong class as equivalent (see my comment on that Answer).
The java.time classes are a vast improvement over the legacy date-time classes, night-and-day difference. The old classes are poorly-designed, confusing, and troublesome. You should avoid the old classes whenever possible. But when you need to convert to/from the old/new, you can do so by calling new methods add to the old classes.
For much more information on conversion, see my Answer and nifty diagram to another Question, Convert java.util.Date to what “java.time” type?.
Searching Stack Overflow gives many hundreds of example Questions and Answers on using java.time. But here is a quick synopsis.
Instant
Get the current moment with an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
ZonedDateTime
To see that same simultaneous moment through the lens of some particular region’s wall-clock time, apply a time zone (ZoneId
) to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone();
A time zone is a region’s history of changes in its offset-from-UTC. But sometimes you are given only an offset without the full zone. In that case, use the OffsetDateTime
class.
ZoneOffset offset = ZoneOffset.parse( "+05:30" );
OffsetDateTime odt = instant.atOffset( offset );
Use of a time zone is preferable over use of a mere offset.
LocalDateTime
The “Local” in the Local…
classes means any locality, not a particular locality. So the name can be counter-intuitive.
LocalDateTime
, LocalDate
, and LocalTime
purposely lack any information about offset or time zone. So they do not represent actual moments, they are not points on the timeline. When in doubt or in confusion, use ZonedDateTime
rather than LocalDateTime
. Search Stack Overflow for much more discussion.
Do not conflate date-time objects with strings that represent their value. You can parse a string to get a date-time object, and you can generate a string from a date-time object. But the string is never the date-time itself.
Learn about standard ISO 8601 formats, used by default in the java.time classes.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
true and false operators are really weird.
More comprehensive example can be found here.
Edit: There is related SO question What’s the false operator in C# good for?
To render more than one whitespace on most web browsers use
instead of normal white spaces.
echo "<p>Hello punt"; // This will render as Hello Punt (with 4 white spaces)
echo "<p> Hello punt"; // This will render as Hello punt (with one space)
For showing data in raw format (with exact number of spaces and "enters") use HTML <pre>
tag.
echo "<pre>Hello punt</pre>"; //Will render exactly as written here (8 white spaces)
Or you can use some CSS to style current block, not to break text or strip spaces (I don't know, but this one)
Any way you do the output will be the same but the browser itself strips double white spaces and renders as one.
For starters ignore all answers with tell you to use $watch. Angular works off of a listener already. I guarantee you that you are complicating things by merely thinking in this direction.
Ignore all answers that tell you to user $timeout. You cannot know how long the page will take to load, therefore this is not the best solution.
You only need to know when the page is done rendering.
<div ng-app='myApp'>
<div ng-controller="testctrl">
<label>{{total}}</label>
<table>
<tr ng-repeat="item in items track by $index;" ng-init="end($index);">
<td>{{item.number}}</td>
</tr>
</table>
</div>
var app = angular.module('myApp', ["testctrl"]);
var controllers = angular.module("testctrl", []);
controllers.controller("testctrl", function($scope) {
$scope.items = [{"number":"one"},{"number":"two"},{"number":"three"}];
$scope.end = function(index){
if(index == $scope.items.length -1
&& typeof $scope.endThis == 'undefined'){
/// DO STUFF HERE
$scope.total = index + 1;
$scop.endThis = true;
}
}
});
Track the ng-repeat by $index and when the length of array equals the index stop the loop and do your logic.
In my case i have just put the Class MyprojectApplication in a package(com.example.start) with the same level of model, controller,service packages.
In case you actually mean what you seem to ask, I'll provide this alternative answer.
You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict
does. This will do so:
class DictWithDefault(dict):
def __init__(self, default, **kwargs):
self.default = default
super(DictWithDefault, self).__init__(**kwargs)
def __getitem__(self, key):
if key in self:
return super(DictWithDefault, self).__getitem__(key)
return self.default
Use like this:
d = DictWIthDefault(99, x=5, y=3)
print d["x"] # 5
print d[42] # 99
42 in d # False
d[42] = 3
42 in d # True
Alternatively, you can use a standard dict
like this:
d = {3: 9, 4: 2}
default = 99
print d.get(3, default) # 9
print d.get(42, default) # 99
This will prompt for computer name and join to domain then restart.
$computerName = Get-WmiObject Win32_ComputerSystem
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Desired Computer Name ")
$computername.rename("$name")
Add-Computer -DomainName [domainname] -Credential [user\domain] -Verbose
Restart-Computer
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
In some instances, using fall-throughs is an act of laziness on the part of the programmer - they could use a series of || statements, for example, but instead use a series of 'catch-all' switch cases.
That being said, I've found them to be especially helpful when I know that eventually I'm going to need the options anyway (for example in a menu response), but have not yet implemented all the choices. Likewise, if you're doing a fall-through for both 'a' and 'A', I find it substantially cleaner to use the switch fall-through than a compound if statement.
It's probably a matter of style and how the programmers think, but I'm not generally fond of removing components of a language in the name of 'safety' - which is why I tend towards C and its variants/descendants more than, say, Java. I like being able to monkey-around with pointers and the like, even when I have no "reason" to.
$.getJSON(url,function(json){
if ( json.length == 0 )
{
console.log("NO !")
}
});
If you want to convert from char to int, why not think about unicode number?
SELECT UNICODE(';') -- 59
This way you can convert any char to int without any error. Cheers.
Service
startService()
Thread
Main Thread
stopSelf()
or stopService()
IntentService
Handler
or BroadcastReceiver
Intent
Main Thread
Here is how you can get the keyboard inputs:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");
name = scanner.next(); // Get what the user types.
web2py includes support for easily building RESTful API's, described here and here (video). In particular, look at parse_as_rest
, which lets you define URL patterns that map request args to database queries; and smart_query
, which enables you to pass arbitrary natural language queries in the URL.
Try writing all the errors to a file.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
Something like that.
You probably want to flatten all of the lists in Values
into a single list:
List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();
I just use an array to achieved multiple requests, hope it helps someone. (Kotlin)
// got all permission
private fun requestPermission(){
var mIndex: Int = -1
var requestList: Array<String> = Array(10, { "" } )
// phone call Permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.CALL_PHONE
}
// SMS Permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.SEND_SMS
}
// Access photos Permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.READ_EXTERNAL_STORAGE
}
// Location Permission
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.ACCESS_FINE_LOCATION
}
if(mIndex != -1){
ActivityCompat.requestPermissions(this, requestList, PERMISSIONS_REQUEST_ALL)
}
}
// permission response
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSIONS_REQUEST_ALL -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Phone Call permission accept.")
}
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SMS permission accept.")
}
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SMS permission accept.")
}
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Location permission accept.")
}
} else {
Toast.makeText(mContext, "Permission Failed!", Toast.LENGTH_LONG).show()
}
return
}
}
}
Convert the series to a dataframe and transpose it, then append normally.
srs = srs.to_frame().T
df = df.append(srs)
Directly use this: ondragstart="return false;"
in your image tag.
<img src="http://image-example.png" ondragstart="return false;"/>
If you have multiple images, wrapped on a <div>
tag:
<div ondragstart="return false;">
<img src="image1.png"/>
<img scr="image2.png"/>
</div>
Works in all major browsers.
Just sort by whatever (mpg for example, question is not clear on this)
mt <- mtcars[order(mtcars$mpg), ]
then use the by function to get the top n rows in each group
d <- by(mt, mt["cyl"], head, n=4)
If you want the result to be a data.frame:
Reduce(rbind, d)
Edit: Handling ties is more difficult, but if all ties are desired:
by(mt, mt["cyl"], function(x) x[rank(x$mpg) %in% sort(unique(rank(x$mpg)))[1:4], ])
Another approach is to break ties based on some other information, e.g.,
mt <- mtcars[order(mtcars$mpg, mtcars$hp), ]
by(mt, mt["cyl"], head, n=4)
Thanks to @Gerben's post came to know there are two events show.bs.tab (before the tab is shown) and shown.bs.tab (after the tab is shown) as explained in the docs - Bootstrap Tab usage
An additional solution if we're only interested in a specific tab, and maybe add separate functions without having to add an if - else block in one function, is to use the a href selector (maybe along with additional selectors if required)
$("a[href='#tab_target_id']").on('shown.bs.tab', function(e) {
console.log('shown - after the tab has been shown');
});
// or even this one if we want the earlier event
$("a[href='#tab_target_id']").on('show.bs.tab', function(e) {
console.log('show - before the new tab has been shown');
});
In this specific case, the ToString() will return the name of the object retruned by the SelectedCell Property.( a collection of the currently selected cells).
This behavior occurs when an object has no specific implenetation for the ToString() methods.
in our case, all you have to do is to iterate the collection of the cells and to accumulate its values to a string. then push this string to the TextBox.
have a look here how to implement the iteration:
Addition after very useful comment of mhand at the end
Although most solutions might work, I think they are not very efficiently. Suppose if you only want the first few items of the first few chunks. Then you wouldn't want to iterate over all (zillion) items in your sequence.
The following will at utmost enumerate twice: once for the Take and once for the Skip. It won't enumerate over any more elements than you will use:
public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>
(this IEnumerable<TSource> source, int chunkSize)
{
while (source.Any()) // while there are elements left
{ // still something to chunk:
yield return source.Take(chunkSize); // return a chunk of chunkSize
source = source.Skip(chunkSize); // skip the returned chunk
}
}
Suppose you divide your source into chunks of chunkSize
. You enumerate only the first N chunks. From every enumerated chunk you'll only enumerate the first M elements.
While(source.Any())
{
...
}
the Any will get the Enumerator, do 1 MoveNext() and returns the returned value after Disposing the Enumerator. This will be done N times
yield return source.Take(chunkSize);
According to the reference source this will do something like:
public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count)
{
return TakeIterator<TSource>(source, count);
}
static IEnumerable<TSource> TakeIterator<TSource>(IEnumerable<TSource> source, int count)
{
foreach (TSource element in source)
{
yield return element;
if (--count == 0) break;
}
}
This doesn't do a lot until you start enumerating over the fetched Chunk. If you fetch several Chunks, but decide not to enumerate over the first Chunk, the foreach is not executed, as your debugger will show you.
If you decide to take the first M elements of the first chunk then the yield return is executed exactly M times. This means:
After the first chunk has been yield returned, we skip this first Chunk:
source = source.Skip(chunkSize);
Once again: we'll take a look at reference source to find the skipiterator
static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
while (count > 0 && e.MoveNext()) count--;
if (count <= 0)
{
while (e.MoveNext()) yield return e.Current;
}
}
}
As you see, the SkipIterator
calls MoveNext()
once for every element in the Chunk. It doesn't call Current
.
So per Chunk we see that the following is done:
Take():
If the content is enumerated: GetEnumerator(), one MoveNext and one Current per enumerated item, Dispose enumerator;
Skip(): for every chunk that is enumerated (NOT the contents of the chunk): GetEnumerator(), MoveNext() chunkSize times, no Current! Dispose enumerator
If you look at what happens with the enumerator, you'll see that there are a lot of calls to MoveNext(), and only calls to Current
for the TSource items you actually decide to access.
If you take N Chunks of size chunkSize, then calls to MoveNext()
If you decide to enumerate only the first M elements of every fetched chunk, then you need to call MoveNext M times per enumerated Chunk.
The total
MoveNext calls: N + N*M + N*chunkSize
Current calls: N*M; (only the items you really access)
So if you decide to enumerate all elements of all chunks:
MoveNext: numberOfChunks + all elements + all elements = about twice the sequence
Current: every item is accessed exactly once
Whether MoveNext is a lot of work or not, depends on the type of source sequence. For lists and arrays it is a simple index increment, with maybe an out of range check.
But if your IEnumerable is the result of a database query, make sure that the data is really materialized on your computer, otherwise the data will be fetched several times. DbContext and Dapper will properly transfer the data to local process before it can be accessed. If you enumerate the same sequence several times it is not fetched several times. Dapper returns an object that is a List, DbContext remembers that the data is already fetched.
It depends on your Repository whether it is wise to call AsEnumerable() or ToLists() before you start to divide the items in Chunks
I would get the part before and after what you want to replace and put them either side.
Like:
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
var matches = str.match(regex);
var result = matches[1] + "1" + matches[2];
// With ES6:
var result = `${matches[1]}1${matches[2]}`;
lenkan's answer is a great solution.
<div>
{{ beep: <div>Beep</div>,
boop: <div>Boop</div>
}[greeting]}
</div>
If you need a default value, then you can even do
<div>
{{ beep: <div>Beep</div>,
boop: <div>Boop</div>
}[greeting] || <div>Hello world</div>}
</div>
Alternatively, if that doesn't read well to you, then you can do something like
<div>
{
rswitch(greeting, {
beep: <div>Beep</div>,
boop: <div>Boop</div>,
default: <div>Hello world</div>
})
}
</div>
with
function rswitch (param, cases) {
if (cases[param]) {
return cases[param]
} else {
return cases.default
}
}
You can define a generic function like this:
@SuppressWarnings("unchecked")
public static <T> List<T> newFixedSizeList(int size) {
return (List<T>)Arrays.asList(new Object[size]);
}
And
List<String> s = newFixedSizeList(3); // All elements are initialized to null
s.set(0, "zero");
s.add("three"); // throws java.lang.UnsupportedOperationException
Arrays in java are objects, and all objects are passed by reference. In order to really "copy" an array, instead of creating another name for an array, you have to go and create a new array and copy over all the values. Note that System.arrayCopy will copy 1-dimensional arrays fully, but NOT 2-dimensional arrays. The reason is that a 2D array is in fact a 1D array of 1D arrays, and arrayCopy copies over pointers to the same internal 1D arrays.
Technically, this is the same answer as @Sujee. It also depends on your version of Oracle as to whether it works. (I think this syntax was introduced in Oracle 12??)
SELECT *
FROM table
ORDER BY value DESC, date_column ASC
FETCH first 1 rows only;
As I say, if you look under the bonnet, I think this code is unpacked internally by the Oracle Optimizer to read like @Sujee's. However, I'm a sucker for pretty coding, and nesting select
statements without a good reason does not qualify as beautiful!! :-P
There is more than one way to define "memory leak". In particular, there are two primary definitions of "memory leak" that are in common usage among programmers.
The first commonly used definition of "memory leak" is, "Memory was allocated and was not subsequently freed before the program terminated." However, many programmers (rightly) argue that certain types of memory leaks that fit this definition don't actually pose any sort of problem, and therefore should not be considered true "memory leaks".
An arguably stricter (and more useful) definition of "memory leak" is, "Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block." In other words, you cannot free memory that you no longer have any pointers to. Such memory is therefore a "memory leak". Valgrind uses this stricter definition of the term "memory leak". This is the type of leak which can potentially cause significant heap depletion, especially for long lived processes.
The "still reachable" category within Valgrind's leak report refers to allocations that fit only the first definition of "memory leak". These blocks were not freed, but they could have been freed (if the programmer had wanted to) because the program still was keeping track of pointers to those memory blocks.
In general, there is no need to worry about "still reachable" blocks. They don't pose the sort of problem that true memory leaks can cause. For instance, there is normally no potential for heap exhaustion from "still reachable" blocks. This is because these blocks are usually one-time allocations, references to which are kept throughout the duration of the process's lifetime. While you could go through and ensure that your program frees all allocated memory, there is usually no practical benefit from doing so since the operating system will reclaim all of the process's memory after the process terminates, anyway. Contrast this with true memory leaks which, if left unfixed, could cause a process to run out of memory if left running long enough, or will simply cause a process to consume far more memory than is necessary.
Probably the only time it is useful to ensure that all allocations have matching "frees" is if your leak detection tools cannot tell which blocks are "still reachable" (but Valgrind can do this) or if your operating system doesn't reclaim all of a terminating process's memory (all platforms which Valgrind has been ported to do this).
Just a cleaned up version of clemo's code - works in Access, which doesn't have the Application.Wait function.
Public Sub Pause(sngSecs As Single)
Dim sngEnd As Single
sngEnd = Timer + sngSecs
While Timer < sngEnd
DoEvents
Wend
End Sub
Public Sub TestPause()
Pause 1
MsgBox "done"
End Sub
I think a very simple solution could be following:
DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE ','+@Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),tableid)+',%';
While @roufamatic did show use of the arguments keyword and @Ken showed a great example of an object for usage I feel neither truly addressed what is going on in this instance and may confuse future readers or instill a bad practice as not explicitly stating a function/method is intended to take a variable amount of arguments/parameters.
function varyArg () {
return arguments[0] + arguments[1];
}
When another developer is looking through your code is it very easy to assume this function does not take parameters. Especially if that developer is not privy to the arguments keyword. Because of this it is a good idea to follow a style guideline and be consistent. I will be using Google's for all examples.
Let's explicitly state the same function has variable parameters:
function varyArg (var_args) {
return arguments[0] + arguments[1];
}
There may be times when an object is needed as it is the only approved and considered best practice method of an data map. Associative arrays are frowned upon and discouraged.
SIDENOTE: The arguments keyword actually returns back an object using numbers as the key. The prototypal inheritance is also the object family. See end of answer for proper array usage in JS
In this case we can explicitly state this also. Note: this naming convention is not provided by Google but is an example of explicit declaration of a param's type. This is important if you are looking to create a more strict typed pattern in your code.
function varyArg (args_obj) {
return args_obj.name+" "+args_obj.weight;
}
varyArg({name: "Brian", weight: 150});
This depends on your function's and program's needs. If for instance you are simply looking to return a value base on an iterative process across all arguments passed then most certainly stick with the arguments keyword. If you need definition to your arguments and mapping of the data then the object method is the way to go. Let's look at two examples and then we're done!
function sumOfAll (var_args) {
return arguments.reduce(function(a, b) {
return a + b;
}, 0);
}
sumOfAll(1,2,3); // returns 6
function myObjArgs(args_obj) {
// MAKE SURE ARGUMENT IS AN OBJECT OR ELSE RETURN
if (typeof args_obj !== "object") {
return "Arguments passed must be in object form!";
}
return "Hello "+args_obj.name+" I see you're "+args_obj.age+" years old.";
}
myObjArgs({name: "Brian", age: 31}); // returns 'Hello Brian I see you're 31 years old
As mentioned up top of the answer the arguments keyword actually returns an object. Because of this any method you want to use for an array will have to be called. An example of this:
Array.prototype.map.call(arguments, function (val, idx, arr) {});
To avoid this use the rest parameter:
function varyArgArr (...var_args) {
return var_args.sort();
}
varyArgArr(5,1,3); // returns 1, 3, 5
With {} you assign the elements as they are declared; the rest is initialized with 0.
If there is no = {}
to initalize, the content is undefined.
When you want to create a new line or wrap in your TextArea you have to add \n (newline) after the text.
TextArea t = new TextArea();
t.setText("insert text when you want a new line add \nThen more text....);
setBounds();
setFont();
add(t);
This is the only way I was able to do it, maybe there is a simpler way but I havent discovered that yet.
You can use iText for do such things
//iText imports
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
for example:
try {
PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
System.out.println(str);
reader.close();
} catch (Exception e) {
System.out.println(e);
}
another one
try {
PdfReader reader = new PdfReader("c:/temp/test.pdf");
System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
String page = PdfTextExtractor.getTextFromPage(reader, 2);
System.out.println("Page Content:\n\n"+page+"\n\n");
System.out.println("Is this document tampered: "+reader.isTampered());
System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
e.printStackTrace();
}
the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.
PROBLEM :-
Sometimes, Localhost may not get resolved. So it tends to return an output as seen below :
# curl -XGET localhost:9200/_cluster/health?pretty
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
# curl -XGET localhost:9200/_cat/indices
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
SOLUTION :-
Guess, this error is most probably returned by Local Squid deployed in the server.
So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.
I know that this is a super-old post. Assuming that you are calling into your application, here is an idea that has worked for me:
If you don't need total control, you could use an update panel which would do this for you.
You have to cast one (or both) of the arguments to the division operator to double
:
double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);
Since you are performing the same calculation twice I'd recommend refactoring your code:
double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;
This works in the same way, but now there is an implicit cast to double. This conversion from int
to double
is an example of a widening primitive conversion.
If you also need to disable the drop-down (not to hide the text) then set the lengthChange
option to false
$('#datatable').dataTable( {
"lengthChange": false
} );
Works for DataTables 1.10+
Read more in the official documentation
Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".
Try Project Euler:
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
The problem is:
Add all the natural numbers below 1000 that are multiples of 3 or 5.
This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.
Here's a complete answer with Objective C and Swift:
1) Create an IBAction
unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.
// Objective C
- (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {
}
// Swift
@IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {
}
2) On the source view controller (the controller you're segueing from), ^ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.
3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.
4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.
// Objective C
[self performSegueWithIdentifier:@"unwindToContainerVC" sender:self];
// Swift
self.performSegueWithIdentifier("unwindToContainerVC", sender: self)
NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.