My solution was to add:
ctlUpdatePanel.Update();
after binding control after postback. it was in updatepanel with UpdateMode="Conditional" attribute.
Well I don't convert bytes to hex often so I have to say I don't know if there is a better way then this, but here is a way to do it.
StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
sb.Append(b.ToString("X2"));
string hexString = sb.ToString();
None of answered method solve the problem which log4j.properties
file is not found for non-maven jsf web project in NetBeans. So the answer is:
resources
in project root folder (outermost folder).Dlog4j.configuration=resources/log4j.properties
I wrote special pattern in log4j file to check whether log4j is used my file:
# Root Logger Option
log4j.rootLogger=INFO, console
# Redirect Log Messages To Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} xxxx (%F:%L) - %m%n
I checked it because if you use BasicConfigurator.configure();
in your code in log4j use predefined pattern.
Following function will help you to add,update and delete parameters to or from URL.
//example1and
var myURL = '/search';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
//example2
var myURL = '/search?category=mobile';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
//example3
var myURL = '/search?location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
//example4
var myURL = '/search?category=mobile&location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
//example5
var myURL = 'https://example.com/search?location=texas#fragment';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california#fragment
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york#fragment
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search#fragment
Here is the function.
function updateUrl(url,key,value){
if(value!==undefined){
value = encodeURI(value);
}
var hashIndex = url.indexOf("#")|0;
if (hashIndex === -1) hashIndex = url.length|0;
var urls = url.substring(0, hashIndex).split('?');
var baseUrl = urls[0];
var parameters = '';
var outPara = {};
if(urls.length>1){
parameters = urls[1];
}
if(parameters!==''){
parameters = parameters.split('&');
for(k in parameters){
var keyVal = parameters[k];
keyVal = keyVal.split('=');
var ekey = keyVal[0];
var evalue = '';
if(keyVal.length>1){
evalue = keyVal[1];
}
outPara[ekey] = evalue;
}
}
if(value!==undefined){
outPara[key] = value;
}else{
delete outPara[key];
}
parameters = [];
for(var k in outPara){
parameters.push(k + '=' + outPara[k]);
}
var finalUrl = baseUrl;
if(parameters.length>0){
finalUrl += '?' + parameters.join('&');
}
return finalUrl + url.substring(hashIndex);
}
function extractSummary(iCalContent) {
var rx = /\nSUMMARY:(.*)\n/g;
var arr = rx.exec(iCalContent);
return arr[1];
}
You need these changes:
Put the *
inside the parenthesis as
suggested above. Otherwise your matching
group will contain only one
character.
Get rid of the ^
and $
. With the global option they match on start and end of the full string, rather than on start and end of lines. Match on explicit newlines instead.
I suppose you want the matching group (what's
inside the parenthesis) rather than
the full array? arr[0]
is
the full match ("\nSUMMARY:..."
) and
the next indexes contain the group
matches.
String.match(regexp) is supposed to return an array with the matches. In my browser it doesn't (Safari on Mac returns only the full match, not the groups), but Regexp.exec(string) works.
You should not rely on a hash code being equal to a specific value. Just that it will return consistent results within the same execution. The API docs say the following :
The general contract of hashCode is:
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
EDIT Since the javadoc for String.hashCode() specifies how a String's hash code is computed, any violation of this would violate the public API specification.
Short and sweet.
[].reduce($('.x'), function(i,v) {return i+v.outerHTML}, '')
or event more sweet with help of arrow functions
[].reduce.call($('.x'), (i,v) => i+v.outerHTML, '')
or without jQuery at all
[].reduce.call(document.querySelectorAll('.x'), (i,v) => i+v.outerHTML, '')
or if you don't like this approach, check that
$('.x').get().reduce((i,v) => i+v.outerHTML, '')
Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"
Then with one simple $text1 = file_get_contents('text.txt');
command have your text with not a single problem.
I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.
Here is the Pipe being called in an *ngFor directive,
<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
Hello {{item.first}} !
</div>
Here is the Pipe,
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
transform(myobjects: Array<object>, args?: Array<object>): any {
if (args && Array.isArray(myobjects)) {
// copy all objects of original array into new array of objects
var returnobjects = myobjects;
// args are the compare oprators provided in the *ngFor directive
args.forEach(function (filterobj) {
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
// return new array of objects to *ngFor directive
return returnobjects;
}
}
}
And here is the Component containing the object to filter,
import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
items = [{ title: "mr", first: "john", last: "jones" }
,{ title: "mr", first: "adrian", last: "jacobs" }
,{ title: "mr", first: "lou", last: "jones" }
,{ title: "ms", first: "linda", last: "hamilton" }
];
}
GitHub Example: Fork a working copy of this example here
*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.
Happy Coding :-)
The simplest solution is to use something like boost::filesystem
. If
for some reason this isn't an option...
Doing this correctly will require some system dependent code: under
Windows, either '\\'
or '/'
can be a path separator; under Unix,
only '/'
works, and under other systems, who knows. The obvious
solution would be something like:
std::string
basename( std::string const& pathname )
{
return std::string(
std::find_if( pathname.rbegin(), pathname.rend(),
MatchPathSeparator() ).base(),
pathname.end() );
}
, with MatchPathSeparator
being defined in a system dependent header
as either:
struct MatchPathSeparator
{
bool operator()( char ch ) const
{
return ch == '/';
}
};
for Unix, or:
struct MatchPathSeparator
{
bool operator()( char ch ) const
{
return ch == '\\' || ch == '/';
}
};
for Windows (or something still different for some other unknown system).
EDIT: I missed the fact that he also wanted to suppress the extention. For that, more of the same:
std::string
removeExtension( std::string const& filename )
{
std::string::const_reverse_iterator
pivot
= std::find( filename.rbegin(), filename.rend(), '.' );
return pivot == filename.rend()
? filename
: std::string( filename.begin(), pivot.base() - 1 );
}
The code is a little bit more complex, because in this case, the base of
the reverse iterator is on the wrong side of where we want to cut.
(Remember that the base of a reverse iterator is one behind the
character the iterator points to.) And even this is a little dubious: I
don't like the fact that it can return an empty string, for example.
(If the only '.'
is the first character of the filename, I'd argue
that you should return the full filename. This would require a little
bit of extra code to catch the special case.)
}
I have an idea to use value of id()
in logging.
It's cheap to get and it's quite short.
In my case I use tornado and id()
would like to have an anchor to group messages scattered and mixed over file by web socket.
I think what you want is this:
last_list=[]
if p.last_name != None and p.last_name != "":
last_list.append(p.last_name)
print last_list
Your current if statement:
if p.last_name == None or p.last_name == "":
pass
Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.
Also, it looks like your statement pan_list.append(p.last)
is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.
Imagine that this is your Json response
{"Visit":{"VisitId":8,"Description":"visit8"}}
This is how you parse the response and access the values
Ext.Ajax.request({
headers: {
'Content-Type': 'application/json'
},
url: 'api/fullvisit/getfullvisit/' + visitId,
method: 'GET',
dataType: 'json',
success: function (response, request) {
obj = JSON.parse(response.responseText);
alert(obj.Visit.VisitId);
}
});
This will alert the VisitId field
Brando ZWZ provides some great answers to handling this situation.
Re: Same navbar on multiple pages Aug 21, 2018 10:13 AM|LINK
As far as I know, there are multiple solution.
For example:
The Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar).
Then we could directly load it from the jquery without writing a lot of codes.
Like this:
<!--Navigation bar-->
<div id="nav-placeholder">
</div>
<script>
$(function(){
$("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->
Solution2:
You could use JavaScript code to generate the whole nav bar.
Like this:
Javascript code:
$(function () {
var bar = '';
bar += '<nav class="navbar navbar-default" role="navigation">';
bar += '<div class="container-fluid">';
bar += '<div>';
bar += '<ul class="nav navbar-nav">';
bar += '<li id="home"><a href="home.html">Home</a></li>';
bar += '<li id="index"><a href="index.html">Index</a></li>';
bar += '<li id="about"><a href="about.html">About</a></li>';
bar += '</ul>';
bar += '</div>';
bar += '</div>';
bar += '</nav>';
$("#main-bar").html(bar);
var id = getValueByName("id");
$("#" + id).addClass("active");
});
function getValueByName(name) {
var url = document.getElementById('nav-bar').getAttribute('src');
var param = new Array();
if (url.indexOf("?") != -1) {
var source = url.split("?")[1];
items = source.split("&");
for (var i = 0; i < items.length; i++) {
var item = items[i];
var parameters = item.split("=");
if (parameters[0] == "id") {
return parameters[1];
}
}
}
}
Html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="main-bar"></div>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<%--add this line to generate the nav bar--%>
<script src="../assets/js/nav-bar.js?id=index" id="nav-bar"></script>
</body>
</html>
https://forums.asp.net/t/2145711.aspx?Same+navbar+on+multiple+pages
I just had to play with the divo's ConsoleSpinner
class. Mine is nowhere near as concise, but it just didn't sit well with me that users of that class have to write their own while(true)
loop. I'm shooting for an experience more like this:
static void Main(string[] args)
{
Console.Write("Working....");
ConsoleSpinner spin = new ConsoleSpinner();
spin.Start();
// Do some work...
spin.Stop();
}
And I realized it with the code below. Since I don't want my Start()
method to block, I don't want the user to have to worry about writing a while(spinFlag)
-like loop, and I want to allow multiple spinners at the same time I had to spawn a separate thread to handle the spinning. And that means the code has to be a lot more complicated.
Also, I haven't done that much multi-threading so it's possible (likely even) that I've left a subtle bug or three in there. But it seems to work pretty well so far:
public class ConsoleSpinner : IDisposable
{
public ConsoleSpinner()
{
CursorLeft = Console.CursorLeft;
CursorTop = Console.CursorTop;
}
public ConsoleSpinner(bool start)
: this()
{
if (start) Start();
}
public void Start()
{
// prevent two conflicting Start() calls ot the same instance
lock (instanceLocker)
{
if (!running )
{
running = true;
turner = new Thread(Turn);
turner.Start();
}
}
}
public void StartHere()
{
SetPosition();
Start();
}
public void Stop()
{
lock (instanceLocker)
{
if (!running) return;
running = false;
if (! turner.Join(250))
turner.Abort();
}
}
public void SetPosition()
{
SetPosition(Console.CursorLeft, Console.CursorTop);
}
public void SetPosition(int left, int top)
{
bool wasRunning;
//prevent other start/stops during move
lock (instanceLocker)
{
wasRunning = running;
Stop();
CursorLeft = left;
CursorTop = top;
if (wasRunning) Start();
}
}
public bool IsSpinning { get { return running;} }
/* --- PRIVATE --- */
private int counter=-1;
private Thread turner;
private bool running = false;
private int rate = 100;
private int CursorLeft;
private int CursorTop;
private Object instanceLocker = new Object();
private static Object console = new Object();
private void Turn()
{
while (running)
{
counter++;
// prevent two instances from overlapping cursor position updates
// weird things can still happen if the main ui thread moves the cursor during an update and context switch
lock (console)
{
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
switch (counter)
{
case 0: Console.Write("/"); break;
case 1: Console.Write("-"); break;
case 2: Console.Write("\\"); break;
case 3: Console.Write("|"); counter = -1; break;
}
Console.SetCursorPosition(OldLeft, OldTop);
}
Thread.Sleep(rate);
}
lock (console)
{ // clean up
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
Console.Write(' ');
Console.SetCursorPosition(OldLeft, OldTop);
}
}
public void Dispose()
{
Stop();
}
}
It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?
But look at this, a well-formed XML document:
<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>
The root of this document has three children: a processing instruction, a comment, and an element.
So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:
<xsl:template match="/comment()"/>
Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*
.
For Swift 4.0, this got easier:
let defaults = UserDefaults.standard
//Set
defaults.set(passwordTextField.text, forKey: "Password")
//Get
let myPassword = defaults.string(forKey: "Password")
This is what worked for me...
import cv2
import numpy as np
#Created an image (really an ndarray) with three channels
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)
#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255
#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)
#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image
#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])
#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
You are using incorrect overload. You should use this overload
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
And the correct code would be
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
Note that extra parameter at the end.
For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object
overload that you are trying to use.
Given an answer as high voted and views. I did find the answer with mixed of here and other links.
I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)
//css
.disabled{
pointer-events:none;
opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done
So rather than write long code, I found an interesting solution via CSS.
$(document).ready(function () {_x000D_
var PatientId ; _x000D_
//var PatientId =1; //remove to test enable i.e. patient selected_x000D_
if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {_x000D_
console.log(PatientId);_x000D_
$("#dvHeaderSubMenu a").each(function () { _x000D_
$(this).addClass('disabled');_x000D_
}); _x000D_
return;_x000D_
}_x000D_
})
_x000D_
.disabled{_x000D_
pointer-events:none;_x000D_
opacity:0.4;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dvHeaderSubMenu">_x000D_
<ul class="m-nav m-nav--inline pull-right nav-sub">_x000D_
<li class="m-nav__item">_x000D_
<a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon fa fa-tachometer"></i>_x000D_
Overview_x000D_
</a>_x000D_
</li>_x000D_
_x000D_
<li class="m-nav__item active">_x000D_
<a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon fa fa-user"></i>_x000D_
Personal_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">_x000D_
<a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-medical-8"></i>_x000D_
Insurance Claim_x000D_
</a>_x000D_
<div class="m-dropdown__wrapper">_x000D_
<span class="m-dropdown__arrow m-dropdown__arrow--left"></span>_x000D_
_x000D_
<ul class="m-nav">_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon flaticon-toothbrush-1"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Primary_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-interface"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Secondary_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-healthy"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Medical_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
_x000D_
</li>_x000D_
</ul> _x000D_
</div>
_x000D_
A "technical manager" who had formerly been a coder introduced the following wonderful macros into our C++ project because he thought that checking for NULL
values in DOM parsing routines was just too much work:
TRYSEGV
CATCHSEGV
Under the covers, these used setjmp
, longjmp
, and a signal handler for SIGSEGV
to emulate the ability to "catch" a segfault.
Of course, nothing in the code reset the jump pointed once the code had exited the scope of the original TRYSEGV
macro invocation, so any segfault in the code would return to the (now invalid) jump_env
pointer.
The code would immediately die there, but not before destroying the program stack and rendering debugging more or less pointless.
UPDATED It works fine in my case:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)
Just changed in 2020. Works fine for me.
What you want is %.2f
, not 2%f
.
Also, you might want to replace your %d
with a %f
;)
#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}
This will output:
When this number: 94.945600 is assigned to 2 dp, it will be: 94.95
See here for a full description of the printf formatting options: printf
export
in sh
and related shells (such as bash
), marks an environment variable to be exported to child-processes, so that the child inherits them.
The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.
One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.
Here is a nice summary table from cppreference.com:
Here, insertion refers to any method which adds one or more elements to the container and erasure refers to any method which removes one or more elements from the container.
&& is a short circuit operator whereas & is a AND operator.
Try this.
String s = null;
boolean b = false & s.isEmpty(); // NullPointerException
boolean sb = false && s.isEmpty(); // sb is false
You hide Bootstrap modals with:
$('#modal').modal('hide');
Saying $().hide()
makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.
May be you can find answer here? Equivalent of double-clickable .sh and .bat on Mac?
Usually you can create bash script for Mac OS, where you put similar commands as in batch file. For your case create bash file and put same command, but change back-slashes with regular ones.
Your file will look something like:
#! /bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar;./supportlibraries/Framework_DataTable.jar;./supportlibraries/Framework_Reporting.jar;./supportlibraries/Framework_Utilities.jar;./supportlibraries/poi-3.8-20120326.jar;PATH_TO_YOUR_SELENIUM_SERVER_FOLDER/selenium-server-standalone-2.19.0.jar" allocator.testTrack
Change folders in path above to relevant one.
Then make this script executable: open terminal and navigate to folder with your script. Then change read-write-execute rights for this file running command:
chmod 755 scriptname.sh
Then you can run it like any other regular script: ./scriptname.sh
or you can run it passing file to bash:
bash scriptname.sh
To help other bug-hunters. I had this error because the function didn't exist.
I had a spelling error.
It seems that your configuration is using the print
option for numpy.seterr
:
>>> import numpy as np
>>> np.array([1])/0 #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0 #'print' mode
Warning: divide by zero encountered in divide
array([0])
This means that the warning you see is not a real warning, but it's just some characters printed to stdout
(see the documentation for seterr
). If you want to catch it you can:
numpy.seterr(all='raise')
which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.numpy.seterr(all='warn')
, which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.Once you actually have a warning, you can use the warnings
module to control how the warnings should be treated:
>>> import warnings
>>>
>>> warnings.filterwarnings('error')
>>>
>>> try:
... warnings.warn(Warning())
... except Warning:
... print 'Warning was raised as an exception!'
...
Warning was raised as an exception!
Read carefully the documentation for filterwarnings
since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings
which is a context manager which automatically resets the original filterwarnings
function:
>>> import warnings
>>> with warnings.catch_warnings():
... warnings.filterwarnings('error')
... try:
... warnings.warn(Warning())
... except Warning: print 'Raised!'
...
Raised!
>>> try:
... warnings.warn(Warning())
... except Warning: print 'Not raised!'
...
__main__:2: Warning:
may be you could add a attribute to your EditText like this:
android:imeOptions="actionSearch"
I installed it on macOS and had to:
cd /Applications/Postgres.app/Contents/Versions/9.5/bin
createuser -U postgres -s YOURUSERNAME
createdb YOURUSERNAME
Here's the source: https://github.com/PostgresApp/PostgresApp/issues/313#issuecomment-192461641
Just use the vector constructor.
std::vector<int> data();
// Load Z elements into data so that Z > Y > X
std::vector<int> sub(&data[100000],&data[101000]);
To embed this in your script, you can do it like this:
Write-Output $server.name | Out-File '(Your Path)\Servers.txt' -Append
That should do the trick.
Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:
public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;
groupedCustomerList =
from User in userList
group User by User.GroupID into newGroup
orderby newGroup.Key
select newGroup;
Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.
Enums are just classes in disguise, so for the most part, anything you can do with a class you can do with an enum.
I cannot think of a reason that an enum should not be able to implement an interface, at the same time I cannot think of a good reason for them to either.
I would say once you start adding thing like interfaces, or method to an enum you should really consider making it a class instead. Of course I am sure there are valid cases for doing non-traditional enum things, and since the limit would be an artificial one, I am in favour of letting people do what they want there.
That method must be called on the Dispose
method of objects that implements the IDisposable
, in this way the GC wouldn't call the finalizer another time if someones calls the Dispose
method.
I purge derivedData often enough that I have an alias for it. It can fix build problems. I have the following in /Users/Myusername/.bash_profile
alias purgeallbuilds='rm -rf ~/Library/Developer/Xcode/DerivedData/*'
Then in terminal, I type purgeallbuilds, and all subfolders of DerivedData are deleted.
Minimal example, writing directly to a file:
import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))
or safely opening / closing:
import json
with open(filename, 'wb') as outfile:
json.dump(data, outfile)
with open(filename) as infile:
data = json.load(infile)
If you want to save it in a string instead of a file:
import json
json_str = json.dumps(data)
data = json.loads(json_str)
Steps to Remove app from App Store
Ternary Operator always returns a value. So in situation when you want some output value from result and there are only 2 conditions always better to use ternary operator. Use if-else if any of the above mentioned conditions are not true.
I was trying to access my web pages on specific port number and tried much things, but I've found the port was filtered by firewall. Just added a bypass rule and everything was done.
Maybe help someone!
There needs to be some type of backend framework to send the email. This can be done via PHP/ASP.NET, or with the local mail client. If you want the user to see nothing, the best way is to tap into those by an AJAX call to a separate send_email file.
You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.
Forking is nothing more than a clone on the GitHub server side:
You keep a fork in sync with the original project by:
The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.
The goal is really to allow collaboration even though direct participation is not always possible.
The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.
The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream
(rebase your work on top of new commits from upstream), and then git push --force origin
, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.
See also:
This is work for me.
spinner.setSelection(spinner_adapter.getPosition(selected_value)+1);
I don't think you can set that option there. You will have to use jQuery.ajax() with the appropriate parameters (basically getJSON just wraps that call into an easier API, as well).
I faced the same issue, mine is even more complicated.
Admin will upload audio and pdf files into storage:
audios/season1, season2.../class1, class 2/.mp3 files
books/.pdf files
Android app needs to get the list of sub folders and files.
The solution is catching the upload event on storage and create the same structure on firestore using cloud function.
Step 1: Create manually 'storage' collection and 'audios/books' doc on firestore
Step 2: Setup cloud function
Might take around 15 mins: https://www.youtube.com/watch?v=DYfP-UIKxH0&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=1
Step 3: Catch upload event using cloud function
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
const path = require('path');
export const onFileUpload = functions.storage.object().onFinalize(async (object) => {
let filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
if (metageneration !== "1") return;
// Get the file name.
const fileName = path.basename(filePath);
filePath = filePath.substring(0, filePath.length - 1);
console.log('contentType ' + contentType);
console.log('fileName ' + fileName);
console.log('filePath ' + filePath);
console.log('path.dirname(filePath) ' + path.dirname(filePath));
filePath = path.dirname(filePath);
const pathArray = filePath.split("/");
let ref = '';
for (const item of pathArray) {
if (ref.length === 0) {
ref = item;
}
else {
ref = ref.concat('/sub/').concat(item);
}
}
ref = 'storage/'.concat(ref).concat('/sub')
admin.firestore().collection(ref).doc(fileName).create({})
.then(result => {console.log('onFileUpload:updated')})
.catch(error => {
console.log(error);
});
});
Step 4: Retrieve list of folders/files on Android app using firestore
private static final String STORAGE_DOC = "storage/";
public static void getMediaCollection(String path, OnCompleteListener onCompleteListener) {
String[] pathArray = path.split("/");
String doc = null;
for (String item : pathArray) {
if (TextUtils.isEmpty(doc)) doc = STORAGE_DOC.concat(item);
else doc = doc.concat("/sub/").concat(item);
}
doc = doc.concat("/sub");
getFirestore().collection(doc).get().addOnCompleteListener(onCompleteListener);
}
Step 5: Get download url
public static void downloadMediaFile(String path, OnCompleteListener<Uri> onCompleteListener) {
getStorage().getReference().child(path).getDownloadUrl().addOnCompleteListener(onCompleteListener);
}
Note
We have to put "sub" collection to each item since firestore doesn't support to retrieve the list of collection.
It took me 3 days to find out the solution, hopefully will take you 3 hours at most.
Cheers.
mvn clean package -DpropEnv=PROD
Then using like this in POM.xml
<properties>
<myproperty>${propEnv}</myproperty>
</properties>
Make sure you put the onSubmit attribute on the form not the button in case you have a from.
<form onSubmit={e => e.preventDefault()}>
<button onClick={this.handleClick}>Click Me</button>
</form>
Make sure to change the button onClick attribute to your custom function.
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
position: static
, which means the element is not positioned and occurs where it normally would in the document. Normally you wouldn't specify this unless you needed to override a positioning that had been previously set.position: relative
, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.position: absolute
, the element is removed from the document and placed exactly where you tell it to go.So in regard to your question you should position the containing block relative, i.e:
#parent {
position: relative;
}
And the child element you should position absolute to the parent element like this:
#child {
position: absolute;
}
There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).
I think you still need the primary key property in the OtherInfo class.
@Entity
public class OtherInfo {
@Id
public int id;
@OneToOne(mappedBy="otherInfo")
public Person person;
rest of attributes ...
}
Also, you may need to add the @PrimaryKeyJoinColumn annotation to the other side of the mapping. I know that Hibernate uses this by default. But then I haven't used JPA annotations, which seem to require you to specify how the association wokrs.
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
I had the same issue on Linux with Jupyter.
To solve it I've added the dot library to python sys.path
First: check if dot
is installed,
Then:
find his path whereis dot
-> /local/notebook/miniconda2/envs/ik2/bin/dot
Finally in python script : sys.path.append("/local/notebook/miniconda2/envs/ik2/bin/dot")
This is the Scala solution if anyone needs it
def anUnsafeOkHttpClient(): OkHttpClient = {
val manager: TrustManager =
new X509TrustManager() {
override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
override def getAcceptedIssuers = Seq.empty[X509Certificate].toArray
}
val trustAllCertificates = Seq(manager).toArray
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCertificates, new java.security.SecureRandom())
val sslSocketFactory = sslContext.getSocketFactory()
val okBuilder = new OkHttpClient.Builder()
okBuilder.sslSocketFactory(sslSocketFactory, trustAllCertificates(0).asInstanceOf[X509TrustManager])
okBuilder.hostnameVerifier(new NoopHostnameVerifier)
okBuilder.build()
}
For me, it works,
git push -f heroku otherBranch:master
The -f (force flag) is recommended in order to avoid conflicts with other developers’ pushes. Since you are not using Git for your revision control, but as a transport only, using the force flag is a reasonable practice.
source :- offical docs
Bootstrap4:
Comes with .no-gutters
out of the box.
source: https://github.com/twbs/bootstrap/pull/21211/files
Bootstrap3:
Requires custom CSS.
Stylesheet:
.row.no-gutters {
margin-right: 0;
margin-left: 0;
& > [class^="col-"],
& > [class*=" col-"] {
padding-right: 0;
padding-left: 0;
}
}
Then to use:
<div class="row no-gutters">
<div class="col-xs-4">...</div>
<div class="col-xs-4">...</div>
<div class="col-xs-4">...</div>
</div>
It will:
If you are aiming for maximum browser support, modern approach is to place button in a div with display:flex;
and flex-direction:row;
The same trick will work for height with flex-direction:column;
or both height and width(will require 2 divs)
"For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."
So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:
SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'
This is what i use:
html:
<h6><span class="horizontal-line">GET IN</span> TOUCH</h6>
css:
.horizontal-line { border-bottom: 2px solid #FF0000; padding-bottom: 5px; }
Steps for upgrading to PHP7 on CentOS 6 system. Taken from install-php-7-in-centos-6
To install latest PHP 7, you need to add EPEL and Remi repository to your CentOS 6 system
yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-6.rpm
Now install yum-utils, a group of useful tools that enhance yum’s default package management features
yum install yum-utils
In this step, you need to enable Remi repository using yum-config-manager utility, as the default repository for installing PHP.
yum-config-manager --enable remi-php70
If you want to install PHP 7.1 or PHP 7.2 on CentOS 6, just enable it as shown.
yum-config-manager --enable remi-php71
yum-config-manager --enable remi-php72
Then finally install PHP 7 on CentOS 6 with all necessary PHP modules using the following command.
yum install php php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-zip php-fileinfo
Double check the installed version of PHP on your system as follows.
php -V
render() {
window.scrollTo(0, 0)
...
}
Can be a simple solution in case the props are not changed and componentDidUpdate() not firing.
For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:
TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")
After inserting the value you can update the value in the database with double quotes or single quotes:
update table TableName replace(Dstring, "QQ", "\"")
About REST return codes: it is wrong to mix HTTP protocol codes and REST results.
However, I saw many implementations mixing them, and many developers may not agree with me.
HTTP return codes are related to the HTTP Request
itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.
For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:
"403 Forbidden/Access Denied" may mean:
And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...
From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.
If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the http server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as http result, right?
Instead of this you may return 200 HTTP code and simply a JSON with an empty array/object, or to use a bool result/success flag to inform about the performed operation status.
Also, some internet providers may intercept your requests and return you a 404 http code. This does not means that your data are not found, but it's something wrong at transport level.
From Wiki:
In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".
Web container also known as a Servlet container is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.
I think you're confused because you're running from the REPL, which automatically prints out the value returned when you call a function. In that case, you do get identical output whether you have a function that creates a value, prints it, and throws it away, or you have a function that creates a value and returns it, letting the REPL print it.
However, these are very much not the same thing, as you will realize when you call autoparts with another function that wants to do something with the value that autoparts creates.
When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics
object outside the paint()
/paintComponent()
/etc. methods.
However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics()
method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage
instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel
's paintComponent()
, you simply need to draw the BufferedImage
instance unto the JPanel
. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.
You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:
namespace X
{
namespace Y
{
class A;
void func(A* a) { ... } // incomplete type here!
}
}
...but, in class A was defined like this:
namespace X
{
class A { ... };
}
Thus, A was defined as X::A
, but I was using it as X::Y::A
.
The fix obviously is to move the forward reference to its proper place like so:
namespace X
{
class A;
namespace Y
{
void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
}
}
You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
The value of 0xDEADBEEF has three practical benefits, mostly for older systems. Old assembler/C hacks, like me, would use it to fill unallocated memory to coax out memory issues. Also, it's a pun of the slang term "dead meat". The programmer is dead meat if DEADBEEF winds up in his pointers. I congratulate the guy who first thought of using the value DEADBEEF. It's clever in many ways.
As for practical reasons, firstly, it's more noticeable in a hex memory dump because it actually spells words as opposed to random hex values.
Secondly, if the value winds up in a pointer, it's more likely to induce a memory out-of-range fault. An address of DEADBEEF was out of the address range of systems (we're talking last century systems now) regardless of the system's endian.
Thirdly, it is more likely to induce a fault on systems that require even boundary pointer values for accessing 16/32/64-bit data. The value is more likely to fault because both of the 16 bit values (DEAD, BEEF) are odd.
1) To answer your question:
String s="Java";
System.out.println(s.length());
var swap = function () {
var divs = document.getElementsByTagName('div');
var div1 = divs[0];
var div2 = divs[1];
var div3 = divs[2];
div3.parentNode.insertBefore(div1, div3);
div1.parentNode.insertBefore(div3, div2);
};
This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.
What standards peculiarities does it rely on?
insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.
You can use the top margin-top and adjust the text or you could also use padding-top both would have similar visual effect in your case but actually both behave a bit differently.
I'd use RestSharp - https://github.com/restsharp/RestSharp
Create class to deserialize to:
public class MyObject {
public string Id { get; set; }
public string Text { get; set; }
...
}
And the code to get that object:
RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");
// The above code will make a request URL of
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need
var response = client.Execute<MyObject>(request);
MyObject obj = response.Data;
Check out http://restsharp.org/ to get started.
I haven’t actually done anything with font-face
, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.
The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.
Does Firefox download the font when you actually use it in a font
declaration? (e.g. h1 { font: 'DejaVu Serif';
)?
There really seems no way for fooling the <a href= ..
into a POST method. However, given that you have access to CSS of a page, this can be substituted by using a form instead.
Unfortunately, the obvious way of just styling the button in CSS as an anchor tag, is not cross-browser compatible, since different browsers treat <button value= ...
differently.
Incorrect:
<form action='actbusy.php' method='post'>
<button type='submit' name='parameter' value='One'>Two</button>
</form>
The above example will be showing 'Two' and transmit 'parameter:One' in FireFox, while it will show 'One' and transmit also 'parameter:One' in IE8.
The way around is to use hidden input field(s) for delivering data and the button just for submitting it.
<form action='actbusy.php' method='post'>
<input class=hidden name='parameter' value='blaah'>
<button type='submit' name='delete' value='Delete'>Delete</button>
</form>
Note, that this method has a side effect that besides 'parameter:blaah' it will also deliver 'delete:Delete' as surplus parameters in POST.
You want to keep for a button the value attribute and button label between tags both the same ('Delete' on this case), since (as stated above) some browsers will display one and some display another as a button label.
You do not need to do this. Here is how to create a co-variance method:
http://www.youtube.com/watch?v=RqAfC4JXd4A
Alternatively you can use statistical analysis package that Excel has.
eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`
echo $python_include_path # prints /home/<usr>/anaconda3/include/python3.6m" in my case
python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'
It's launching a python script that
eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`
It's executing in the current bash instance the output from the python script. In my case, its executing:
python_include_path=/home/<usr>/anaconda3/include/python3.6m
In other words, it's setting the environment variable "python_include_path" with that path for this shell instance.
Inspired by: http://blog.tintoy.io/2017/06/exporting-environment-variables-from-python-to-bash/
This doesn't necessarily address the question but if you are using Mac OS X then you can probably use lldb
LLDB Homepage . It's very similar to gdb
and even provides a guide to using commands that you would use on gdb
.
Use find for that:
find . -name "foo*"
find
needs a starting point, and the .
(dot) points to the current directory.
FYI, the list of operators (containing like and all others) is in code:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
);
disclaimer:
Joel Larson's answer is correct. Got my upvote.
I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.
I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.
The SQL*Plus® User's Guide and Reference gives an example:
sqlplus hr@\"sales-server:1521/sales.us.acme.com\"
Pay attention to two important points:
I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:
SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Please try the below code:
<script>
const games = {
"Fifa": "232",
"Minecraft": "476",
"Call of Duty": "182"
};
Object.keys(games).forEach((item, index, array) => {
var msg = item+' '+games[item];
console.log(msg);
});
You could try this: df2 = pd.DataFrame.from_dict({'a':a,'b':b}, orient = 'index')
You can do it like this:
SELECT * FROM ... WHERE name LIKE 'someone'
(It's not the solution, but in some cases is very convenient)
"The LIKE operator does a pattern matching comparison. The operand to the right contains the pattern, the left hand operand contains the string to match against the pattern. A percent symbol ("%") in the pattern matches any sequence of zero or more characters in the string. An underscore ("_") in the pattern matches any single character in the string. Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). (A bug: SQLite only understands upper/lower case for ASCII characters. The LIKE operator is case sensitive for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE.)."
A POCO follows the rules of OOP. It should (but doesn't have to) have state and behavior. POCO comes from POJO, coined by Martin Fowler [anecdote here]. He used the term POJO as a way to make it more sexy to reject the framework heavy EJB implementations. POCO should be used in the same context in .Net. Don't let frameworks dictate your object's design.
A DTO's only purpose is to transfer state, and should have no behavior. See Martin Fowler's explanation of a DTO for an example of the use of this pattern.
Here's the difference: POCO describes an approach to programming (good old fashioned object oriented programming), where DTO is a pattern that is used to "transfer data" using objects.
While you can treat POCOs like DTOs, you run the risk of creating an anemic domain model if you do so. Additionally, there's a mismatch in structure, since DTOs should be designed to transfer data, not to represent the true structure of the business domain. The result of this is that DTOs tend to be more flat than your actual domain.
In a domain of any reasonable complexity, you're almost always better off creating separate domain POCOs and translating them to DTOs. DDD (domain driven design) defines the anti-corruption layer (another link here, but best thing to do is buy the book), which is a good structure that makes the segregation clear.
If you want to show the rating bar in small size, then just copy and paste this code in your project.
<RatingBar
android:id="@+id/MyRating"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/getRating"
android:isIndicator="true"
android:numStars="5"
android:stepSize="0.1" />
.htaccess is a hidden file, so you must set all files as visible in your ftp.
I suggest you return your permalink structure to default ( ?p=ID ) so you ensure that .htaccess is the problem.
After that, you could simply set "month and name" structure again, and see if it works.
PS: Have you upgraded to 3.1? I've seen some people with plugin issues in this case.
You can also use long.TryParse
and long.Parse
.
long l1;
l1 = long.Parse("1100.25");
//or
long.TryParse("1100.25", out l1);
A BLOB
can be 65535 bytes (64 KB) maximum.
If you need more consider using:
a MEDIUMBLOB
for 16777215 bytes (16 MB)
a LONGBLOB
for 4294967295 bytes (4 GB).
See Storage Requirements for String Types for more info.
What you should do, is put CallFunction
into *.cpp file, where you include B.h.
After edit, files will look like:
#pragma once //or other specific to compiler...
using namespace std;
class A
{
public:
void CallFunction ();
};
class B: public A
{
public:
virtual void bFunction()
{
//stuff done here
}
};
#include "B.h"
void A::CallFunction(){
//use B object here...
}
Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).
So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.
And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).
Seems like all these answers involve custom css on top of bootstrap. The answer I am providing utilizes only bootstrap so I hope it comes to use for those that want to limit customizations.
This was tested with Bootstrap V3.3.7
<footer class="navbar-default navbar-fixed-bottom">
<div class="container-fluid">
<div class="row">
<div class="col-xs-offset-5 col-xs-2 text-center">
<p>I am centered text<p>
</div>
<div class="col-xs-5"></div>
</div>
</div>
</footer>
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
Use also this way to represent image in base64 encode format...
find PHP function file_get_content
and next to use function base64_encode
and get result to prepare str as data:" . file_mime_type . " base64_encoded string
. Use it in img src attribute. see following code can I help for you.
// A few settings
$img_file = 'raju.jpg';
// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;
// Echo out a sample image
echo '<img src="'.$src.'">';
try changing the connection port to 8012
open xampp as administrator
Mysql config => my.ini change the port from 3306 to 8012
close and run it again I hope it will work.
Try using ctrl+` to toggles the visibility of the terminal and as a result toggle the focus.
I shamelessly converted Apache Common's toBoolean
to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {_x000D_
if (str == "true") {_x000D_
return true;_x000D_
}_x000D_
if (!str) {_x000D_
return false;_x000D_
}_x000D_
switch (str.length) {_x000D_
case 1: {_x000D_
var ch0 = str.charAt(0);_x000D_
if (ch0 == 'y' || ch0 == 'Y' ||_x000D_
ch0 == 't' || ch0 == 'T' ||_x000D_
ch0 == '1') {_x000D_
return true;_x000D_
}_x000D_
if (ch0 == 'n' || ch0 == 'N' ||_x000D_
ch0 == 'f' || ch0 == 'F' ||_x000D_
ch0 == '0') {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 2: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'n' || ch1 == 'N') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'n' || ch0 == 'N') &&_x000D_
(ch1 == 'o' || ch1 == 'O') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 3: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
if ((ch0 == 'y' || ch0 == 'Y') &&_x000D_
(ch1 == 'e' || ch1 == 'E') &&_x000D_
(ch2 == 's' || ch2 == 'S') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'f' || ch1 == 'F') &&_x000D_
(ch2 == 'f' || ch2 == 'F') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 4: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
if ((ch0 == 't' || ch0 == 'T') &&_x000D_
(ch1 == 'r' || ch1 == 'R') &&_x000D_
(ch2 == 'u' || ch2 == 'U') &&_x000D_
(ch3 == 'e' || ch3 == 'E') ) {_x000D_
return true;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 5: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
var ch4 = str.charAt(4);_x000D_
if ((ch0 == 'f' || ch0 == 'F') &&_x000D_
(ch1 == 'a' || ch1 == 'A') &&_x000D_
(ch2 == 'l' || ch2 == 'L') &&_x000D_
(ch3 == 's' || ch3 == 'S') &&_x000D_
(ch4 == 'e' || ch4 == 'E') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
default:_x000D_
break;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}_x000D_
console.log(toBoolean("yEs")); // true_x000D_
console.log(toBoolean("yES")); // true_x000D_
console.log(toBoolean("no")); // false_x000D_
console.log(toBoolean("NO")); // false_x000D_
console.log(toBoolean("on")); // true_x000D_
console.log(toBoolean("oFf")); // false
_x000D_
Inspect this element, and view the console output.
_x000D_
This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:
span.add-label{
display:none;
}
.item:hover span.align{
display:none;
}
.item:hover span.add-label{
display:block;
}
Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ
I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.
What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.
What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.
There is a missing step in Georg Schölly's second answer, but it works fine then.
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
// added the 's' because time was wasted when I copied and pasted and it failed without the 's' in sortedArrayUsingDescriptors
I know this is an old question, but...
I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:
http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/
I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:
Run the command:
appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']
Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT
and DELETE
verbs). Yay!
You may wonder, why the syntax is valid (but not working as expected):
var func = p => { foo: "bar" }
It's because of JavaScript's label syntax:
So if you transpile the above code to ES5, it should look like:
var func = function (p) {
foo:
"bar"; //obviously no return here!
}
Happened to me on node 13.7.0
and npm 6.13.6
(macOS Mojave).
I had the following as part of my errors:
found X vulnerabilities (Y moderate, Z high)
run `npm audit fix` to fix them, or `npm audit` for details
And running the following fixed the problem:
$ npm audit fix
$ npm install
If you also want to bind closing of infowindow to some event, try something like this
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
windows.push(infowindow)
google.maps.event.addListener(map,'click', function(){
infowindow.close();
});
};
})(marker,content,infowindow));
for Xocde 12.0 beta 5:
preferences > Themes > at the bottom you will see the font family
.
In the repository root, the .git/config
file holds all information about remote repositories and branches. In your example, you should look for something like:
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = server:gitRepo.git
Also, the Git command git remote -v
shows the remote repository name and URL. The "origin" remote repository usually corresponds to the original repository, from which the local copy was cloned.
try this=> numpy.array(r) or numpy.array(yourvariable) followed by the command to compare whatever you wish to.
So another way, which I prefer, is to just split the values, for example:
#/path/to/config.cfg
[Numbers]
first_row = 1,2,4,8,12,24,36,48
Could be loaded like this into a list of strings or integers, as follows:
import configparser
config = configparser.ConfigParser()
config.read('/path/to/config.cfg')
# Load into a list of strings
first_row_strings = config.get('Numbers', 'first_row').split(',')
# Load into a list of integers
first_row_integers = [int(x) for x in config.get('Numbers', 'first_row').split(',')]
This method prevents you from needing to wrap your values in brackets to load as JSON.
It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.
http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html
Data Type Date Type Storage Required
(CLOB) (BLOB)
TINYTEXT TINYBLOB L + 1 bytes, where L < 2**8 (255)
TEXT BLOB L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT MEDIUMBLOB L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT LONGBLOB L + 4 bytes, where L < 2**32 (4 GB)
where L stands for the byte length of a string
The application automatically stops when the last Stage
is closed. At this moment, the stop()
method of your Application
class is called, so you don't need an equivalent to setDefaultCloseOperation()
If you want to stop the application before that, you can call Platform.exit()
, for example in your onCloseRequest
call.
You can have all these information on the javadoc page of Application
: http://docs.oracle.com/javafx/2/api/javafx/application/Application.html
<?php
// connect to database
$conn=mysqli_connect("localhost","user","password","database");
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// sql query
$sql =mysqli_query($conn,"TRUNCATE " . TABLE_NAME);
// Print message
if ($sql === TRUE) {
echo 'data delete successfully';
}
else {
echo 'Error: '. $conn->error;
}
$conn->close();
?>
Here is code snippet which I use to clear a table. Just change $conn info and TABLE_NAME.
Try this:
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos,yPos,width,height);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
[edit]
// With explicit casting
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos, yPos, width, height);
g.fillRect(
(int)r.getX(),
(int)r.getY(),
(int)r.getWidth(),
(int)r.getHeight()
);
}
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
We can use TRUNC function in Oracle DB. Here is an example.
SELECT TRUNC(TO_DATE('01 Jan 2018 08:00:00','DD-MON-YYYY HH24:MI:SS')) FROM DUAL
Output: 1/1/2018
Less accurate but fastest way to get average color of the image with datauri
support:
function get_average_rgb(img) {
var context = document.createElement('canvas').getContext('2d');
if (typeof img == 'string') {
var src = img;
img = new Image;
img.setAttribute('crossOrigin', '');
img.src = src;
}
context.imageSmoothingEnabled = true;
context.drawImage(img, 0, 0, 1, 1);
return context.getImageData(1, 1, 1, 1).data.slice(0,3);
}
Rephrasing one of the answers in this post, instead of using cmd.split(). Try to use:
import shlex
args = shlex.split(cmd)
Then feed args to subprocess.Popen.
Check this doc for more info: https://docs.python.org/2/library/subprocess.html#popen-constructor
I had the same problem with one of my apps, which is how I ended up finding this. In my case, I uploaded two of my apps at the same time, using Xcode 7.1. One of the apps passed through processing within an hour. The other one was still in processing almost 24 hours later. To get past this issue, I created a new archive with an incremented build number, and uploaded it using the application loader. I did not turn off bitcode. The version that I uploaded using the application loader took less than 20 minutes to get through processing, and I've been able to submit my app for review. The version I submitted prior to this is still stuck in processing.
At least in the case of my app, using application loader appears to have solved the issue.
Spring annotations will work fine if you remove enctype="multipart/form-data"
.
@RequestParam(value="txtEmail", required=false)
You can even get the parameters from the request
object .
request.getParameter(paramName);
Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.
Configure the Multi-part resolver if you want to receive enctype="multipart/form-data"
.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="250000"/>
</bean>
Refer the Spring documentation.
This should work
render(){_x000D_
_x000D_
var payments = [];_x000D_
_x000D_
for(let i = 0; i < noGuest; i++){_x000D_
_x000D_
payments.push(_x000D_
<View key = {i}>_x000D_
<View>_x000D_
<TextInput />_x000D_
</View>_x000D_
<View>_x000D_
<TextInput />_x000D_
</View>_x000D_
<View>_x000D_
<TextInput />_x000D_
</View>_x000D_
</View>_x000D_
)_x000D_
}_x000D_
_x000D_
return (_x000D_
<View>_x000D_
<View>_x000D_
<View><Text>No</Text></View>_x000D_
<View><Text>Name</Text></View>_x000D_
<View><Text>Preference</Text></View>_x000D_
</View>_x000D_
_x000D_
{ payments }_x000D_
</View>_x000D_
)_x000D_
}
_x000D_
We finally found an answer of sorts. First, the problem: the table always sizes itself around the content, rather than forcing the content to fit in the table. That limits your options.
We did it by setting the content div to display:none, letting the table size itself, and then in javascript setting the height and width of the content div to the inner height and width of the enclosing td tag. Show the content div. Repeat the process when the window is resized.
The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.
Sub UserForm_Initialize()
ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub
This approach always works for me:
# First of all, delete all broken links. Replace my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs
Taken from:
Why not just use java.text.SimpleDateFormat ?
Date someDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(someDate);
Or see: http://www.tutorialspoint.com/java/java_date_time.htm
I had this error too , and finally this codes worked for me in dot net core 3.1
first install svcutil in command prompt : dotnet tool install --global dotnet-svcutil
Then close command prompt and open it again.
Then create the Reference.cs in command prompt :
dotnet-svcutil http://YourService.com/SayHello.svc
(It needs an enter key and UserName and Password)
Add a folder named Connected Services to project root.
Copy Reference.cs file to Connected Services folder.
Add these 4 lines to Reference.cs after lines where creating BasicHttpBinding and setting MaxBufferSize :
result.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
result.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
result.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
result.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
Use this service in your Controller :
public async Task<string> Get()
{
try
{
var client = new EstelamClient();
client.ClientCredentials.UserName.UserName = "YourUserName";
client.ClientCredentials.UserName.Password = "YourPassword";
var res = await client.EmployeeCheckAsync("service parameters");
return res.ToString();
}
catch (Exception ex)
{
return ex.Message + " ************ stack : " + ex.StackTrace;
}
}
Do not forget install these packages in .cshtml :
<PackageReference Include="System.ServiceModel.Duplex" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Http" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.NetTcp" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Security" Version="4.6.*" />
The '\0'
inside character literals and string literals stands for the character with the code zero. The meaning in C and in Objective C is identical.
To illustrate, you can use \0
in an array initializer to construct an array equivalent to a null-terminated string:
char str1[] = "Hello";
char str2[] = {'H', 'e', 'l', 'l', 'o', '\0'};
In general, you can use \ooo
to represent an ASCII character in octal notation, where o
s stand for up to three octal digits.
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
No, it certainly is not. It is just another variable name. The $()
you're talking about is actually the jQuery core function. The $self
is just a variable. You can even rename it to foo
if you want, this doesn't change things. The $
(and _
) are legal characters in a Javascript identifier.
Why this is done so is often just some code convention or to avoid clashes with reversed keywords. I often use it for $this
as follows:
var $this = $(this);
I suppose imports
import pandas as pd
import numpy as np
First append new row with NaN, NaN,...
at the end of DataFrame (df
).
s1 = df.iloc[0] # copy 1st row to a new Series s1
s1[:] = np.NaN # set all values to NaN
df2 = df.append(s1, ignore_index=True) # add s1 to the end of df
It will create new DF df2. Maybe there is more elegant way but this works.
Now you can shift it:
df2.x2 = df2.x2.shift(1) # shift what you want
Assuming that EXIT_CODE is referring to System . exit
( exit_code ) then you could do
enum ExitCode
{
NORMAL_SHUTDOWN ( 0 ) , EMERGENCY_SHUTDOWN ( 10 ) , OUT_OF_MEMORY ( 20 ) , WHATEVER ( 30 ) ;
private int value ;
ExitCode ( int value )
{
this . value = value ;
}
public void exit ( )
{
System . exit ( value ) ;
}
}
Then you can put the following at appropriate spots in your code
ExitCode . NORMAL_SHUTDOWN . exit ( ) '
There are two scenarios when this exception could occur. One is mentioned by nandeesh. Other scenario is mentioned here: http://blackriver.to/2012/08/android-annoying-exception-unable-to-add-window-is-your-activity-running/
Make sure you handle both of them
While creating the object for the progressbar check the following.
This fails:
dialog = new ProgressDialog(getApplicationContext());
While adding the activities context works..
dialog = new ProgressDialog(MainActivity.this);
Here is a comparison with np.einsum
to show how the indices are projected
np.allclose(np.einsum('ijk,ijk->ijk', a,b), a*b) # True
np.allclose(np.einsum('ijk,ikl->ijl', a,b), a@b) # True
np.allclose(np.einsum('ijk,lkm->ijlm',a,b), a.dot(b)) # True
Choose the project in eclipse - > Select run as -> Choose Java application. This displays a popup forcing you to select something, try searching your class having the main method in the search box. Once you find it, select it and hit ok. This will launch the spring boot application.
I do not have the spring tool suite installed in eclipse yet and still, it works. I hope this helps.
You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.
static private Drawable **scaleDrawable**(Drawable drawable, int width, int height) {
int wi = drawable.getIntrinsicWidth();
int hi = drawable.getIntrinsicHeight();
int dimDiff = Math.abs(wi - width) - Math.abs(hi - height);
float scale = (dimDiff > 0) ? width / (float)wi : height /
(float)hi;
Rect bounds = new Rect(0, 0, (int)(scale * wi), (int)(scale * hi));
drawable.setBounds(bounds);
return drawable;
}
http://www.codeproject.com/Articles/237501/Windows-Phone-NTP-Client is going to work well for Windows Phone .
Adding the relevant code
/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
{
/// <summary>
/// Contains the time returned from the Ntp request
/// </summary>
public class TimeReceivedEventArgs : EventArgs
{
public DateTime CurrentTime { get; internal set; }
}
/// <summary>
/// Subscribe to this event to receive the time acquired by the NTP requests
/// </summary>
public event EventHandler<TimeReceivedEventArgs> TimeReceived;
protected void OnTimeReceived(DateTime time)
{
if (TimeReceived != null)
{
TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });
}
}
/// <summary>
/// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
/// information later and will provide method to allow some one to choose an NTP server.
/// </summary>
public string[] NtpServerList = new string[]
{
"pool.ntp.org ",
"asia.pool.ntp.org",
"europe.pool.ntp.org",
"north-america.pool.ntp.org",
"oceania.pool.ntp.org",
"south-america.pool.ntp.org",
"time-a.nist.gov"
};
string _serverName;
private Socket _socket;
/// <summary>
/// Constructor allowing an NTP server to be specified
/// </summary>
/// <param name="serverName">the name of the NTP server to be used</param>
public NtpClient(string serverName)
{
_serverName = serverName;
}
/// <summary>
///
/// </summary>
public NtpClient()
: this("time-a.nist.gov")
{ }
/// <summary>
/// Begins the network communication required to retrieve the time from the NTP server
/// </summary>
public void RequestTime()
{
byte[] buffer = new byte[48];
buffer[0] = 0x1B;
for (var i = 1; i < buffer.Length; ++i)
buffer[i] = 0;
DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgsConnect.Completed += (o, e) =>
{
if (e.SocketError == SocketError.Success)
{
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgs.Completed +=
new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.UserToken = buffer;
_socket.SendAsync(sArgs);
}
};
_socket.ConnectAsync(sArgsConnect);
}
void sArgs_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
byte[] buffer = (byte[])e.Buffer;
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
sArgs.RemoteEndPoint = e.RemoteEndPoint;
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.Completed += (o, a) =>
{
if (a.SocketError == SocketError.Success)
{
byte[] timeData = a.Buffer;
ulong hTime = 0;
ulong lTime = 0;
for (var i = 40; i <= 43; ++i)
hTime = hTime << 8 | buffer[i];
for (var i = 44; i <= 47; ++i)
lTime = lTime << 8 | buffer[i];
ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);
TimeSpan timeSpan =
TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
var currentTime = new DateTime(1900, 1, 1) + timeSpan;
OnTimeReceived(currentTime);
}
};
_socket.ReceiveAsync(sArgs);
}
}
}
Usage :
public partial class MainPage : PhoneApplicationPage
{
private NtpClient _ntpClient;
public MainPage()
{
InitializeComponent();
_ntpClient = new NtpClient();
_ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);
}
void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();
});
}
private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
{
_ntpClient.RequestTime();
}
}
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
// Regex - Check Singapore valid mobile numbers
public static boolean isSingaporeMobileNo(String str) {
Pattern mobNO = Pattern.compile("^(((0|((\\+)?65([- ])?))|((\\((\\+)?65\\)([- ])?)))?[8-9]\\d{7})?$");
Matcher matcher = mobNO.matcher(str);
if (matcher.find()) {
return true;
} else {
return false;
}
}
Perhaps this information will help you.
var sitePersonel = {};_x000D_
var employees = []_x000D_
sitePersonel.employees = employees;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var firstName = "John";_x000D_
var lastName = "Smith";_x000D_
var employee = {_x000D_
"firstName": firstName,_x000D_
"lastName": lastName_x000D_
}_x000D_
sitePersonel.employees.push(employee);_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var manager = "Jane Doe";_x000D_
sitePersonel.employees[0].manager = manager;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
console.log(JSON.stringify(sitePersonel));
_x000D_
Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary
So my example becomes:
d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)
Here's a category that should do the trick
@interface UIImage(Overlay)
@end
@implementation UIImage(Overlay)
- (UIImage *)imageWithColor:(UIColor *)color1
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, self.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextClipToMask(context, rect, self.CGImage);
[color1 setFill];
CGContextFillRect(context, rect);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
so you would do:
theImageView.image = [theImageView.image imageWithColor:[UIColor redColor]];
Since you are interested in catching network related errors and HTTP errors, the following provides a better approach:
function curl_error_test($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseBody = curl_exec($ch);
/*
* if curl_exec failed then
* $responseBody is false
* curl_errno() returns non-zero number
* curl_error() returns non-empty string
* which one to use is up too you
*/
if ($responseBody === false) {
return "CURL Error: " . curl_error($ch);
}
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/*
* 4xx status codes are client errors
* 5xx status codes are server errors
*/
if ($responseCode >= 400) {
return "HTTP Error: " . $responseCode;
}
return "No CURL or HTTP Error";
}
Tests:
curl_error_test("http://expamle.com"); // CURL Error: Could not resolve host: expamle.com
curl_error_test("http://example.com/whatever"); // HTTP Error: 404
curl_error_test("http://example.com"); // No CURL or HTTP Error
I think your question is if having an update_attribute in a before_save will lead to and endless loop (of update_attribute calls in before_save callbacks, originally triggered by an update_attribute call)
I'm pretty sure it does bypass the before_save callback since it doesn't actually save the record. You can also save a record without triggering validations by using
Model.save false
Use typings to access node functions from TypeScript:
typings install env~node --global
If you don't have typings install it:
npm install typings --global
You can use GetType - GetProperties - Linq Foreach:
obj.GetType().GetProperties().ToList().ForEach(p =>{
//p is each PropertyInfo
DoSomething(p);
});
Use this:
Request.Url.AbsoluteUri
That will get you the full path (including http://...)
I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:
create table destination_old as select * from destination;
drop table destination;
create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;
It's safe because you have a copy of destination
before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.
Using the pattern above you end up with two country
fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old
and perhaps using coalesce
to retrieve the values from destination_old
if the country
field in source
is null. So for example:
create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
The line
arr[i] = temp;
is wrong. (On the first iteration of your loop it sets arr[i]
to an undefined value; further iterations set it to an incorrect value.) If you remove this line, your array should be reversed correctly.
After that, you should move the code which prints the reversed array into a new loop which iterates over the whole list. Your current code only prints the first count/2
elements.
int temp, i;
for (i = 0; i < count/2; ++i) {
temp = arr[count-i-1];
arr[count-i-1] = arr[i];
arr[i] = temp;
}
for (i = 0; i < count; ++i) {
cout << arr[i] << " ";
}
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
Try adding this in your Activity's onCreate. Works on almost every Android version.
actionBar.setTitle(Html.fromHtml("<font color='#ffff00'>Your Title</font>"));
or
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffff00'>Your Title</font>"));
They are useful to identify each elements in SQL.
For example:
CREATE TABLE SchemaName.TableName (
This would actually create a table by the name SchemaName.TableName
under default dbo
schema even though the intention might be to create the table inside the SchemaName
schema.
The correct way would be the following:
CREATE TABLE [SchemaName].[TableName] (
Now it it knows what is the table name and in which schema should it be created in (rightly in the SchemaName
schema and not in the default dbo
schema)
Most answers said that how to set #ifdef DEBUG and none of them saying how to determinate debug/release build.
My opinion:
I had trouble with SQLite3, nStore and Alfred.
What works for me is node-dirty:
path = "#{__dirname}/data/messages.json"
messages = db path
message = 'text': 'Lorem ipsum dolor sit...'
messages.on "load", ->
messages.set 'my-unique-key', message, ->
console.log messages.get('my-unique-key').text
messages.forEach (key, value) ->
console.log "Found key: #{key}, val: %j", value
messages.on "drain", ->
console.log "Saved to #{path}"
Here is the code you need:
start cmd.exe @cmd /k "Command"
Based on the last response from @Simon, I first uninstalled the new version of Git. I then re-installed the new version of Git into the same directory as the old version, C:/RailsInstaller/Git
, instead of the default directory C:/Git
.
Now my rails terminal window shows that I am running the new git version 1.8.0.
This will not work in your situation. You can only specify the constraint that it has an empty constructor:
public static string GetAllItems<T>(...) where T: new()
What you could do is use property injection by defining this interface:
public interface ITakesAListItem
{
ListItem Item { set; }
}
Then you could alter your method to be this:
public static string GetAllItems<T>(...) where T : ITakesAListItem, new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T() { Item = listItem });
}
...
}
The other alternative is the Func
method described by JaredPar.
Here is a function generalizing previous approaches, creating a grid of images in PIL:
from PIL import Image
import numpy as np
def pil_grid(images, max_horiz=np.iinfo(int).max):
n_images = len(images)
n_horiz = min(n_images, max_horiz)
h_sizes, v_sizes = [0] * n_horiz, [0] * (n_images // n_horiz)
for i, im in enumerate(images):
h, v = i % n_horiz, i // n_horiz
h_sizes[h] = max(h_sizes[h], im.size[0])
v_sizes[v] = max(v_sizes[v], im.size[1])
h_sizes, v_sizes = np.cumsum([0] + h_sizes), np.cumsum([0] + v_sizes)
im_grid = Image.new('RGB', (h_sizes[-1], v_sizes[-1]), color='white')
for i, im in enumerate(images):
im_grid.paste(im, (h_sizes[i % n_horiz], v_sizes[i // n_horiz]))
return im_grid
It will shrink each row and columns of the grid to the minimum. You can have only a row by using pil_grid(images), or only a column by using pil_grid(images, 1).
One benefit of using PIL over numpy-array based solutions is that you can deal with images structured differently (like grayscale or palette-based images).
Example outputs
def dummy(w, h):
"Produces a dummy PIL image of given dimensions"
from PIL import ImageDraw
im = Image.new('RGB', (w, h), color=tuple((np.random.rand(3) * 255).astype(np.uint8)))
draw = ImageDraw.Draw(im)
points = [(i, j) for i in (0, im.size[0]) for j in (0, im.size[1])]
for i in range(len(points) - 1):
for j in range(i+1, len(points)):
draw.line(points[i] + points[j], fill='black', width=2)
return im
dummy_images = [dummy(20 + np.random.randint(30), 20 + np.random.randint(30)) for _ in range(10)]
pil_grid(dummy_images)
:
pil_grid(dummy_images, 3)
:
pil_grid(dummy_images, 1)
:
you can use enumerate keeping the ind/index of the elements is in vm, if you make vm
a set you will also have 0(1)
lookups:
vm = {-1, -1, -1, -1}
print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])
https://github.com/mattt/TTTAttributedLabel
That's definitely what you need. You can also apply attributes for your label, like underline, and apply different colors to it. Just check the instructions for clickable urls.
Mainly, you do something like the following:
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring
Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.
You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).
Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.
Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV
(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.
Hope this helps someone, I've found expressions in ng-class to be very useful!
HTML
<ul>
<li ng-repeat="person in people"
data-ng-class="{'active-selection': person.id == activeClass}">
<a data-ng-click="selectPerson(person.id)">
{{person.name}}
</a>
</li>
</ul>
JS
app.controller('MainCtrl', function($scope) {
$scope.people = [{
id: "1",
name: "John",
}, {
id: "2",
name: "Lucy"
}, {
id: "3",
name: "Mark"
}, {
id: "4",
name: "Sam"
}];
$scope.selectPerson = function(id) {
$scope.activeClass = id;
console.log(id);
};
});
CSS:
.active-selection {
background-color: #eee;
}
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
I looked at Android Source Tree.
Inside com.android.server.am.ActivityManagerService.java (internal service exposed by android.app.ActivityManager).
public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
outInfo.availMem = Process.getFreeMemory();
outInfo.totalMem = Process.getTotalMemory();
outInfo.threshold = homeAppMem;
outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
outInfo.hiddenAppThreshold = hiddenAppMem;
outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
ProcessList.SERVICE_ADJ);
outInfo.visibleAppThreshold = mProcessList.getMemLevel(
ProcessList.VISIBLE_APP_ADJ);
outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
ProcessList.FOREGROUND_APP_ADJ);
}
Inside android.os.Process.java
/** @hide */
public static final native long getFreeMemory();
/** @hide */
public static final native long getTotalMemory();
It calls JNI method from android_util_Process.cpp
Conclusion
MemoryInfo.availMem = MemFree + Cached in /proc/meminfo.
Notes
Total Memory is added in API level 16.
If there are true answers to those questions, it would be different per software vendor and would be defined by the vendor. I don't know of any true industry standards that are followed with regards to this matter.
Historically with Microsoft, they'll mark something as deprecated and state they'll remove it in a future version. That can be several versions before they actually get rid of it though.
You have two ways to fix this. The preferred way is to use:
string answer;
(instead of char
). The other possible way to fix it is:
if (answer == 'y') ...
(note single quotes instead of double, representing a char
constant).
You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:
YOU: /setjoingroups
BotFather: Choose a bot to change group membership settings.
YOU: @YourBot
BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED
YOU: Enable
BotFather: Success! The new status is: ENABLED.
After this you will see button "Add to Group" in your bot's profile.
There is also this neat little extension method:
static class ExtensionMethods
{
public static Color ToColor(this uint argb)
{
return Color.FromArgb((byte)((argb & -16777216)>> 0x18),
(byte)((argb & 0xff0000)>> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
}
}
In use:
Color color = 0xFFDFD991.ToColor();
I like an example from Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates - Head First Design Patterns
book.
Example:
let's assume you created home theatre and finally you would like to watch a movie. So you have to do:
Amplifier amplifier = new Amplifier();
CdPlayer cdPlayer = new CdPlayer();
DvdPlayer dvdPlayer = new DvdPlayer();
Lights lights = new Lights();
PopcornPopper popcornPopper = new PopcornPopper();
Projector projector = new Projector();
Screen screen = new Screen();
popcornPopper.turnOn();
popcornPopper.pop();
amplifier.turnOn();
amplifier.setVolume(10);
lights.turnOn();
lights.dim(10);
screen.up();
dvdPlayer.turnOn();
dvdPlayer.play();
what happens when movie is over? You have to do the same but in reverse order so complexity of watch and end movie is becoming very complex. Facade pattern says that you can create a facade and let user just call one method instead of calling all of this. Let's create facade:
public class HomeTheatherFacade {
Amplifier amplifier;
DvdPlayer dvdPlayer;
CdPlayer cdPlayer;
Projector projector;
Lights lights;
Screen screen;
PopcornPopper popcornPopper;
public HomeTheatherFacade(Amplifier amplifier, DvdPlayer dvdPlayer, CdPlayer cdPlayer, Projector projector, Lights lights, Screen screen, PopcornPopper popcornPopper) {
this.amplifier = amplifier;
this.dvdPlayer = dvdPlayer;
this.cdPlayer = cdPlayer;
this.projector = projector;
this.lights = lights;
this.screen = screen;
this.popcornPopper = popcornPopper;
}
public void watchMovie(String movieTitle) {
popcornPopper.turnOn();
popcornPopper.pop();
amplifier.turnOn();
amplifier.setVolume(10);
lights.turnOn();
lights.dim(10);
screen.up();
dvdPlayer.turnOn();
dvdPlayer.play();
}
public void endMovie() {
dvdPlayer.turnOff();
screen.down();
lights.turnOff();
amplifier.turnOff();
}
}
and now instead of calling all of this you can just call watchMovie
and endMovie
methods:
public class HomeTheatherFacadeTest {
public static void main(String[] args){
Amplifier amplifier = new Amplifier();
CdPlayer cdPlayer = new CdPlayer();
DvdPlayer dvdPlayer = new DvdPlayer();
Lights lights = new Lights();
PopcornPopper popcornPopper = new PopcornPopper();
Projector projector = new Projector();
Screen screen = new Screen();
HomeTheatherFacade homeTheatherFacade = new HomeTheatherFacade(amplifier, dvdPlayer, cdPlayer, projector, lights, screen, popcornPopper);
homeTheatherFacade.watchMovie("Home Alone");
homeTheatherFacade.endMovie();
}
}
So:
"The Facade Pattern provides a unified interface to a set of interfaces in a subsytem. Facade defines a higher level interface that makes the subsystem easier to use."
I must bring an amazing tool to your notice which i have used sometime back. AVICode Interceptor Studio. In my previous company we used this wonderful tool to profile the webapplication (This is supposed to be the single largest web application in the world and the largest civilian IT project ever done). The performance team did wonders with the help of this magnificent tool. It is a pain to configure it, but that is a one time activity and i would say it is worth the time. Checkout this page for details.
Thanks, James
@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.
Try this:
rdd = df.rdd.map(tuple)
or
rdd = df.rdd.map(list)
As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:
String myDateString = "13:24:40";
LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
int second = localTime.get(ChronoField.SECOND_OF_MINUTE);
//prints "hour: 13, minute: 24, second: 40":
System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));
Remarks:
====== Below is the old (original) answer for this question, using pre-Java8 API: =====
I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.
A SimpleDateFormat might do the trick here:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
It should be something like:
String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds
The gotchas you should be aware of:
the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this
Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])
First I wanted to add comment under Duncan Smart post, but unfortunately I have not got enough reputation yet to leave comments. So I will try it here.
I just want to warn about side effects.
JsonTextReader internally parses json into typed JTokens and then serialises them back.
For example if your original JSON was
{ "double":0.00002, "date":"\/Date(1198908717056)\/"}
After prettify you get
{
"double":2E-05,
"date": "2007-12-29T06:11:57.056Z"
}
Of course both json string are equivalent and will deserialize to structurally equal objects, but if you need to preserve original string values, you need to take this into concideration
Since you asked for a C++ solution...
#include <algorithm>
#include <iterator>
const int arr_size = 10;
some_type src[arr_size];
// ...
some_type dest[arr_size];
std::copy(std::begin(src), std::end(src), std::begin(dest));
You can also use keyword namespace
to organize your variables, classes, methods and so on. See doc
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
const lettersRegexp = /^[A-Za-z]+$/;
const numberRegexp = /^[0-9]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
It is common to use the MAC address is associated with the network card.
The address is available in Java 6 through through the following API:
Java 6 Docs for Hardware Address
I haven't used it in Java, but for other network identification applications it has been helpful.
Just had the same issue but in my case I had typed the wrong branch on the remote. So, it seems that is another source of this issue... double check you're pushing to the correct branch.
I've used this "portable plotter". It's very small, multiplatform, easy to use and you can plug it into different graphical libraries. pplot
(Only for the plots part)
If you use or plan to use Qt, another multiplatform solution is Qwt and Qchart
you can use this:
try {
Intent followIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" +
"https://www.facebook.com/app_scoped_user_id/"+scoped user id+"/"));
activity.startActivity(followIntent);
} catch (Exception e) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + user name)));
String errorMessage = (e.getMessage() == null) ? "Message is empty" : e.getMessage();
}
attention: you can get scoped user id from "link" permission facebook api
Alternative:
boolean isWhiteSpaces( String s ) {
return s != null && s.matches("\\s+");
}
The E stands for the exponent, and it is used to shorten long numbers. Since the input is a math input and exponents are in math to shorten great numbers, so that's why there is an E.
It is displayed like this: 4e.
I found this https://typescriptbcl.codeplex.com/SourceControl/latest
here is the Guid version they have in case the link does not work later.
module System {
export class Guid {
constructor (public guid: string) {
this._guid = guid;
}
private _guid: string;
public ToString(): string {
return this.guid;
}
// Static member
static MakeNew(): Guid {
var result: string;
var i: string;
var j: number;
result = "";
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return new Guid(result);
}
}
}
Yet another solution if Object.entries
won't work for you.
const obj = {_x000D_
'1': 29,_x000D_
'2': 42_x000D_
};_x000D_
const arr = Array.from(Object.keys(obj), k=>[`${k}`, obj[k]]);_x000D_
console.log(arr);
_x000D_
SpreadsheetGear for .NET does it this way:
IWorkbook workbook = Factory.GetWorkbook();
IRange a1 = workbook.Worksheets[0].Cells["A1"];
a1.Value = "Hello\r\nWorld!";
a1.WrapText = true;
workbook.SaveAs(@"c:\HelloWorld.xlsx", FileFormat.OpenXMLWorkbook);
Note the "WrapText = true" - Excel will not wrap the text without this. I would assume that Aspose has similar APIs.
Disclaimer: I own SpreadsheetGear LLC
Check whether you have put name="your_radio" where you have inserted radio tag
if you have done this then check your php code. Use isset()
e.g.
if(isset($_POST['submit']))
{
/*other variables*/
$radio_value = $_POST["your_radio"];
}
If you have done this as well then we need to look through your codes
Google do an interesting thing with their gmail.com addresses. gmail.com addresses allow only letters (a-z), numbers, and periods(which are ignored).
e.g., [email protected] is the same as [email protected], and both email addresses will be sent to the same mailbox. [email protected] is also delivered to the same mailbox.
So to answer the question, sometimes it depends on the implementer on how much of the RFC standards they want to follow. Google's gmail.com address style is compatible with the standards. They do it that way to avoid confusion where different people would take similar email addresses e.g.
*** gmail.com accepting rules ***
[email protected] (accepted)
[email protected] (bounce and account can never be created)
[email protected] (accepted)
D.Oy'[email protected] (bounce and account can never be created)
The wikipedia link is a good reference on what email addresses generally allow. http://en.wikipedia.org/wiki/Email_address
I had a similar issue on CentOS 7 while a correct version of Java was installed and java -version
gave a nice result.
Collecting multiple answers from different SO threads I did the following:
Make sure Java is installed (and version is compatible with Jenkins) There're some tricks if saying about CentOS, this is mentioned in official Jenkins tutorial here
If Java is installed and available, when running java -v
output should look like this:
~>$java -version
openjdk version "1.8.0_161"
OpenJDK Runtime Environment (build 1.8.0_161-b14)
OpenJDK 64-Bit Server VM (build 25.161-b14, mixed mode)
Add a path to Java to your /etc/rc.d/init.d/jenkins
~>$ sudo vim /etc/rc.d/init.d/jenkins
candidates="
/etc/alternatives/java
/usr/lib/jvm/java-1.8.0/bin/java
/usr/lib/jvm/jre-1.8.0/bin/java
/usr/lib/jvm/java-1.7.0/bin/java
/usr/lib/jvm/jre-1.7.0/bin/java
/usr/bin/java
/usr/java/jdk1.8.0_162/bin/java ##add your java path here
"
How to get your 'real' path to java distributive which is called when you type smth like java -v
Follow this SO thread
If steps above didn't help, try to make sure all permission issues are resolved:
jenkins
user doesn't have permissions to run it, then change jenkins
to root
in config (described here)chmod
setting 755
permissions to java
installation folderAnd finally what helped me in result
When I did run journalctl -xe
as was suggested when I've tried to sudo service jenkins start
, I got similar Java stacktrace:
Starting CloudBees Jenkins Enterprise Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at Main._main(Main.java:140)
at Main.main(Main.java:98)
Caused by: java.lang.UnsatisfiedLinkError: /tmp/jna--1712433994/jna7387046629130767794.tmp: /tmp/jna--1712433994/jna7387046629130767794.tmp: failed to map segment from shared object: Operation not permitted
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1937)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1822)
at java.lang.Runtime.load0(Runtime.java:809)
at java.lang.System.load(System.java:1086)
at com.sun.jna.Native.loadNativeDispatchLibraryFromClasspath(Native.java:761)
at com.sun.jna.Native.loadNativeDispatchLibrary(Native.java:736)
at com.sun.jna.Native.<clinit>(Native.java:131)
at com.sun.akuma.CLibrary.<clinit>(CLibrary.java:89)
at com.sun.akuma.JavaVMArguments.resolvePID(JavaVMArguments.java:128)
at com.sun.akuma.JavaVMArguments.ofLinux(JavaVMArguments.java:116)
at com.sun.akuma.JavaVMArguments.of(JavaVMArguments.java:104)
at com.sun.akuma.JavaVMArguments.current(JavaVMArguments.java:92)
at com.sun.akuma.Daemon.daemonize(Daemon.java:106)
at com.sun.akuma.Daemon.all(Daemon.java:88)
... 6 more
The problem is that Jenkins tries to launch JNA
library from /tmp
dir which is marked as noexec
by default, so we it could be fixed by creating a temporary directory in a /jenkins
path so it could be executed.
The full way to do this is described here by CloudBees support (thanks a lot for them)
I hope something from this list will help (as well I mostly leave it for me in the future when I'll have to install Jenkins for CentOs again :)
Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)
sub myhandler(eventsource)
process(eventsource.value)
end sub
for each cell
cell.setEventHandler(myHandler)
But i dont know the syntax for achieving this in VB/VBA, or if is even possible.
You dont have to bind anything, Just use Arrow functions like this:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1
};
}
//ARROW FUNCTION
delta = () => {
this.setState({
count: this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
Try this:
var d = new Date(),
minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
Simply,
SELECT TIME(column_name), DATE(column_name)
try this one : java.net.URL;
JOptionPane.showMessageDialog(null, getDomainName(new URL("https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains")));
public String getDomainName(URL url){
String strDomain;
String[] strhost = url.getHost().split(Pattern.quote("."));
String[] strTLD = {"com","org","net","int","edu","gov","mil","arpa"};
if(Arrays.asList(strTLD).indexOf(strhost[strhost.length-1])>=0)
strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else if(strhost.length>2)
strDomain = strhost[strhost.length-3]+"."+strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else
strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
return strDomain;}