When I did sudo /etc/init.d/php-fpm start
I got the following error:
Starting php-fpm: [28-Mar-2013 16:18:16] ERROR: [pool www] cannot get uid for user 'apache'
I guess /etc/php-fpm.d/www.conf
needs to know the user that the webserver is running as and assumes it's apache when, for nginx, it's actually nginx, and needs to be changed.
A little late to the party, but since I was looking for it (and I might need to find it again sometime), here's what I did to include version, company name, etc. into my C++ DLL under VS2013 Express:
Hope this helps!
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
The [new-ish at the time of writing in 2017] Fetch API is intended to make GET requests easy, but it is able to POST as well.
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
If you are as lazy as me (or just prefer a shortcut/helper):
window.post = function(url, data) {
return fetch(url, {method: "POST", body: JSON.stringify(data)});
}
// ...
post("post/data/here", {element: "osmium"});
Nowadays with HTML5, it's pretty simple:
<input type="search" placeholder="Search..."/>
Most modern browsers will automatically render a usable clear button in the field by default.
(If you use Bootstrap, you'll have to add an override to your css file to make it show)
input[type=search]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
Safari/WebKit browsers can also provide extra features when using type="search"
, like results=5
and autosave="..."
, but they also override many of your styles (e.g. height, borders) . To prevent those overrides, while still retaining functionality like the X button, you can add this to your css:
input[type=search] {
-webkit-appearance: none;
}
See css-tricks.com for more info about the features provided by type="search"
.
The following works fine:
backgroundColor: 'rgba(52, 52, 52, alpha)'
You could also try:
backgroundColor: 'transparent'
You can do this in CSS:
a.menu_links {
cursor: pointer;
}
This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href
attribute in there (it's missing from your example).
You could do it in one document if you had a conditional based on params sent over. Eg:
if (isset($_GET['secret_param'])) {
<run script>
} else {
<display button>
}
I think the best way though is to have two files.
I caught this error a few days ago.
IN my case it was because I was using a Transaction on a Singleton.
.Net does not work well with Singleton as stated above.
My solution was this:
public class DbHelper : DbHelperCore
{
public DbHelper()
{
Connection = null;
Transaction = null;
}
public static DbHelper instance
{
get
{
if (HttpContext.Current is null)
return new DbHelper();
else if (HttpContext.Current.Items["dbh"] == null)
HttpContext.Current.Items["dbh"] = new DbHelper();
return (DbHelper)HttpContext.Current.Items["dbh"];
}
}
public override void BeginTransaction()
{
Connection = new SqlConnection(Entity.Connection.getCon);
if (Connection.State == System.Data.ConnectionState.Closed)
Connection.Open();
Transaction = Connection.BeginTransaction();
}
}
I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class
In C# the code looks like:
Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);
or
var dictionary = new Dictionary<string, int> {
{"sample1", 1},
{"sample2", 2}
};
In JavaScript:
var dictionary = {
"sample1": 1,
"sample2": 2
}
A C# dictionary object contains useful methods, like dictionary.ContainsKey()
In JavaScript, we could use the hasOwnProperty
like:
if (dictionary.hasOwnProperty("sample1"))
console.log("sample1 key found and its value is"+ dictionary["sample1"]);
how did you install easy_install/pip? make sure that you installed it for the upgraded version of python. what could have happened here is that the old (default) python install might be linked to your pip install. you might wanna try running the default version and importing the newly installed modules.
This is called a correlated update
UPDATE table1 t1
SET (name, desc) = (SELECT t2.name, t2.desc
FROM table2 t2
WHERE t1.id = t2.id)
WHERE EXISTS (
SELECT 1
FROM table2 t2
WHERE t1.id = t2.id )
Assuming the join results in a key-preserved view, you could also
UPDATE (SELECT t1.id,
t1.name name1,
t1.desc desc1,
t2.name name2,
t2.desc desc2
FROM table1 t1,
table2 t2
WHERE t1.id = t2.id)
SET name1 = name2,
desc1 = desc2
Another way to detect if arguments were passed to the script:
((!$#)) && echo No arguments supplied!
Note that (( expr ))
causes the expression to be evaluated as per rules of Shell Arithmetic.
In order to exit in the absence of any arguments, one can say:
((!$#)) && echo No arguments supplied! && exit 1
Another (analogous) way to say the above would be:
let $# || echo No arguments supplied
let $# || { echo No arguments supplied; exit 1; } # Exit if no arguments!
help let
says:
let: let arg [arg ...]
Evaluate arithmetic expressions. ... Exit Status: If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.
While personally I would be preferring !str.isBlank()
, as others already suggested (or str -> !str.isBlank()
as a Predicate), a more modern and efficient version of the str.trim()
approach mentioned above, would be using str.strip()
- considering nulls as "whitespace":
if (str != null && str.strip().length() > 0) {...}
For example as Predicate, for use with streams, e. g. in a unit test:
@Test
public void anyNonEmptyStrippedTest() {
String[] strings = null;
Predicate<String> isNonEmptyStripped = str -> str != null && str.strip().length() > 0;
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).noneMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r" };
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).anyMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r", "test" };
}
Use date() function to get the desired date
<?php
// set default timezone
date_default_timezone_set('UTC');
//define date and time
$strtotime = 1307595105;
// output
echo date('d M Y H:i:s',$strtotime);
// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format
?>
Recommended online tool for strtotime to date conversion:
I have strong working solution.
in layoutSubviews:
_title.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 0)
_title.sizeToFit()
_title.frame.size = _title.bounds.size
in text setter:
_title.text = newValue
setNeedsLayout()
UPD. of course with this UILabel settings:
_title.lineBreakMode = .ByWordWrapping
_title.numberOfLines = 0
f = open('test.txt','r')
for line in f.xreadlines():
print line
f.close()
You should be referencing Selected
not ids.Contains
as the last line.
I just realized this is a formatting issue, from the OP. Regardless you should be referencing the value in Selected. I recommend adding some Console.WriteLine calls to see exactly what is being printed out on each line and also what each value is.
After your update: ids is an empty list, how is this not throwing a NullReferenceException? As it was never initialized in that code block
Use window.open()
. It's pretty straightforward !
In your component.html
file-
<a (click)="goToLink("www.example.com")">page link</a>
In your component.ts
file-
goToLink(url: string){
window.open(url, "_blank");
}
Taken from: http://www.w3.org/Style/Examples/007/units:
The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.
em
is basically CSS property for font sizes.
From the documentation:
Paths associated with the default
provider
are generally interoperable with thejava.io.File
class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented byjava.io.File
. ThetoPath
method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as thejava.io.File
object. In addition, thetoFile
method is useful to construct aFile
from theString
representation of aPath
.
(emphasis mine)
So, for toFile
:
Returns a
File
object representing this path.
And toPath
:
Returns a
java.nio.file.Path
object constructed from the this abstract path.
What you ask is quite complex topic - not easily answerable. Other answers are ok, but they covered just a small part of all the things you need to do.
As seen in comments, it is not possible to fix hardware problems 100%, however it is possible with high probabily to reduce or catch them using various techniques.
If I was you, I would create the software of the highest Safety integrity level level (SIL-4). Get the IEC 61513 document (for the nuclear industry) and follow it.
this is work for me ,but you should merge remote repository files to the local files:
git init
git remote add origin url-to-git
git branch --set-upstream-to=origin/master master
git fetch
git status
I found a solution that doesn't need to access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.
The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.
If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.
This function downsample to half at a time until reaching the desired size:
function resize_image( src, dst, type, quality ) {
var tmp = new Image(),
canvas, context, cW, cH;
type = type || 'image/jpeg';
quality = quality || 0.92;
cW = src.naturalWidth;
cH = src.naturalHeight;
tmp.src = src.src;
tmp.onload = function() {
canvas = document.createElement( 'canvas' );
cW /= 2;
cH /= 2;
if ( cW < src.width ) cW = src.width;
if ( cH < src.height ) cH = src.height;
canvas.width = cW;
canvas.height = cH;
context = canvas.getContext( '2d' );
context.drawImage( tmp, 0, 0, cW, cH );
dst.src = canvas.toDataURL( type, quality );
if ( cW <= src.width || cH <= src.height )
return;
tmp.src = dst.src;
}
}
// The images sent as parameters can be in the DOM or be image objects
resize_image( $( '#original' )[0], $( '#smaller' )[0] );
As in @deinonychusaur's reply, but even more compact:
In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)
To tell eclipse to use JDK, you have to follow the below steps.
After completing the above steps, you are done now and eclipse will start using the selected JDK for compilation.
I have used methods described above. Now I am using the method which is a way similiar but more simple to me.
Like this:
<img src="icon.jpg" width="324" height="324">
<p align="center">
<img src="screen1.png" width="256" height="455">
<img src="screen2.png" width="256" height="455">
<img src="screen3.png" width="256" height="455">
</p>
On above example I have used paragraph to align images side by side. If you are going to use single image just use the code as below
<img src="icon.jpg" width="324" height="324">
Have a nice day!
NOLOCK is often exploited as a magic way to speed up database reads, but I try to avoid using it whever possible.
The result set can contain rows that have not yet been committed, that are often later rolled back.
An error or Result set can be empty, be missing rows or display the same row multiple times.
This is because other transactions are moving data at the same time you're reading it.
READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.
If you pass in a date range, you can use this:
def last_day_of_month(any_days):
res = []
for any_day in any_days:
nday = any_day.days_in_month -any_day.day
res.append(any_day + timedelta(days=nday))
return res
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
HTML--
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css--
.active{
background:red;
}
button.btn:active{
background:red;
}
jQuery--
jQuery("#my_styles .btn").click(function(){
jQuery("#my_styles .btn").removeClass('active');
jQuery(this).toggleClass('active');
});
view the live demo on jsfiddle
jQuery('#from_date').on('change', function(){
var date = $(this).val();
jQuery('#to_date').datetimepicker({minDate: date});
});
Use this Custom ImageView in Xml
public class RoundedCornerImageView extends ImageView {
public RoundedCornerImageView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth(), h = getHeight();
Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
Bitmap finalBitmap;
if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
false);
else
finalBitmap = bitmap;
Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
final RectF rectf = new RectF(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
//Set Required Radius Here
int yourRadius = 7;
canvas.drawRoundRect(rectf, yourRadius, yourRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(finalBitmap, rect, rect, paint);
return output;
}
}
var_dump(extension_loaded('curl'));
Basically you have two options
scale_x_continuous(limits = c(-5000, 5000))
or
coord_cartesian(xlim = c(-5000, 5000))
Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.
You can also use the shorthand function xlim
(or ylim
), which like the first option removes data points outside of the given range:
+ xlim(-5000, 5000)
For more information check the description of coord_cartesian
.
The RStudio cheatsheet for ggplot2
makes this quite clear visually. Here is a small section of that cheatsheet:
Distributed under CC BY.
Just convert it by this line :
for the new table :
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
for Existing Table:
Alter ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Source :
https://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html
I can also verify the above solution except I had to change in
**..\server\<server profile>\conf\props\jmx-console-users.properties**
button1, button2 and button3 have same even handler
private void button1_Click(Object sender, EventArgs e)
{
Button btnSender = (Button)sender;
if (btnSender == button1 || btnSender == button2)
{
//some code here
}
else if (btnSender == button3)
//some code here
}
Tried all the above But for me it was solved by
npm start
It’s so simple you’ll kick yourself: just press Enter!
<a href="#" title='Tool
Tip
On
New
Line'>link with tip</a>
_x000D_
The process for timing out an operations is described in the documentation for signal.
The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.
Note that this will only work on UNIX.
Here's an implementation that creates a decorator (save the following code as timeout.py
).
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
This creates a decorator called @timeout
that can be applied to any long running functions.
So, in your application code, you can use the decorator like so:
from timeout import timeout
# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
...
# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
...
# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
...
I've solved this problem this way. In IntelliJ all of your packages should be in a sub package which is the sub package of main/java. For example I've put all of my packages under src/main/java/com.misisol.watchStore/ and spring could find my beans then after.
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
You can use this ShellScript to install (most) of it's dependencies, clone, build, compile and get all the necessary files into ../src/includes
folder:
https://github.com/node-tensorflow/node-tensorflow/blob/master/tools/install.sh
try
hive --outputformat==csv2 -e "select * from YOUR_TABLE";
This worked for me
my hive version is "Hive 3.1.0.3.1.0.0-78"
string s = "hello";
char c = s[1];
// now c == 'e'
See also Substring
, to return more than one character.
If you are trying to block all interaction with the page you might want to look at the jQuery BlockUI Plugin
You would use the focus
and blur
events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
Click to view Example Code Showing it working (JSFiddle)
jww is right — you're referencing the wrong intermediate certificate.
As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt
Filename:
__file__
# or
sys.argv[0]
Line:
inspect.currentframe().f_lineno
(not inspect.currentframe().f_back.f_lineno
as mentioned above)
The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123
You are looking for git merge-base
. Usage:
$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.
Dim val1 As Integer, val2 As Integer, i As Integer
For i = 1 To 333
Sheets("Feuil2").Activate
ActiveSheet.Cells(i, 1).Select
val1 = Cells(i, 1).Value
val2 = Cells(i, 2).Value
Sheets("Classeur2.csv").Select
Cells(val1, val2).Select
ActiveCell.FormulaR1C1 = "1"
Next i
The answer varies depending on what storage engine you're using. The ideal scenario is if you're using InnoDB. In that case you can use the --single-transaction
flag, which will give you a coherent snapshot of the database at the time that the dump begins.
import json
def writeToFile(logData, fileName, openOption="w"):
file = open(fileName, openOption)
file.write(json.dumps(json.loads(logData), indent=4))
file.close()
You need to load it from resource stream.
Bitmap bmp = new Bitmap(
System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.myimage.png"));
If you want to know all resource names in your assembly, go with:
string[] all = System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceNames();
foreach (string one in all) {
MessageBox.Show(one);
}
ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>
, where binddn
is the DN of the person whose credentials you are authenticating.
On success (i.e., valid credentials), you get Result: Success (0)
. On failure, you get ldap_bind: Invalid credentials (49)
.
A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.
Try disabling all non-essential modules (in php.ini
), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.
If that doesn't help, you should report a php bug.
There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.
HTML Code:
<div class="text">Lorem ipsum.</div>
JQuery Code:
$(document).ready(function(){
var DivWidth = $(".text").width();
$(".left").click(function(){
$(".text").animate({
width: 0
});
});
$(".right").click(function(){
$(".text").animate({
width: DivWidth
});
});
});
You can see an example here: How to slide toggle a DIV from Left to Right?
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
Try putting this in your .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^sub.domain.com
RewriteRule ^(.*)$ /subdomains/sub/$1 [L,NC,QSA]
For a more general rule (that works with any subdomain, not just sub
) replace the last two lines with this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com
RewriteRule ^(.*)$ subdomains/%1/$1 [L,NC,QSA]
You've got the syntax right:
WITH AuthorRating(AuthorName, AuthorRating) AS
SELECT aname AS AuthorName,
AVG(quantity) AS AuthorRating
FROM Book
GROUP By Book.aname
However, as others have mentioned, MySQL does not support this command. WITH was added in SQL:1999; the newest version of the SQL standard is SQL:2008. You can find some more information about databases that support SQL:1999's various features on Wikipedia.
MySQL has traditionally lagged a bit in support for the SQL standard, whereas commercial databases like Oracle, SQL Server (recently), and DB2 have followed them a bit more closely. PostgreSQL is typically pretty standards compliant as well.
You may want to look at MySQL's roadmap; I'm not completely sure when this feature might be supported, but it's great for creating readable roll-up queries.
Use shorthand property for the background property and type the folder name where thje image had been located.
.btn-pTool{
margin:0;
padding:0;
background:url("../folder name/slide_button.png") no-repeat;
}
.btn-pToolName{
text-align: center;
width: 26px;
height: 190px;
display: block;
color: #fff;
text-decoration: none;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
line-height: 32px;
}
Here is a simple snippet that sorts a javascript representation of a Json.
function isObject(v) {
return '[object Object]' === Object.prototype.toString.call(v);
};
JSON.sort = function(o) {
if (Array.isArray(o)) {
return o.sort().map(JSON.sort);
} else if (isObject(o)) {
return Object
.keys(o)
.sort()
.reduce(function(a, k) {
a[k] = JSON.sort(o[k]);
return a;
}, {});
}
return o;
}
It can be used as follows:
JSON.sort({
c: {
c3: null,
c1: undefined,
c2: [3, 2, 1, 0],
},
a: 0,
b: 'Fun'
});
That will output:
{
a: 0,
b: 'Fun',
c: {
c2: [3, 2, 1, 0],
c3: null
}
}
From the @param wiki page:
If a parameter is expected to have a particular property, you can document that immediately after the @param tag for that parameter, like so:
/**
* @param userInfo Information about the user.
* @param userInfo.name The name of the user.
* @param userInfo.email The email of the user.
*/
function logIn(userInfo) {
doLogIn(userInfo.name, userInfo.email);
}
There used to be a @config tag which immediately followed the corresponding @param, but it appears to have been deprecated (example here).
If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:
var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }
And then access them using JavaScript's associative array syntax:
alert(table['one']); // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10
this is a version problem change version > 2.4 to 1.9 solve it
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
<version>2.4.1</version>
to
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
255 chars, though the complete path should not be longer than that as well. There is a nice table over at Wikipedia about this: http://en.wikipedia.org/wiki/Filename.
To use quotes just for completeness.
"/Users/my/work/a project with space"/**
If not recursive, remove the /**
Maybe this helps someone else. For me the solution was to open NuGet settings on Visual Studio (2015/2017) and add a new feed URL: http://www.nuget.org/api/v2/.
I didn't have to change any proxy related settings.
There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)
You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.
UNAME := $(shell uname -m)
all:
$(info Checking if custom header is needed)
ifeq ($(UNAME), x86_64)
... do some things to build unistd_32.h
endif
@make -C $(KDIR) M=$(PWD) modules
So you want unistd_32.h built (maybe) before you invoke the second make
, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:
ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif
all:
@make -C $(KDIR) M=$(PWD) modules
unistd_32.h:
... do some things to build unistd_32.h
Now for building unistd_32.h
:
F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else
F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
ifeq ($(F2_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
else
$(error asm/unistd_32.h and asm-386/unistd.h does not exist)
endif
endif
You are trying to build unistd.h
from unistd_32.h
; the only trick is that unistd_32.h
could be in either of two places. The simplest way to clean this up is to use a vpath
directive:
vpath unistd.h /usr/include/asm /usr/include/asm-i386
unistd_32.h: unistd.h
sed -e 's/__NR_/__NR32_/g' $< > $@
In order to have have a less verbose code, and avoid name conflicts between datetime and datetime.datetime, you should rename the classes with CamelCase names.
from datetime import datetime as DateTime, timedelta as TimeDelta
So you can do the following, which I think it is clearer.
date_1 = DateTime.today()
end_date = date_1 + TimeDelta(days=10)
Also, there would be no name conflict if you want to import datetime
later on.
First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer()
.
My solution was to do a combination of these two resources:
https://gist.github.com/tamoyal/2ea1fcdf99c819b4e07d
and
http://www.gab.lc/articles/migration_postgresql_9-3_to_9-4
The second one helped more then the first one. Also to not, don't follow the steps as is as some are not necessary. Also, if you are not being able to backup the data via postgres console, you can use alternative approach, and backup it with pgAdmin 3 or some other program, like I did in my case.
Also, the link: https://help.ubuntu.com/stable/serverguide/postgresql.html Helped to set the encrypted password and set md5 for authenticating the postgres user.
After all is done, to check the postgres server
version run in terminal:
sudo -u postgres psql postgres
After entering the password run in postgres terminal:
SHOW SERVER_VERSION;
It will output something like:
server_version
----------------
9.4.5
For setting and starting postgres I have used command:
> sudo bash # root
> su postgres # postgres
> /etc/init.d/postgresql start
> /etc/init.d/postgresql stop
And then for restoring database from a file:
> psql -f /home/ubuntu_username/Backup_93.sql postgres
Or if doesn't work try with this one:
> pg_restore --verbose --clean --no-acl --no-owner -h localhost -U postgres -d name_of_database ~/your_file.dump
And if you are using Rails do a bundle exec rake db:migrate
after pulling the code :)
Keep in mind that you have to exactly specify your path to your language.JSON like this:
language: {
url: '/mywebsite/js/localisation/German.json'
}
You can leave action attribute blank. The form will automatically submit itself in the same page.
<form action="">
According to the w3c specification, action attribute must be non-empty valid url in general. There is also an explanation for some situations in which the action attribute may be left empty.
The action of an element is the value of the element’s formaction attribute, if the element is a Submit Button and has such an attribute, or the value of its form owner’s action attribute, if it has one, or else the empty string.
So they both still valid and works:
<form action="">
<form action="FULL_URL_STRING_OF_CURRENT_PAGE">
If you are sure your audience is using html5 browsers, you can even omit the action attribute:
<form>
This will do it in one line.
>>> a=[2,3,4]
>>> b=[1,2]
>>> bool(sum(map(lambda x: x in b, a)))
True
Try TCPDF. I find it the best so far.
For detailed tutorial on using the two most popular pdf generation classes: TCPDF and FPDF.. please follow this link: PHP: Easily create PDF on the fly with TCPDF and FPDF
Hope it helps.
Suppose you have many selects. This can do it:
$('.selectClass').change(function(){
var optionSelected = $(this).find('option:selected').attr('optionAtribute');
alert(optionSelected);//this will show the value of the atribute of that option.
});
template<class It>
std::reverse_iterator<It> reversed( It it ) {
return std::reverse_iterator<It>(std::forward<It>(it));
}
Then:
for( auto rit = reversed(data.end()); rit != reversed(data.begin()); ++rit ) {
std::cout << *rit;
Alternatively in C++14 just do:
for( auto rit = std::rbegin(data); rit != std::rend(data); ++rit ) {
std::cout << *rit;
In C++03/11 most standard containers have a .rbegin()
and .rend()
method as well.
Finally, you can write the range adapter backwards
as follows:
namespace adl_aux {
using std::begin; using std::end;
template<class C>
decltype( begin( std::declval<C>() ) ) adl_begin( C&& c ) {
return begin(std::forward<C>(c));
}
template<class C>
decltype( end( std::declval<C>() ) ) adl_end( C&& c ) {
return end(std::forward<C>(c));
}
}
template<class It>
struct simple_range {
It b_, e_;
simple_range():b_(),e_(){}
It begin() const { return b_; }
It end() const { return e_; }
simple_range( It b, It e ):b_(b), e_(e) {}
template<class OtherRange>
simple_range( OtherRange&& o ):
simple_range(adl_aux::adl_begin(o), adl_aux::adl_end(o))
{}
// explicit defaults:
simple_range( simple_range const& o ) = default;
simple_range( simple_range && o ) = default;
simple_range& operator=( simple_range const& o ) = default;
simple_range& operator=( simple_range && o ) = default;
};
template<class C>
simple_range< decltype( reversed( adl_aux::adl_begin( std::declval<C&>() ) ) ) >
backwards( C&& c ) {
return { reversed( adl_aux::adl_end(c) ), reversed( adl_aux::adl_begin(c) ) };
}
and now you can do this:
for (auto&& x : backwards(ctnr))
std::cout << x;
which I think is quite pretty.
The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/"
(as I'm sure you know) means the replacement string is \/
, and (as you probably don't know) the replacement string \/
actually just inserts /
, because Java is weird, and gives \
a special meaning in the replacement string. (It's supposedly so that \$
will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:
"Hello/You/There".replaceAll("/", "\\\\/");
or:
"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));
The existing answers which leverage SJCL, CryptoJS, and/or WebCrypto aren't necessarily wrong but they're not as safe as you might initially suspect. Generally you want to use libsodium. First I'll explain why, then how.
Short answer: In order for your encryption to actually be secure, these libraries expect you to make too many choices e.g. the block cipher mode (CBC, CTR, GCM; if you can't tell which of the three I just listed is secure to use and under what constraints, you shouldn't be burdened with this sort of choice at all).
Unless your job title is cryptography engineer, the odds are stacked against you implementing it securely.
CryptoJS offers a handful of building blocks and expects you to know how to use them securely. It even defaults to CBC mode (archived).
Read this write-up on AES-CBC vulnerabilities.
WebCrypto is a potluck standard, designed by committee, for purposes that are orthogonal to cryptography engineering. Specifically, WebCrypto was meant to replace Flash, not provide security.
SJCL's public API and documentation begs users to encrypt data with a human-remembered password. This is rarely, if ever, what you want to do in the real world.
Additionally: Its default PBKDF2 round count is roughly 86 times as small as you want it to be. AES-128-CCM is probably fine.
Out of the three options above, SJCL is the least likely to end in tears. But there are better options available.
You don't need to choose between a menu of cipher modes, hash functions, and other needless options. You'll never risk screwing up your parameters and removing all security from your protocol.
Instead, libsodium just gives you simple options tuned for maximum security and minimalistic APIs.
crypto_box()
/ crypto_box_open()
offer authenticated public-key encryption.
crypto_secretbox()
/ crypto_secretbox_open()
offer shared-key authenticated encryption.
Additionally, libsodium has bindings in dozens of popular programming languages, so it's very likely that libsodium will just work when trying to interoperate with another programming stack. Also, libsodium tends to be very fast without sacrificing security.
First, you need to decide one thing:
If you selected the first option, get CipherSweet.js.
The documentation is available online. EncryptedField
is sufficient for most use cases, but the EncryptedRow
and EncryptedMultiRows
APIs may be easier if you have a lot of distinct fields you want to encrypt.
With CipherSweet, you don't need to even know what a nonce/IV is to use it securely.
Additionally, this handles int
/float
encryption without leaking facts about the contents through ciphertext size.
Otherwise, you'll want sodium-plus, which is a user-friendly frontend to various libsodium wrappers. Sodium-Plus allows you to write performant, asynchronous, cross-platform code that's easy to audit and reason about.
To install sodium-plus, simply run...
npm install sodium-plus
There is currently no public CDN for browser support. This will change soon. However, you can grab sodium-plus.min.js
from the latest Github release if you need it.
const { SodiumPlus } = require('sodium-plus');_x000D_
let sodium;_x000D_
_x000D_
(async function () {_x000D_
if (!sodium) sodium = await SodiumPlus.auto();_x000D_
let plaintext = 'Your message goes here';_x000D_
let key = await sodium.crypto_secretbox_keygen();_x000D_
let nonce = await sodium.randombytes_buf(24);_x000D_
let ciphertext = await sodium.crypto_secretbox(_x000D_
plaintext,_x000D_
nonce,_x000D_
key _x000D_
);_x000D_
console.log(ciphertext.toString('hex'));_x000D_
_x000D_
let decrypted = await sodium.crypto_secretbox_open(_x000D_
ciphertext,_x000D_
nonce,_x000D_
key_x000D_
);_x000D_
_x000D_
console.log(decrypted.toString());_x000D_
})();
_x000D_
The documentation for sodium-plus is available on Github.
If you'd like a step-by-step tutorial, this dev.to article has what you're looking for.
So I experienced this yesterday (22 feb '17), I tried uploading the build via Xcode (8.2) multiple times, it showed (Processing)
. Then I tried it with the application loader, still the same. I just had to wait for ~12 hours to have it spam me with processing done emails.
So yeah, it's not you, it's them.
This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site. Good Luck.
standalone one cell solution based on VLOOKUP
=IFERROR(ARRAYFORMULA(IF(LEN(A2:A),
IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
{{(TRANSPOSE({{{0; "Less than 500"},
{500; "Between 500 and 1000"}},
{{1000; "Between 1000 and 1500"},
{1500; "Between 1500 and 2000"}}}))}}, 2)),)), )
=IFERROR(ARRAYFORMULA(IF(LEN(A2:A);
IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
{{(TRANSPOSE({{{0; "Less than 500"}\
{500; "Between 500 and 1000"}}\
{{1000; "Between 1000 and 1500"}\
{1500; "Between 1500 and 2000"}}}))}}; 2));)); )
The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.
Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true
will not work with your first method.
[<-
with mapply
is a bit faster than sapply
.
> dat[mapply(is.infinite, dat)] <- NA
With mnel's data, the timing is
> system.time(dat[mapply(is.infinite, dat)] <- NA)
# user system elapsed
# 15.281 0.000 13.750
I had a similar problem with 'org.codehaus.mojo'-'jaxws-maven-plugin': could not resolve dependencies. Fortunately, I was able to do a Project > Clean in Eclipse, which resolved the issue.
There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)
class User(object):
email = 'none'
firstname = 'none'
lastname = 'none'
def __init__(self, email=None, firstname=None, lastname=None):
self.email = email
self.firstname = firstname
self.lastname = lastname
@classmethod
def print_var(cls, obj):
print ("obj.email obj.firstname obj.lastname")
print(obj.email, obj.firstname, obj.lastname)
print("cls.email cls.firstname cls.lastname")
print(cls.email, cls.firstname, cls.lastname)
u1 = User(email='abc@xyz', firstname='first', lastname='last')
User.print_var(u1)
In the above code, the User class has 3 global variables, each with value 'none'. u1 is the object created by instantiating this class. The method print_var prints the value of class variables of class User and object variables of object u1. In the output shown below, each of the class variables User.email
, User.firstname
and User.lastname
has value 'none'
, while the object variables u1.email
, u1.firstname
and u1.lastname
have values 'abc@xyz'
, 'first'
and 'last'
.
obj.email obj.firstname obj.lastname
('abc@xyz', 'first', 'last')
cls.email cls.firstname cls.lastname
('none', 'none', 'none')
You can use HAVING clause for filter calculated in SELECT fields and aliases
Note that shutdown.exe
is just a wrapper around InitiateSystemShutdownEx
, which provides some niceties missing in ExitWindowsEx
Actually we are not giving the answer anijhaw is looking for. Here is the one liner:
all(l[i] <= l[i+1] for i in xrange(len(l)-1))
For Python 3:
all(l[i] <= l[i+1] for i in range(len(l)-1))
Use it like this:
$("#searchField").focus(function() {
$(this).val("");
});
It has to work. Otherwise it probably never gets focused.
Functions cannot be used to modify base table information, use a stored procedure.
Strings are sorted lexicographically. The behavior you're seeing is correct.
Define your own comparator to sort the strings however you prefer.
It would also work the way you're expecting (5 as the first element) if you changed your collections to Integer instead of using String.
Use simple
ssh-keyscan hostname
to find if key(s) exists on both sites:
ssh-keyscan rc1.localdomain
[or@rc2 ~]$ ssh-keyscan rc1
# rc1 SSH-2.0-OpenSSH_5.3
rc1 ssh-rsa AAAAB3NzaC1yc2EAAAABI.......==
ssh-keyscan rc2.localdomain
[or@rc2 ~]$ ssh-keyscan rc2
# rac2 SSH-2.0-OpenSSH_5.3
rac2 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAys7kG6pNiC.......==
Use Reader.read(). A return value of -1 means end of stream; else, cast to char.
This code reads character data from a list of file arguments:
public class CharacterHandler {
//Java 7 source level
public static void main(String[] args) throws IOException {
// replace this with a known encoding if possible
Charset encoding = Charset.defaultCharset();
for (String filename : args) {
File file = new File(filename);
handleFile(file, encoding);
}
}
private static void handleFile(File file, Charset encoding)
throws IOException {
try (InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, encoding);
// buffer for efficiency
Reader buffer = new BufferedReader(reader)) {
handleCharacters(buffer);
}
}
private static void handleCharacters(Reader reader)
throws IOException {
int r;
while ((r = reader.read()) != -1) {
char ch = (char) r;
System.out.println("Do something with " + ch);
}
}
}
The bad thing about the above code is that it uses the system's default character set. Wherever possible, prefer a known encoding (ideally, a Unicode encoding if you have a choice). See the Charset class for more. (If you feel masochistic, you can read this guide to character encoding.)
(One thing you might want to look out for are supplementary Unicode characters - those that require two char values to store. See the Character class for more details; this is an edge case that probably won't apply to homework.)
If you have a pd.Series
object x
with index named 'Gene', you can use reset_index
and supply the name
argument:
df = x.reset_index(name='count')
Here's a demo:
x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'
df = x.reset_index(name='count')
print(df)
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
In simpler terms, Imagine if you want mock below line:
StaticClass.method();
then you write below lines of code to mock:
PowerMockito.mockStatic(StaticClass.class);
PowerMockito.doNothing().when(StaticClass.class);
StaticClass.method();
In python 3.7 and above there is a new and easy way. here is the syntax:
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
OutPut:
Hello, Eric. You are 74.
In my case, detach
and attach
worked:
getSupportFragmentManager()
.beginTransaction()
.detach(contentFragment)
.attach(contentFragment)
.commit();
<?php
echo "<p>hello\n";
echo "world</p>";
echo "\n\n";
echo "<p>\n\tindented\n</p>\n";
echo "
<div>
easy formatting<br />
across multiple lines!
</div>
";
?>
<p>hello
world</p>
<p>
indented
</p>
<div>
easy formatting<br />
across multiple lines!
</div>
String[] strarray = strlist.toArray(new String[0]);
if u want List convert to string use StringUtils.join(slist, '\n');
Next to being in the wrong directory I just tripped about another variant:
I had a File.open(my_file).each {|line| puts line}
exploding but there was something by that name in the directory I was working in (ls in the command line showed the name). I checked with a File.exists?(my_file)
which strangely returned false
. Explanation: my_file
was a symlink which target didn't exist anymore! Since File.exists?
will follow a symlink it will say false
though the link is still there.
Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:
(X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C)
, where ...
means "0 or more different values(B,) dot (B, C) -> (C,)
(A, B) dot (B,) -> (A,)
(B,) dot (B,) -> ()
Your problem is that you are using np.matrix
, which is totally unnecessary in your code - the main purpose of np.matrix
is to translate a * b
into np.dot(a, b)
. As a general rule, np.matrix
is probably not a good choice.
Using display:none is not SEO-friendly. The following way allows the hidden content to be searchable. Adding the transition-delay ensures any links included in the hidden content is clickable.
.collapse > p{
cursor: pointer;
display: block;
}
.collapse:focus{
outline: none;
}
.collapse > div {
height: 0;
width: 0;
overflow: hidden;
transition-delay: 0.3s;
}
.collapse:focus div{
display: block;
height: 100%;
width: 100%;
overflow: auto;
}
<div class="collapse" tabindex="1">
<p>Question 1</p>
<div>
<p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
<div class="collapse" tabindex="2">
<p>Question 2</p>
<div>
<p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
In Firefox, any invalid Date is returned as a Date object as Date 1899-11-29T19:00:00.000Z
, therefore check if browser is Firefox then get Date object of string "1899-11-29T19:00:00.000Z".getDate()
. Finally compare it with the date.
I use the VFS API from Apache Commons, here is an example of how to monitor a file without much impact in performance:
I was also stuck on the same kind of problem and I followed the simple steps below.
Just get the exact url of the file to which you want to copy, for example:
http://www.test.com/test.txt (file to copy)
Then pass the exact absolute folder path with filename where you do want to write that file.
If you are on a Windows machine then
d:/xampp/htdocs/upload/test.txt
If you are on a Linux machine then
/var/www/html/upload/test.txt
You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT']
.
Interfaces can not contain any implementation (including default values). You need to switch to abstract class.
In Chrome Browser go to setting , clear browsing history and then reload the page
When the iFrame points to your site like this:
<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
</head>
<body>
<iframe id="my_frame" src="/wherev"></iframe>
</body>
</html>
You can access iFrame DOM through this kind of thing.
var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));
You can do it by using name attibute, class, id or just universal checkbox; If you want to count only checked number of checkbox.
By the class name :
var countChk = $('checkbox.myclassboxName:checked').length;
By name attribute :
var countByName= $('checkbox[name=myAllcheckBoxName]:checked').length;
$('checkbox.className').blur(function() {
//count only checked checkbox
$('checkbox[name=myAllcheckBoxName]:checked').length;
});
The + character occurring in a data URI should be encoded as %2B. This is like encoding any other string in a URI. For example, argument separators (? and &) must be encoded when a URI with an argument is sent as part of another URI.
You can use the -as operator. If casting succeed you get back a number:
$numberAsString -as [int]
I also had messages like No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
I had configured cors properly, but what was missing in webflux in RouterFuncion was accept and contenttype headers APPLICATION_JSON like in this piece of code:
@Bean
RouterFunction<ServerResponse> routes() {
return route(POST("/create")
.and(accept(APPLICATION_JSON))
.and(contentType(APPLICATION_JSON)), serverRequest -> create(serverRequest);
}
sudo.bat
(you can replace sudo
with any name you want) with following content
powershell.exe -Command "Start-Process cmd \"/k cd /d %cd%\" -Verb RunAs"
sudo.bat
to a folder in your PATH
; if you don't know what that means, just move these files to c:\windows\
sudo
will work in Run dialog (win+r) or in explorer address bar (this is the best part :))sudo.bat
(you can replace sudo
with any name you want) with following content
nircmdc elevate cmd /k "cd /d %cd%"
nircmdc.exe
and sudo.bat
to a folder in your PATH
; if you don't know what that means, just move these files to c:\windows\
sudo
will work in Run dialog (win+r) or in explorer address bar (this is the best part :))^\d{1,2}[\W_]?po$
\d
defines a number and {1,2}
means 1 or two of the expression before, \W
defines a non word character.
This worked for me, even within a div:
div.cntrblk tr:hover td {
line-height: 150%;
background-color: rgb(255,0,0);
font-weight: bold;
font-size: 150%;
border: 0;
}
It selected the entire row, but I'd like it to not do the header, haven't looked at that yet. It also partially fixed the fonts that wouldn't scale-up with the hover??? Apparently you to have apply settings to the cell not the row, but select all the component cells with the tr:hover. On to tracking down the in-consistent font scaling problem. Sweet that CSS will do this.
As for the other part of the question, it's common to put the underscore at the end of the variable name to not clash with anything internal.
I do this even inside classes and namespaces because I then only have to remember one rule (compared to "at the end of the name in global scope, and the beginning of the name everywhere else").
This will update npm using npm itself:
sudo npm install npm -g
If you are stuck, try sudo npm update npm -g
. All credit goes to Tim Castelijns. I have tested it on ubuntu 14.04, npm 1.3.10
Note that if you are using nvm for managing multiple versions in your local dev environment for e.g. testing purposes, all your installed versions (listed by nvm ls
) are in ~/.nvm, hence you just omit system wide installation (i.e. omit sudo):
npm install npm -g
DEBIAN ENTERPRISE
For full enterprise practice consider nodesource.com:
curl -sL https://deb.nodesource.com/setup | sudo bash -
as described here.
OTHER ENTERPRISE
For non-debian distributions check out on the node github wiki
https://github.com/joyent/node/wiki/installing-node.js-via-package-manager download page https://nodejs.org/en/download/
For historical understanding: Chis Lea was maintaining his PPA but now joined forces with nodesource.
A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.
regex example:
boolean = (var.to_s =~ /^true$/i) == 0
ternary example:
boolean = var.to_s.eql?('true') ? true : false
The advantage to the regex method is that regular expressions are flexible and can match a wide variety of patterns. For example, if you suspect that var could be any of "True", "False", 'T', 'F', 't', or 'f', then you can modify the regex:
boolean = (var.to_s =~ /^[Tt].*$/i) == 0
The loop in your code is only an over-simplified example, right?
It would be better to create the PreparedStatement
only once, and re-use it over and over again in the loop.
In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement
, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.
To address the situation that you want to re-use the Java-side PreparedStatement
, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement
for the same SQL on the same connection, it will give you the same (cached) instance.
About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.
Another scenario where this shows up is if you are using the older "Web Site" project type in Visual Studio. For that project type, it is unable to reference .dlls that are outside of it's own directory structure (current folder and down). So in the answer above, let's say your directory structure looks like this:
Where ProjectX and ProjectY are parent/child directories, and ProjectX references A.dll which in turn references B.dll, and B.dll is outside the directory structure, such as in a Nuget package on the root (Packages), then A.dll will be included, but B.dll will not.
If you can live with 2.6, EPEL has it for RHEL 5 in the python26
package, although you will need to use python2.6
to invoke it since the system will still need python
to be 2.4 in order to run.
Iterator is an interface in the Java Collections framework that provides methods to traverse or iterate over a collection.
Both iterator and for loop acts similar when your motive is to just traverse over a collection to read its elements.
for-each
is just one way to iterate over the Collection.
For example:
List<String> messages= new ArrayList<>();
//using for-each loop
for(String msg: messages){
System.out.println(msg);
}
//using iterator
Iterator<String> it = messages.iterator();
while(it.hasNext()){
String msg = it.next();
System.out.println(msg);
}
And for-each loop can be used only on objects implementing the iterator interface.
Now back to the case of for loop and iterator.
The difference comes when you try to modify a collection. In this case, iterator is more efficient because of its fail-fast property. ie. it checks for any modification in the structure of underlying collection before iterating over the next element. If there are any modifications found, it will throw the ConcurrentModificationException.
(Note: This functionality of iterator is only applicable in case of collection classes in java.util package. It is not applicable for concurrent collections as they are fail-safe by nature)
What do you want to fade? The background
or color
attribute?
Currently you're changing the background color, but telling it to transition the color property. You can use all
to transition all properties.
.clicker {
-moz-transition: all .2s ease-in;
-o-transition: all .2s ease-in;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
background: #f5f5f5;
padding: 20px;
}
.clicker:hover {
background: #eee;
}
Otherwise just use transition: background .2s ease-in
.
Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy
, use size()
. Otherwise use list comprehensions within recursion.
Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL
This solution also helps in cases of more than one extension like "Avishay.student.DB"
FileInfo FileInf = new FileInfo(filePath);
string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");
This works for me:
$(function () {
$('#datetimepicker5').datetimepicker({
use24hours: true,
format: 'HH:mm'
});
});
Important: It only worked at the point I used uppercase "H" as time format.
You might also consider adding "
.
For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus"
is very good idea.
I also had similar problem where redirects were giving 404 or 405 randomly on my development server. It was an issue with gunicorn instances.
Turns out that I had not properly shut down the gunicorn instance before starting a new one for testing.
Somehow both of the processes were running simultaneously, listening to the same port 8080 and interfering with each other.
Strangely enough they continued running in background after I had killed all my terminals.
Had to kill them manually using fuser -k 8080/tcp
Get COLUMN INDEX on click:
$(this).closest("td").index();
Get ROW INDEX on click:
$(this).closest("tr").index();
String str = "129018";
StringBuilder sb = new StringBuilder();
for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
sb.append('0');
}
sb.append(str);
String result = sb.toString();
Small full code example
Using flat plain stdio standard library only
#include <stdio.h>
int main()
{
char c[1024];
int i=0;
i+=sprintf(c+i,"We " );
i+=sprintf(c+i,"Love " );
sprintf(c+i,"Coding");
printf("%s",c);
}
OUTPUT: We Love Coding
It will open like this:
4, Copy and paste that code in your style.css and simply start using that font like this:
<Typography
variant="h1"
gutterBottom
style={{ fontFamily: "Spicy Rice", color: "pink" }}
>
React Rock
</Typography>
Result:
When you have multiple files, an idea is to show only the first file and the number of the hidden file names.
$('.custom-file input').change(function() {
var $el = $(this),
files = $el[0].files,
label = files[0].name;
if (files.length > 1) {
label = label + " and " + String(files.length - 1) + " more files"
}
$el.next('.custom-file-label').html(label);
});
You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:
>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'
This would of course fail if there is multiple numbers in the input. a quick check would be:
assert(age in input_given)
and also:
assert(len(name)<len(input_given))
As far as I know, there's a good library called localeplanet
for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)
Here's the website of library: http://www.localeplanet.com/
Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/
The common part of all those articles/libraries is that they use a i18n
class and a get
method (in some ways also defining an smaller function name like _
) for retrieving/converting the key
to the value
. In my explaining the key
means that string you want to translate and the value
means translated string.
Then, you just need a JSON document to store key
's and value
's.
For example:
var _ = document.webL10n.get;
alert(_('test'));
And here the JSON:
{ test: "blah blah" }
I believe using current popular libraries solutions is a good approach.
https://github.com/mozilla/pdf.js/
for a live demo http://mozilla.github.io/pdf.js/
it's probably what you want, but I can't see the point of this since modern browsers include such functionality, also it will run terribly slow on low-powered devices like mobile devices that, by the way, have their own optimized plugins and apps.
There are probably as many naming conventions as there are individuals, the debate being as endless (and sterile) as to which brace style to use and so forth.
So I'll have 2 advices:
The rest is up to you.
You might consider changing your approach and using a variable variable name?
$var_name = "FooBar";
$$var_name = "a string";
then you could just
print($var_name);
to get
FooBar
Here's the link to the PHP manual on Variable variables
var attr, object_information='';
for(attr in object){
//Get names and values of propertys with style (name : value)
object_information += attr + ' : ' + object[attr] + '\n';
}
alert(object_information); //Show all Object
That is ambiguous because a pointer is just an address, so an int
can also be treated as a pointer – 0 (an int
) can be converted to unsigned int
or char *
equally easily.
The short answer is to call p.setval()
with something that's unambiguously one of the types it's implemented for: unsigned int
or char *
. p.setval(0U)
, p.setval((unsigned int)0)
, and p.setval((char *)0)
will all compile.
It's generally a good idea to stay out of this situation in the first place, though, by not defining overloaded functions with such similar types.
Visual Studio 2003 doesn't seem to allow you to set environment variables for debugging.
What I do in C/C++ is use _putenv()
in main()
and set any variables. Usually I surround it with a #if defined DEBUG_MODE / #endif
to make sure only certain builds have it.
_putenv("MYANSWER=42");
I believe you can do the same thing with C# using os.putenv(), i.e.
os.putenv('MYANSWER', '42');
These will set the envrironment variable for that shell process only, and as such is an ephemeral setting, which is what you are looking for.
By the way, its good to use process explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx), which is a sysinternals tool. You can see what a given process' copy of the environment variables is, so you can validate that what you set is what you got.
You can also use android.os.SystemClock. For example SystemClock.elapsedRealtime() will give you more accurate time readings when the phone is asleep.
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
console.log(strTime);
$scope.time = strTime;
date.setDate(date.getDate()+1);
month = '' + (date.getMonth() + 1),
day = '' + date.getDate(1),
year = date.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var tomorrow = [year, month, day].join('-');
$scope.tomorrow = tomorrow;
You are missing a comma in your statement.
Try this:
data[data[, "Var1"]>10, ]
Or:
data[data$Var1>10, ]
Or:
subset(data, Var1>10)
As an example, try it on the built-in dataset, mtcars
data(mtcars)
mtcars[mtcars[, "mpg"]>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
mtcars[mtcars$mpg>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
subset(mtcars, mpg>25)
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
The basic issue: /usr/bin/java
is pointing to one provided by OSX itself initially (/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
)
We need to point this to the one downloaded by the JDK installer. The below steps are for OSX 10.10.4 Yosemite.
Path
item and copy the path (cmd+c). This is the latest one installed by the JDK installer/updater. In my case, the path was /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java
ln -s
command) the system java binary to the latest one, which we discovered in the previous step. Run the below command:sudo ln -s /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java
Thats it. To verify, you can just run
java -version
on the terminal. It should output the latest version that you installed/updated to.
originalArrayList.addAll(copyArrayList);
Please Note: When using the addAll() method to copy, the contents of both the array lists (originalArrayList and copyArrayList) refer to the same objects or contents. So if you modify any one of them the other will also reflect the same change.
If you don't wan't this then you need to copy each element from the originalArrayList to the copyArrayList, like using a for or while loop.
You want something more like this:
SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
JOIN TableB
ON TableB.aID = TableA.aID
JOIN TableC
ON TableC.cID = TableB.cID
JOIN TableD
ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now())
In your example, you are not actually including TableD
. All you have to do is perform another join just like you have done before.
A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.
Assertions are a development-phase tool to catch bugs in your code. They're designed to be easily removed, so they won't exist in production code. So assertions are not part of the "solution" that you deliver to the customer. They're internal checks to make sure that the assumptions you're making are correct. The most common example is to test for null. Many methods are written like this:
void doSomething(Widget widget) {
if (widget != null) {
widget.someMethod(); // ...
... // do more stuff with this widget
}
}
Very often in a method like this, the widget should simply never be null. So if it's null, there's a bug in your code somewhere that you need to track down. But the code above will never tell you this. So in a well-intentioned effort to write "safe" code, you're also hiding a bug. It's much better to write code like this:
/**
* @param Widget widget Should never be null
*/
void doSomething(Widget widget) {
assert widget != null;
widget.someMethod(); // ...
... // do more stuff with this widget
}
This way, you will be sure to catch this bug early. (It's also useful to specify in the contract that this parameter should never be null.) Be sure to turn assertions on when you test your code during development. (And persuading your colleagues to do this, too is often difficult, which I find very annoying.)
Now, some of your colleagues will object to this code, arguing that you should still put in the null check to prevent an exception in production. In that case, the assertion is still useful. You can write it like this:
void doSomething(Widget widget) {
assert widget != null;
if (widget != null) {
widget.someMethod(); // ...
... // do more stuff with this widget
}
}
This way, your colleagues will be happy that the null check is there for production code, but during development, you're no longer hiding the bug when widget is null.
Here's a real-world example: I once wrote a method that compared two arbitrary values for equality, where either value could be null:
/**
* Compare two values using equals(), after checking for null.
* @param thisValue (may be null)
* @param otherValue (may be null)
* @return True if they are both null or if equals() returns true
*/
public static boolean compare(final Object thisValue, final Object otherValue) {
boolean result;
if (thisValue == null) {
result = otherValue == null;
} else {
result = thisValue.equals(otherValue);
}
return result;
}
This code delegates the work of the equals()
method in the case where thisValue is not null. But it assumes the equals()
method correctly fulfills the contract of equals()
by properly handling a null parameter.
A colleague objected to my code, telling me that many of our classes have buggy equals()
methods that don't test for null, so I should put that check into this method. It's debatable if this is wise, or if we should force the error, so we can spot it and fix it, but I deferred to my colleague and put in a null check, which I've marked with a comment:
public static boolean compare(final Object thisValue, final Object otherValue) {
boolean result;
if (thisValue == null) {
result = otherValue == null;
} else {
result = otherValue != null && thisValue.equals(otherValue); // questionable null check
}
return result;
}
The additional check here, other != null
, is only necessary if the equals()
method fails to check for null as required by its contract.
Rather than engage in a fruitless debate with my colleague about the wisdom of letting the buggy code stay in our code base, I simply put two assertions in the code. These assertions will let me know, during the development phase, if one of our classes fails to implement equals()
properly, so I can fix it:
public static boolean compare(final Object thisValue, final Object otherValue) {
boolean result;
if (thisValue == null) {
result = otherValue == null;
assert otherValue == null || otherValue.equals(null) == false;
} else {
result = otherValue != null && thisValue.equals(otherValue);
assert thisValue.equals(null) == false;
}
return result;
}
The important points to keep in mind are these:
Assertions are development-phase tools only.
The point of an assertion is to let you know if there's a bug, not just in your code, but in your code base. (The assertions here will actually flag bugs in other classes.)
Even if my colleague was confident that our classes were properly written, the assertions here would still be useful. New classes will be added that might fail to test for null, and this method can flag those bugs for us.
In development, you should always turn assertions on, even if the code you've written doesn't use assertions. My IDE is set to always do this by default for any new executable.
The assertions don't change the behavior of the code in production, so my colleague is happy that the null check is there, and that this method will execute properly even if the equals()
method is buggy. I'm happy because I will catch any buggy equals()
method in development.
Also, you should test your assertion policy by putting in a temporary assertion that will fail, so you can be certain that you are notified, either through the log file or a stack trace in the output stream.
This is the only thing that I found to work
-(void) testHTTPS {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:[NSString stringWithFormat:@"%@", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
I know this is not fully relevant, but since this answer is ranked first many a times when you search 'how to display images in Jupyter', please consider this answer as well.
You could use matplotlib to show an image as follows.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("your_image.png")
plt.imshow(image)
plt.show()
/*
Tracks what keys are currently down on the keyboard
*/
function keyboard_module(onUpdate){
var kb = {};
var unicode_mapping = {};
document.onkeydown = function(e){
var unicode=e.charCode? e.charCode : e.keyCode
var key = getKey(unicode);
kb[key] = true;
if(onUpdate){
onUpdate(kb);
}
}
document.onkeyup = function(e){
var unicode=e.charCode? e.charCode : e.keyCode
var key = getKey(unicode);
delete kb[key];
if(onUpdate){
onUpdate(kb);
}
}
function getKey(unicode){
if(unicode_mapping[unicode]){
var key = unicode_mapping[unicode];
}else{
var key= unicode_mapping[unicode] = String.fromCharCode(unicode);
}
return key;
}
return kb;
}
function testing(kb){
console.log('These are the down keys', kb);
}
var keyboard = keyboard_module(testing);
....
//somewhere else in the code
if(keyboard['K']){/*do something special */}
On a rather unrelated note: more performance hacks!
When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N
(shown first):
To leap past these 2 elements means to compute (N >> 1) + N + 1
, ((N << 1) + N + 1) >> 1
and N >> 2
, respectively.
Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1
.
Case (1) is obvious. Case (2) implies (N & 1) == 1
, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba
from most- to least-significant, then a = 1
, and the following holds:
(N << 1) + N + 1: (N >> 1) + N + 1:
b10 b1
b1 b
+ 1 + 1
---- ---
bBb0 bBb
where B = !b
. Right-shifting the first result gives us exactly what we want.
Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1
.
As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.
The resulting algorithm looks like this:
uint64_t sequence(uint64_t size, uint64_t *path) {
uint64_t n, i, c, maxi = 0, maxc = 0;
for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
c = 2;
while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
c += 2;
if (n == 2)
c++;
if (c > maxc) {
maxi = i;
maxc = c;
}
}
*path = maxc;
return maxi;
}
int main() {
uint64_t maxi, maxc;
maxi = sequence(1000000, &maxc);
printf("%llu, %llu\n", maxi, maxc);
return 0;
}
Here we compare n > 2
because the process may stop at 2 instead of 1 if the total length of the sequence is odd.
Let`s translate this into assembly!
MOV RCX, 1000000;
DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;
@main:
XOR RSI, RSI;
LEA RDI, [RCX + 1];
@loop:
ADD RSI, 2;
LEA RDX, [RDI + RDI*2 + 2];
SHR RDX, 1;
SHRD RDI, RDI, 2; ror rdi,2 would do the same thing
CMOVL RDI, RDX; Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
CMOVS RDI, RDX;
CMP RDI, 2;
JA @loop;
LEA RDX, [RSI + 1];
CMOVE RSI, RDX;
CMP RAX, RSI;
CMOVB RAX, RSI;
CMOVB RBX, RCX;
SUB RCX, 2;
JA @main;
MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;
@itoa:
XOR RDX, RDX;
DIV RCX;
ADD RDX, '0';
PUSH RDX;
TEST RAX, RAX;
JNE @itoa;
PUSH RCX;
LEA RAX, [RBX + 1];
TEST RBX, RBX;
MOV RBX, RDI;
JNE @itoa;
POP RCX;
INC RDI;
MOV RDX, RDI;
@outp:
MOV RSI, RSP;
MOV RAX, RDI;
SYSCALL;
POP RAX;
TEST RAX, RAX;
JNE @outp;
LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;
Use these commands to compile:
nasm -f elf64 file.asm
ld -o file file.o
See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)
If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.
For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.
If you have already included the CSRF token in your form. Then you are getting the error page possibly because of cache data in your form.
Open your terminal/command prompt and run these commands in your project root.
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
,Also try to clear the browser cache along with running these commands.
You can indeed use __call() in a generic fashion to access protected methods. To be able to test this class
class Example {
protected function getMessage() {
return 'hello';
}
}
you create a subclass in ExampleTest.php:
class ExampleExposed extends Example {
public function __call($method, array $args = array()) {
if (!method_exists($this, $method))
throw new BadMethodCallException("method '$method' does not exist");
return call_user_func_array(array($this, $method), $args);
}
}
Note that the __call() method does not reference the class in any way so you can copy the above for each class with protected methods you want to test and just change the class declaration. You may be able to place this function in a common base class, but I haven't tried it.
Now the test case itself only differs in where you construct the object to be tested, swapping in ExampleExposed for Example.
class ExampleTest extends PHPUnit_Framework_TestCase {
function testGetMessage() {
$fixture = new ExampleExposed();
self::assertEquals('hello', $fixture->getMessage());
}
}
I believe PHP 5.3 allows you to use reflection to change the accessibility of methods directly, but I assume you'd have to do so for each method individually.
Humans:
Get the snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Bots:
The accepted answer is correct with removing URL by NSFileManager is correct, but as stated in iOS 5+ edit, the persistent store is not represented only by one file. For SQLite store it's *.sqlite, *.sqlite-shm and *.sqlite-wal ... fortunately since iOS 7+ we can use method
[NSPersistentStoreCoordinator +removeUbiquitousContentAndPersistentStoreAtURL:options:error:]
to take care of removal, so the code should be something like this:
NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSString *storeName = ...;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:storeURL.path options:@{NSPersistentStoreUbiquitousContentNameKey: storeName} error:&error];
Just Use
hr
{
padding: 0;
border: none;
border-top: 1px solid #CCC;
color: #333;
text-align: center;
font-size: 12px;
vertical-align:middle;
}
hr:after
{
content: "Or";
display: inline-block;
position: relative;
top: -0.7em;
font-size: 1.2em;
padding: 0 0.25em;
background: white;
}
In Javascript you can do the following:
Object.keys(ahash)[0];
for others who have troubles to add swift class into objective-c project. this is what work for me :
and that's it. now create the swift class in your code like it was objective-c.
Take a look at the Cursor.Position
Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
This issue is coming due to some build error. 1. Clean Project - if issue not resolve 2. update maven project - If still not resolved 3. Go to build path from (right click on project- > properties -> java build path) now check library files. if you see an error then resolve it by adding missing file at given location.
I face the same issue, after lots of approaches I found 3rd solution to get that issue fixed
Yes, you can do
git push https://username:[email protected]/file.git --all
in this case https://username:[email protected]/file.git
replace the origin
in git push origin --all
To see more options for git push
, try git help push
Use JSON to transfer data types (arrays and objects) between client and server.
In PHP:
In JavaScript:
PHP:
echo json_encode($id_numbers);
JavaScript:
id_numbers = JSON.parse(msg);
As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.
id_numbers = new Array();
$.ajax({
url:"Example.php",
type:"POST",
success:function(msg){
id_numbers = msg;
},
dataType:"json"
});
def copy_myfile_dirOne_to_dirSec(src, dest, ext):
if not os.path.exists(dest): # if dest dir is not there then we create here
os.makedirs(dest);
for item in os.listdir(src):
if item.endswith(ext):
s = os.path.join(src, item);
fd = open(s, 'r');
data = fd.read();
fd.close();
fname = str(item); #just taking file name to make this name file is destination dir
d = os.path.join(dest, fname);
fd = open(d, 'w');
fd.write(data);
fd.close();
print("Files are copyed successfully")
height attribute has been deprecated in html 5. What I would do is create a border around the hr and increase the thickness of the border as such: hr style="border:solid 2px black;"
from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
This is precisely the sort of scenario where analytics come to the rescue.
Given this test data:
SQL> select * from employment_history
2 order by Gc_Staff_Number
3 , start_date
4 /
GC_STAFF_NUMBER START_DAT END_DATE C
--------------- --------- --------- -
1111 16-OCT-09 Y
2222 08-MAR-08 26-MAY-09 N
2222 12-DEC-09 Y
3333 18-MAR-07 08-MAR-08 N
3333 01-JUL-09 21-MAR-09 N
3333 30-JUL-10 Y
6 rows selected.
SQL>
An inline view with an analytic LAG() function provides the right answer:
SQL> select Gc_Staff_Number
2 , start_date
3 , prev_end_date
4 from (
5 select Gc_Staff_Number
6 , start_date
7 , lag (end_date) over (partition by Gc_Staff_Number
8 order by start_date )
9 as prev_end_date
10 , current_flag
11 from employment_history
12 )
13 where current_flag = 'Y'
14 /
GC_STAFF_NUMBER START_DAT PREV_END_
--------------- --------- ---------
1111 16-OCT-09
2222 12-DEC-09 26-MAY-09
3333 30-JUL-10 21-MAR-09
SQL>
The inline view is crucial to getting the right result. Otherwise the filter on CURRENT_FLAG removes the previous rows.
You can use NOW()
:
INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())
A really simple way to do this...
// create the option
var opt = $("<option>").val("myvalue").text("my text");
//append option to the select element
$(#my-select).append(opt);
This could be done in lots of ways, even in a single line if really you want to.
Your syntax would create an alias for a as b, but it wouldn't have scope beyond the results of the statement. It sounds like you may want to create a VIEW
Use a library like Guava or Commons / IO. They have oneliner methods.
Guava:
Files.toString(file, charset);
Commons / IO:
FileUtils.readFileToString(file, charset);
Without such a library, I'd write a helper method, something like this:
public String readFile(File file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file.toPath()), charset);
}
Here is the simplest and the easiest way to find the position of the clicked item:
I've also faced the same problem.
I wanted to find of the position of the clicked/selected item of the RecyclerView() and perform some specific operations on that particular item.
getAdapterPosition() method works like a charm for these kind of stuff. I found this method after a day of long research and after trying numerous other methods.
int position = getAdapterPosition();
Toast.makeText(this, "Position is: "+position, Toast.LENGTH_SHORT).show();
You do not have to use any extra method. Just create a global variable named 'position' and initialize it with getAdapterPosition() in any of the major method of the adapter (class or similar).
Here is a brief documentation from this link.
getAdapterPosition added in version 22.1.0 int getAdapterPosition () Returns the Adapter position of the item represented by this ViewHolder. Note that this might be different than the getLayoutPosition() if there are pending adapter updates but a new layout pass has not happened yet. RecyclerView does not handle any adapter updates until the next layout traversal. This may create temporary inconsistencies between what user sees on the screen and what adapter contents have. This inconsistency is not important since it will be less than 16ms but it might be a problem if you want to use ViewHolder position to access the adapter. Sometimes, you may need to get the exact adapter position to do some actions in response to user events. In that case, you should use this method which will calculate the Adapter position of the ViewHolder.
Happy to help. Feel free to ask doubts.
After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout
. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
I had a number of errors similar to this. Make sure your setFrom email address is valid in $mail->setFrom()
There's a simpler way than a whole bunch of if statements. Use the or (||) operator.
function getBrowserDimensions() {
return {
width: (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth),
height: (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)
};
}
var browser_dims = getBrowserDimensions();
alert("Width = " + browser_dims.width + "\nHeight = " + browser_dims.height);
This will solve the problem. No need to write code in controller. And remove your css styles display:none
<div><button id="mybutton" ng-click="myvalue=true">Click me</button></div>
Check for any webkit styles being applied to elements like ul, h4 etc. For me it was margin-before and after causing this.
-webkit-margin-before: 1.33em;
-webkit-margin-after: 1.33em;
Arrays.asList() returns a list that doesn't allow operations affecting its size (note that this is not the same as "unmodifiable").
You could do new ArrayList<String>(Arrays.asList(split));
to create a real copy, but seeing what you are trying to do, here is an additional suggestion (you have a O(n^2)
algorithm right below that).
You want to remove list.size() - count
(lets call this k
) random elements from the list. Just pick as many random elements and swap them to the end k
positions of the list, then delete that whole range (e.g. using subList() and clear() on that). That would turn it to a lean and mean O(n)
algorithm (O(k)
is more precise).
Update: As noted below, this algorithm only makes sense if the elements are unordered, e.g. if the List represents a Bag. If, on the other hand, the List has a meaningful order, this algorithm would not preserve it (polygenelubricants' algorithm instead would).
Update 2: So in retrospect, a better (linear, maintaining order, but with O(n) random numbers) algorithm would be something like this:
LinkedList<String> elements = ...; //to avoid the slow ArrayList.remove()
int k = elements.size() - count; //elements to select/delete
int remaining = elements.size(); //elements remaining to be iterated
for (Iterator i = elements.iterator(); k > 0 && i.hasNext(); remaining--) {
i.next();
if (random.nextInt(remaining) < k) {
//or (random.nextDouble() < (double)k/remaining)
i.remove();
k--;
}
}
You name it... Lambda version... :)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
You need several includes... I leave you that as an exercise...
I know this answer is late, but I hope it helps others.
The answer is simple. You have to just copy your local.properties
file to the folder where project is stored and it will work like charm. But remember, it must be placed in the root folder where the project is stored.
No, you cannot insert a div directly inside of a table. It is not correct html, and will result in unexpected output.
I would be happy to be more insightful, but you haven't said what you are attempting, so I can't really offer an alternative.
You can also use onBackPressed by following ways using customized Toast:
customized_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/txtMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@drawable/ic_white_exit_small"
android:drawableLeft="@drawable/ic_white_exit_small"
android:drawablePadding="8dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center"
android:textColor="@android:color/white"
android:textSize="16sp"
android:text="Press BACK again to exit.."
android:background="@drawable/curve_edittext"/>
MainActivity.java
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
android.os.Process.killProcess(Process.myPid());
System.exit(1);
return;
}
this.doubleBackToExitPressedOnce = true;
Toast toast = new Toast(Dashboard.this);
View view = getLayoutInflater().inflate(R.layout.toast_view,null);
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);
int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin);
toast.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Upon trying all the answers above, I found that using "RequestsCookieJar" instead of the regular CookieJar for subsequent requests fixed my problem.
import requests
import json
# The Login URL
authUrl = 'https://whatever.com/login'
# The subsequent URL
testUrl = 'https://whatever.com/someEndpoint'
# Logout URL
testlogoutUrl = 'https://whatever.com/logout'
# Whatever you are posting
login_data = {'formPosted':'1',
'login_email':'[email protected]',
'password':'pw'
}
# The Authentication token or any other data that we will receive from the Authentication Request.
token = ''
# Post the login Request
loginRequest = requests.post(authUrl, login_data)
print("{}".format(loginRequest.text))
# Save the request content to your variable. In this case I needed a field called token.
token = str(json.loads(loginRequest.content)['token']) # or ['access_token']
print("{}".format(token))
# Verify Successful login
print("{}".format(loginRequest.status_code))
# Create your Requests Cookie Jar for your subsequent requests and add the cookie
jar = requests.cookies.RequestsCookieJar()
jar.set('LWSSO_COOKIE_KEY', token)
# Execute your next request(s) with the Request Cookie Jar set
r = requests.get(testUrl, cookies=jar)
print("R.TEXT: {}".format(r.text))
print("R.STCD: {}".format(r.status_code))
# Execute your logout request(s) with the Request Cookie Jar set
r = requests.delete(testlogoutUrl, cookies=jar)
print("R.TEXT: {}".format(r.text)) # should show "Request Not Authorized"
print("R.STCD: {}".format(r.status_code)) # should show 401
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
The link you gave does actually describe the differences, but it's buried at the bottom of the page:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
The conversion could be to normalize \r\n
to \n
(or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.
In my case it was stupid missing of @OneToOne annotation, i set @MapsId without it
TL;DR:
No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.
Answer:
EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald
[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.
This is stated really clear in EventEmitter's documentation.
Use by directives and components to emit custom Events.
Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit()
method. We should never subscribe manually to an EventEmitter.
All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference
Do NOT count on EventEmitter continuing to be an Observable!
Do NOT count on those Observable operators being there in the future!
These will be deprecated soon and probably removed before release.
Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call
eve.emit()
His comment is in line with Rob's comment long time ago.
Simply use it to emit events from your component. Take a look a the following example.
@Component({
selector : 'child',
template : `
<button (click)="sendNotification()">Notify my parent!</button>
`
})
class Child {
@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit('Some value to send to the parent');
}
}
@Component({
selector : 'parent',
template : `
<child (notifyParent)="getNotification($event)"></child>
`
})
class Parent {
getNotification(evt) {
// Do something with the notification (evt) sent by the child!
}
}
class MyService {
@Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}
Stop right there... you're already wrong...
Hopefully these two simple examples will clarify EventEmitter's proper usage.
Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.
Create an assembly called SomeAssembly.dll with this class :
namespace SomeNameSpace
{
public class MyProxy : IWebProxy
{
public ICredentials Credentials
{
get { return new NetworkCredential("user", "password"); }
//or get { return new NetworkCredential("user", "password","domain"); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri("http://my.proxy:8080");
}
public bool IsBypassed(Uri host)
{
return false;
}
}
}
Add this to your config file :
<defaultProxy enabled="true" useDefaultCredentials="false">
<module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>
This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.
This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.
Class is for applying your style to a group of elements. ID styles apply to just the element with that ID (there should only be one). Usually you use classes, but if there's a one-off you can use IDs (or just stick the style straight into the element).
When use codeIgniter Framework then refer this active records link. how the data interact with structure and more.
The following functions allow you to build SQL SELECT statements.
Selecting Data
$this->db->get();
Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:
$query = $this->db->get('mytable');
With access to each row
$query = $this->db->get('mytable');
foreach ($query->result() as $row)
{
echo $row->title;
}
Where clues
$this->db->get_where();
EG:
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
Select field
$this->db->select('title, content, date');
$query = $this->db->get('mytable');
// Produces: SELECT title, content, date FROM mytable
E.G
$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');
Both @property
and traditional getters and setters have their advantages. It depends on your use case.
@property
You don't have to change the interface while changing the implementation of data access. When your project is small, you probably want to use direct attribute access to access a class member. For example, let's say you have an object foo
of type Foo
, which has a member num
. Then you can simply get this member with num = foo.num
. As your project grows, you may feel like there needs to be some checks or debugs on the simple attribute access. Then you can do that with a @property
within the class. The data access interface remains the same so that there is no need to modify client code.
Cited from PEP-8:
For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.
Using @property
for data access in Python is regarded as Pythonic:
It can strengthen your self-identification as a Python (not Java) programmer.
It can help your job interview if your interviewer thinks Java-style getters and setters are anti-patterns.
Traditional getters and setters allow for more complicated data access than simple attribute access. For example, when you are setting a class member, sometimes you need a flag indicating where you would like to force this operation even if something doesn't look perfect. While it is not obvious how to augment a direct member access like foo.num = num
, You can easily augment your traditional setter with an additional force
parameter:
def Foo:
def set_num(self, num, force=False):
...
Traditional getters and setters make it explicit that a class member access is through a method. This means:
What you get as the result may not be the same as what is exactly stored within that class.
Even if the access looks like a simple attribute access, the performance can vary greatly from that.
Unless your class users expect a @property
hiding behind every attribute access statement, making such things explicit can help minimize your class users surprises.
As mentioned by @NeilenMarais and in this post, extending traditional getters and setters in subclasses is easier than extending properties.
Traditional getters and setters have been widely used for a long time in different languages. If you have people from different backgrounds in your team, they look more familiar than @property
. Also, as your project grows, if you may need to migrate from Python to another language that doesn't have @property
, using traditional getters and setters would make the migration smoother.
Neither @property
nor traditional getters and setters makes the class member private, even if you use double underscore before its name:
class Foo:
def __init__(self):
self.__num = 0
@property
def num(self):
return self.__num
@num.setter
def num(self, num):
self.__num = num
def get_num(self):
return self.__num
def set_num(self, num):
self.__num = num
foo = Foo()
print(foo.num) # output: 0
print(foo.get_num()) # output: 0
print(foo._Foo__num) # output: 0