To connect locally to MySql
, you do not have to setup a firewall with inbound rules. But, even if you already setup iptables
to allow the TCP
inbound port 3306 and grant the privilege to the user to access the db locally, you may have to setup the bind address in your my.cnf
file, edit the default address there and put the server IP address that is running the MySql
service.
IF EXISTS()
is semantically incorrect. EXISTS
condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:
declare
l_exst number(1);
begin
select case
when exists(select ce.s_regno
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1
)
then 1
else 0
end into l_exst
from dual;
if l_exst = 1
then
DBMS_OUTPUT.put_line('YES YOU CAN');
else
DBMS_OUTPUT.put_line('YOU CANNOT');
end if;
end;
Or you can simply use count
function do determine the number of rows returned by the query, and rownum=1
predicate - you only need to know if a record exists:
declare
l_exst number;
begin
select count(*)
into l_exst
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1;
if l_exst = 0
then
DBMS_OUTPUT.put_line('YOU CANNOT');
else
DBMS_OUTPUT.put_line('YES YOU CAN');
end if;
end;
You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }
So
http://stack_overflow.com/~foo%20bar#link
would be
http://stack\_overflow.com/\~foo\%20bar\#link
Pure js alternative to window.open
let a= document.createElement('a');
a.target= '_blank';
a.href= 'https://support.wwf.org.uk/';
a.click();
here is working example (stackoverflow snippets not allow to opening)
I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html
The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.
According to official Android information about dumpsys:
The dumpsys tool runs on the device and provides information about the status of system services.
To get a list of available services use
adb shell dumpsys -l
You can use getComputedStyle()
.
var element = document.getElementById('image_1'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.
For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio
This feature still available, but it is NOT available by default, you have to install it separately.
see this answer also to see an image associated
https://stackoverflow.com/a/66289543/4390133
(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)
Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)
Preview Selected Items
is enabled in the solution explorer, disabled it temporarily, you can re-enable it lateryou could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)
You could do the opposite of what you proposed.
location (/test)/ {
set $folder $1;
}
location (/test_/something {
set $folder $1;
}
Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:
class MathsOperations:
@staticmethod
def testAddition (x, y):
return x + y
@staticmethod
def testMultiplication (a, b):
return a * b
You get this message when you've used async in your template, but are referring to an object that isn't an Observable.
So for examples sake, lets' say I had these properties in my class:
job:Job
job$:Observable<Job>
Then in my template, I refer to it this way:
{{job | async }}
instead of:
{{job$ | async }}
You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.
just tested doing this and it seems to work in firefox & IE
<html>
<head>
<script type="text/javascript">
function alertFilename()
{
var thefile = document.getElementById('thefile');
alert(thefile.value);
}
</script>
</head>
<body>
<form>
<input type="file" id="thefile" onchange="alertFilename()" />
<input type="button" onclick="alertFilename()" value="alert" />
</form>
</body>
</html>
Go to your project target in Xcode > General > Set "Requires full screen" (under Hide status bar) to true.
You may use the below code to write, for example an image to S3 in 2019. To be able to connect to S3 you will have to install AWS CLI using command pip install awscli
, then enter few credentials using command aws configure
:
import urllib3
import uuid
from pathlib import Path
from io import BytesIO
from errors import custom_exceptions as cex
BUCKET_NAME = "xxx.yyy.zzz"
POSTERS_BASE_PATH = "assets/wallcontent"
CLOUDFRONT_BASE_URL = "https://xxx.cloudfront.net/"
class S3(object):
def __init__(self):
self.client = boto3.client('s3')
self.bucket_name = BUCKET_NAME
self.posters_base_path = POSTERS_BASE_PATH
def __download_image(self, url):
manager = urllib3.PoolManager()
try:
res = manager.request('GET', url)
except Exception:
print("Could not download the image from URL: ", url)
raise cex.ImageDownloadFailed
return BytesIO(res.data) # any file-like object that implements read()
def upload_image(self, url):
try:
image_file = self.__download_image(url)
except cex.ImageDownloadFailed:
raise cex.ImageUploadFailed
extension = Path(url).suffix
id = uuid.uuid1().hex + extension
final_path = self.posters_base_path + "/" + id
try:
self.client.upload_fileobj(image_file,
self.bucket_name,
final_path
)
except Exception:
print("Image Upload Error for URL: ", url)
raise cex.ImageUploadFailed
return CLOUDFRONT_BASE_URL + id
I've written a library that helps do precisely this. It allows search by object simply by initializing only the fields you want to filter by: https://github.com/kg6zvp/GenericEntityEJB
width="100" height="100"
in the svg file then add this x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100"
while keeping the already defined width="100" height="100"
. img
so you could then do this: img{height: 20px; width: 20px;}
and the image will scale.Standard Unix exit codes are defined by sysexits.h, as another poster mentioned. The same exit codes are used by portable libraries such as Poco - here is a list of them:
http://pocoproject.org/docs/Poco.Util.Application.html#16218
A signal 11 is a SIGSEGV (segment violation) signal, which is different from a return code. This signal is generated by the kernel in response to a bad page access, which causes the program to terminate. A list of signals can be found in the signal man page (run "man signal").
I suggest to use :hover to avoid underline if mouse pointer is over an anchor
a:hover {
text-decoration:none;
}
That's not padding, it's the shadow around the button in its background drawable. Create your own background and it will disappear.
Underscore's _.isEqual(object, other)
function seems to work well for arrays. The order of items in the array matter when it checks for equality. See http://underscorejs.org/#isEqual.
I have some hacky answers that are likely to be terrible... but I have very little experience at this point.
a way:
class myClass():
myInstances = []
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
self.__class__.myInstances.append(self)
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
for thisObj in myClass.myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
A hack way to get this done:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
thisStep += 1
if "myClass object at" in thisLocalsLine:
print(thisLocalsLine)
print(myLocals[(thisStep - 2)])
#myInstances.append(myLocals[(thisStep - 2)])
print(myInstances)
myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
Another more 'clever' hack:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myInstances = []
myClasses = {
"myObj01": ["Foo", "Bar"],
"myObj02": ["FooBar", "Baz"]
}
for thisClass in myClasses.keys():
exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
myInstances.append(getattr(sys.modules[__name__], thisClass))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
I think I've got it.
.wrapper {_x000D_
background:#DDD;_x000D_
display:inline-block;_x000D_
padding: 10px;_x000D_
height: 20px;_x000D_
width:auto;_x000D_
}_x000D_
_x000D_
.label {_x000D_
display: inline-block;_x000D_
width: 1em;_x000D_
}_x000D_
_x000D_
.contents, .contents .inner {_x000D_
display:inline-block;_x000D_
}_x000D_
_x000D_
.contents {_x000D_
white-space:nowrap;_x000D_
margin-left: -1em;_x000D_
padding-left: 1em;_x000D_
}_x000D_
_x000D_
.contents .inner {_x000D_
background:#c3c;_x000D_
width:0%;_x000D_
overflow:hidden;_x000D_
-webkit-transition: width 1s ease-in-out;_x000D_
-moz-transition: width 1s ease-in-out;_x000D_
-o-transition: width 1s ease-in-out;_x000D_
transition: width 1s ease-in-out;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
.wrapper:hover .contents .inner {_x000D_
_x000D_
width:100%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<span class="label">+</span><div class="contents">_x000D_
<div class="inner">_x000D_
These are the contents of this div_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Animating to 100%
causes it to wrap because the box is bigger than the available width (100% minus the +
and the whitespace following it).
Instead, you can animate an inner element, whose 100%
is the total width of .contents
.
If you just want to list all the sites (ie. to find a binding)
Change the working directory to "C:\Windows\system32\inetsrv"
cd c:\Windows\system32\inetsrv
Next run "appcmd list sites" (plural) and output to a file. e.g c:\IISSiteBindings.txt
appcmd list sites > c:\IISSiteBindings.txt
Now open with notepad from your command prompt.
notepad c:\IISSiteBindings.txt
require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http');
// Register with spl_autoload:
$loader->register();
$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;
Use the "containment" option:
jQuery UI API - Draggable Widget - containment
The documentation says it only accepts the values: 'parent'
, 'document'
, 'window'
, [x1, y1, x2, y2]
but I seem to remember it will accept a selector such as '#container' too.
EDIT: previous answer was backwards of what you wanted. Use str_replace.
replace <br>
with \n
echo str_replace('<br>', "\n", $var1);
You should not replace the text entirely. Add the text after the "# END WordPress".
I did something similar but I use binding to get the selected item :
<DataGrid Grid.Row="1" AutoGenerateColumns="False" Name="dataGrid"
IsReadOnly="True" SelectionMode="Single"
ItemsSource="{Binding ObservableContactList}"
SelectedItem="{Binding SelectedContact}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Name}" Header="Name"/>
<DataGridTextColumn Binding="{Binding Path=FamilyName}" Header="FamilyName"/>
<DataGridTextColumn Binding="{Binding Path=Age}" Header="Age"/>
<DataGridTextColumn Binding="{Binding Path=Relation}" Header="Relation"/>
<DataGridTextColumn Binding="{Binding Path=Phone.Display}" Header="Phone"/>
<DataGridTextColumn Binding="{Binding Path=Address.Display}" Header="Addr"/>
<DataGridTextColumn Binding="{Binding Path=Mail}" Header="E-mail"/>
</DataGrid.Columns>
</DataGrid>
So I can access my SelectedContact.Name in my ViewModel.
Union
will remove duplicates. Union All
does not.
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.
Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.
How to decide whether to use Tomcat or a full stack Java EE
application server:
When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:
In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.
Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.
my 2 cent
First of all, I suggest that you narrow the problem to which component throws the "Out of Memory Exception".
This could be:
The JVM parameters -xms
and -xmx
represent the heap's "start memory" and the "maximum memory". Forget the "start memory". This is not going to help you now and you should only change this parameter if you're sure your app will consume this amount of memory rapidly.
In production, I think the only parameter that you can change is the -xmx
under the Catalina.sh or Catalina.bat files. But if you are testing your webapp directly from Eclipse with a configured debug environment of Tomcat, you can simply go to your "Debug Configurations" > "Apache Tomcat" > "Arguments" > "VM arguments" and set the -xmx
there.
As for the optimal -xmx
for 2gb, this depends a lot of your environment and the number of requests your app might take. I would try values from 500mb up to 1gb. Check your OS virtual memory "zone" limit and the limit of the JVM itself.
On the selected answer I see that when initially the page is loaded the selection of first option is prior fixed and therefore gives the option of all the categories in selection 2.
You can avoid that by adding the first option as the following in both the select tag:- <option value="none" selected disabled hidden>Select an Option</option>
<select name="select1" id="select1">
<option value="none" selected disabled hidden>Select an Option</option>
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="none" selected disabled hidden>Select an Option</option>
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Since optparse
has been mentioned a couple of times in the answers, and it provides a comprehensive kit for command line processing, here's a short simplified example of how you can use it, assuming the input file exists:
script.R:
library(optparse)
option_list <- list(
make_option(c("-n", "--count_lines"), action="store_true", default=FALSE,
help="Count the line numbers [default]"),
make_option(c("-f", "--factor"), type="integer", default=3,
help="Multiply output by this number [default %default]")
)
parser <- OptionParser(usage="%prog [options] file", option_list=option_list)
args <- parse_args(parser, positional_arguments = 1)
opt <- args$options
file <- args$args
if(opt$count_lines) {
print(paste(length(readLines(file)) * opt$factor))
}
Given an arbitrary file blah.txt
with 23 lines.
On the command line:
Rscript script.R -h
outputs
Usage: script.R [options] file
Options:
-n, --count_lines
Count the line numbers [default]
-f FACTOR, --factor=FACTOR
Multiply output by this number [default 3]
-h, --help
Show this help message and exit
Rscript script.R -n blah.txt
outputs [1] "69"
Rscript script.R -n -f 5 blah.txt
outputs [1] "115"
Best way to make drop down list:
grid.Column("PriceType",canSort:true,header: "PriceType",format: @<span>
<span id="[email protected]">@item.PriceTypeDescription</span>
@Html.DropDownList("PriceType"+(int)item.ShoppingCartID,new SelectList(MvcApplication1.Services.ExigoApiContext.CreateODataContext().PriceTypes.Select(s => new { s.PriceTypeID, s.PriceTypeDescription }).AsEnumerable(),"PriceTypeID", "PriceTypeDescription",Convert.ToInt32(item.PriceTypeId)), new { @class = "PriceType",@style="width:120px;display:none",@selectedvalue="selected"})
</span>),
You can also put below code to the httaccess file as well to allow CORS using htaccess file
######################## Handling Options for the CORS
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [L,R=204]
##################### Add custom headers
Header set X-Content-Type-Options "nosniff"
Header set X-XSS-Protection "1; mode=block"
# Always set these headers for CORS.
Header always set Access-Control-Max-Age 1728000
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,C$
Header always set Access-Control-Allow-Credentials true
For information purpose, You can also have a look at this article http://www.ipragmatech.com/enable-cors-using-htaccess/ which allow CORS header.
Off the top of my head I think it should be done like this:
var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);
With MySQL Workbench you can use Data Export to dump just the table to a local SQL file (Data Only, Structure Only or Structure and Data) and then Data Import to load it into the other DB.
You can have multiple connections (different hosts, databases, users) open at the same time.
While building the project on Unix/Linux platform, set Maven options syntax as below. Notice that single qoutation signs, not double qoutation.
export MAVEN_OPTS='-Xmx512m -XX:MaxPermSize=128m'
You can use selenium.Support
to use the SelectElement
class, this class have a property "Options" that is what you are looking for, I created an extension method to convert your web element to a select element
public static SelectElement AsDropDown(this IWebElement webElement)
{
return new SelectElement(webElement);
}
then you could use it like this
var elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
var options = elem.AsDropDown().Options
You can use the toolbarHeight property of Appbar, it does exactly what you want.
In Python 2 you can avoid making a temporary copy of all the values by using the itervalues()
dictionary method, which returns an iterator of the dictionary's keys:
sum(d.itervalues())
In Python 3 you can just use d.values()
because that method was changed to do that (and itervalues()
was removed since it was no longer needed).
To make it easier to write version independent code which always iterates over the values of the dictionary's keys, a utility function can be helpful:
import sys
def itervalues(d):
return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())
sum(itervalues(d))
This is essentially what Benjamin Peterson's six
module does.
after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.
context.deleteDatabase("database_name.db");
This might help someone. You have to mention the extension otherwise, it will not work.
According to this thread:
The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.
PHP uses one of two methods to keep track of sessions. If cookies are enabled, like in your case, it uses them.
If cookies are disabled, it uses the URL. Although this can be done securely, it's harder and it often, well, isn't. See, e.g., session fixation.
Search for it, you will get lots of SEO advice. The conventional wisdom is that you should use the cookies, but php will keep track of the session either way.
First create a DataGridTemplateColumn
to contain the button:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ShowHideDetails">Details</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
When the button is clicked, update the containing DataGridRow
's DetailsVisibility
:
void ShowHideDetails(object sender, RoutedEventArgs e)
{
for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
if (vis is DataGridRow)
{
var row = (DataGridRow)vis;
row.DetailsVisibility =
row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
break;
}
}
Just put the labels in a div inside the TD and put the height and overflow.. like below.
<table>
<tr>
<td><div style="height:40px; overflow:hidden">Sample</div></td>
<td><div style="height:40px; overflow:hidden">Text</div></td>
<td><div style="height:40px; overflow:hidden">Here</div></td>
</tr>
</table>
You can write your php file to the action
attr of form element.
At the php side you can get the form value by $_POST['element_name']
.
For all solutions instead of ".keyup" ".change" should be used or else the submit button wont be disabled when someone just selects data stored in cookies for any of the text fields.
This is how I use the nodejs fs.readdir function to recursively search a directory.
const fs = require('fs');
const mime = require('mime-types');
const readdirRecursivePromise = path => {
return new Promise((resolve, reject) => {
fs.readdir(path, (err, directoriesPaths) => {
if (err) {
reject(err);
} else {
if (directoriesPaths.indexOf('.DS_Store') != -1) {
directoriesPaths.splice(directoriesPaths.indexOf('.DS_Store'), 1);
}
directoriesPaths.forEach((e, i) => {
directoriesPaths[i] = statPromise(`${path}/${e}`);
});
Promise.all(directoriesPaths).then(out => {
resolve(out);
}).catch(err => {
reject(err);
});
}
});
});
};
const statPromise = path => {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err) {
reject(err);
} else {
if (stats.isDirectory()) {
readdirRecursivePromise(path).then(out => {
resolve(out);
}).catch(err => {
reject(err);
});
} else if (stats.isFile()) {
resolve({
'path': path,
'type': mime.lookup(path)
});
} else {
reject(`Error parsing path: ${path}`);
}
}
});
});
};
const flatten = (arr, result = []) => {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, result);
} else {
result.push(value);
}
}
return result;
};
Let's say you have a path called '/database' in your node projects root. Once this promise is resolved, it should spit out an array of every file under '/database'.
readdirRecursivePromise('database').then(out => {
console.log(flatten(out));
}).catch(err => {
console.log(err);
});
Under HTML5 you are be able to do this:
document.getElementById('test').selectedOptions[0].text
MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.
Better to just use .addClass()
and .removeClass()
even if you have 1 or more styles to change. It's more maintainable and readable.
If you really have the urge to do multiple CSS properties, then use the following:
.css({
'font-size' : '10px',
'width' : '30px',
'height' : '10px'
});
NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.
Can I see (...) the real SQL
If you want to see the SQL sent directly to the database (that is formatted similar to your example), you'll have to use some kind of jdbc driver proxy like P6Spy (or log4jdbc).
Alternatively you can enable logging of the following categories (using a log4j.properties
file here):
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
The first is equivalent to hibernate.show_sql=true
, the second prints the bound parameters among other things.
You don't need to use a type assertion, instead just use the %v
format specifier with Sprintf
:
hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])
Try these:
window.location.href = 'http://www.google.com';
window.location.assign("http://www.w3schools.com");
window.location = 'http://www.google.com';
For more see this link: other ways to reload the page with JavaScript
A shorter alternative to the previously mentioned stash approach would be:
Temporarily move the changes to a stash.
git stash
Create and switch to a new branch and then pop the stash to it in just one step.
git stash branch new_branch_name
Then just add
and commit
the changes to this new branch.
Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...
The other reason is, that it's not clear at all what the "right" implementation of a set is:
There is a functional approach:
func IsInEvenNumbers(n int) bool {
if n % 2 == 0 {
return true
}
return false
}
This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.
A map does not have that problem, since you store something associated with the value.
I've had success putting text within span tags and then setting vertical-align: middle on that span. Don't know how cross-browser compliant this is though, I've only tested it in webkit browsers.
Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"
Reset the kernel at the console, and the plot will appear in a separate window
If you just need to search for one string within another, use the index
function (or rindex
if you want to start scanning from the end of the string):
if (index($string, $substring) != -1) {
print "'$string' contains '$substring'\n";
}
To search a string for a pattern match, use the match operator m//
:
if ($string =~ m/pattern/) {
print "'$string' matches the pattern\n";
}
The Substring
method works perfectly when you only want the Hours:Minutes:Seconds. It's simple, clean code and easy to understand.
var yourTimeSpan = DateTime.Now - DateTime.Now.AddMinutes(-2);
var formatted = yourTimeSpan.ToString().Substring(0,8);// 00:00:00
Console.WriteLine(formatted);
You can use .is()
.
if( $('#leftmenu').is(':empty') ) {
// ...
Or you could just test the length
property to see if one was found.
if( $('#leftmenu:empty').length ) {
// ...
Keep in mind that empty means no white space either. If there's a chance that there will be white space, then you can use $.trim()
and check for the length of the content.
if( !$.trim( $('#leftmenu').html() ).length ) {
// ...
Heres a another take on this problem, using recursion and without using mutable variables. Also, im not using setInterval
so theres no cleanup that has to be done.
Having this HTML
<section id="testimonials">
<h2>My testimonial spinner</h2>
<div class="testimonial">
<p>First content</p>
</div>
<div class="testimonial">
<p>Second content</p>
</div>
<div class="testimonial">
<p>Third content</p>
</div>
</section>
Using ES2016
Here you call the function recursively and update the arguments.
const testimonials = $('#testimonials')
.children()
.filter('div.testimonial');
const showTestimonial = index => {
testimonials.hide();
$(testimonials[index]).fadeIn();
return index === testimonials.length
? showTestimonial(0)
: setTimeout(() => { showTestimonial(index + 1); }, 10000);
}
showTestimonial(0); // id of the first element you want to show.
Get rid of the semicolon after WordGame
.
You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.
Use aggregation substring search (with index!!!):
db.collection.aggregate([{
$project : {
fieldExists : {
$indexOfBytes : ['$field', 'string']
}
}
}, {
$match : {
fieldExists : {
$gt : -1
}
}
}, {
$limit : 5
}
]);
You can set proxies using environment variables.
import os
os.environ['http_proxy'] = '127.0.0.1'
os.environ['https_proxy'] = '127.0.0.1'
urllib2
will add proxy handlers automatically this way. You need to set proxies for different protocols separately otherwise they will fail (in terms of not going through proxy), see below.
For example:
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
# next line will fail (will not go through the proxy) (https)
urllib2.urlopen('https://www.google.com')
Instead
proxy = urllib2.ProxyHandler({
'http': '127.0.0.1',
'https': '127.0.0.1'
})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
# this way both http and https requests go through the proxy
urllib2.urlopen('http://www.google.com')
urllib2.urlopen('https://www.google.com')
I was also plagued by this error, and after trying all the other answers, magically found the following solution:
Delete package-lock.json and the node_modules folder, then run npm install
again.
If that doesn't work, try running these in order:
npm install
npm cache clean --force
npm install -g npm
npm install
(taken from @Thisuri's answer and @Mathias Falci's comment respectively)
and then re-deleting the above files and re-running npm install
.
Worked for me!
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
just use UPDATE query without condition like this
UPDATE tablename SET online_status=0;
package com.android.jigsawtest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurafaceClass extends SurfaceView implements
SurfaceHolder.Callback {
Bitmap mBitmap;
Paint paint =new Paint();
public SurafaceClass(Context context) {
super(context);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
// TODO Auto-generated constructor stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mBitmap, 0, 0, paint);
}
}
You can escape the quotes with a backslash:
"I asked my son's teacher, \"How is my son doing now?\""
As of PHP >= 5.4.0
$translatedString = transliterator_transliterate('Any-Latin; Latin-ASCII; [\u0080-\u7fff] remove', $string);
You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.
If you're targeting decent browsers only, then just make use of CSS3:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<label class="unselectable">Unselectable label</label>
If you'd like to cover older browsers as well, then consider this JavaScript fallback:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734</title>
<script>
window.onload = function() {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
disableSelection(labels[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function() { return false; };
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function() { return false; };
}
}
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
If you're already using jQuery, then here's another example which adds a new function disableSelection()
to jQuery so that you can use it anywhere in your jQuery code:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734 with jQuery</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.fn.extend({
disableSelection: function() {
this.each(function() {
if (typeof this.onselectstart != 'undefined') {
this.onselectstart = function() { return false; };
} else if (typeof this.style.MozUserSelect != 'undefined') {
this.style.MozUserSelect = 'none';
} else {
this.onmousedown = function() { return false; };
}
});
}
});
$(document).ready(function() {
$('label').disableSelection();
});
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
For me, the user was mongod
instead of mongodb
sudo chown mongod:mongod /newlocation
You can see the logs for errors if the service fails:
/var/log/mongodb/mongod.log
If you have a List of type string that you want in a drop down list I do the following:
EDIT: Clarified, making it a fuller example.
public class ShipDirectory
{
public string ShipDirectoryName { get; set; }
public List<string> ShipNames { get; set; }
}
ShipDirectory myShipDirectory = new ShipDirectory()
{
ShipDirectoryName = "Incomming Vessels",
ShipNames = new List<string>(){"A", "A B"},
}
myShipDirectory.ShipNames.Add("Aunt Bessy");
@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })
Which gives a drop down list like so:
<select id="ShipNames" name="ShipNames" style="width:500px">
<option value="">Select a Ship...</option>
<option>A</option>
<option>A B</option>
<option>Aunt Bessy</option>
</select>
To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):
public ActionResult MyActionName(MyViewModel model)
Access the ShipNames value like so: model.ShipNames
If you just want to access the drop down list on post then the signature becomes:
public ActionResult MyActionName(string ShipNames)
EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.
SELECT name, LENGTH(name) AS mlen
FROM mytable
ORDER BY
mlen DESC
LIMIT 1
null=True
sets NULL
(versus NOT NULL
) on the column in your DB. Blank values for Django field types such as DateTimeField
or ForeignKey
will be stored as NULL
in the DB.
blank
determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True
then the field will not be required, whereas if it's False
the field cannot be blank.
The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL
values for that field. The exception is CharField
s and TextField
s, which in Django are never saved as NULL
. Blank values are stored in the DB as an empty string (''
).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False
if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR
and TEXT
types are never saved as NULL
by Django, so null=True
is unnecessary. However, you can manually set one of these fields to None
to force set it as NULL
. If you have a scenario where that might be necessary, you should still include null=True
.
I tried the accepted solution and it didn't work for me. I use the browser debugger and found out the actual height that should be used is the clientHeight
BUT you have to put this into the updated()
hook for the whole solution to work.
data(){
return {
conversation: [
{
}
]
},
mounted(){
EventBus.$on('msg-ctr--push-msg-in-conversation', textMsg => {
this.conversation.push(textMsg)
// Didn't work doing scroll here
})
},
updated(){ <=== PUT IT HERE !!
var elem = this.$el
elem.scrollTop = elem.clientHeight;
},
document.getElementById('TextBoxID').readOnly = true; //to enable readonly
document.getElementById('TextBoxID').readOnly = false; //to disable readonly
Right and Left shift work on same way here is How Right Shift works; The Right Shift: The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its general form:
value >> num
Here, num specifies the number of positions to right-shift the value in value. That is, the >> moves all of the bits in the specified value to the right the number of bit positions specified by num. The following code fragment shifts the value 32 to the right by two positions, resulting in a being set to 8:
int a = 32;
a = a >> 2; // a now contains 8
When a value has bits that are “shifted off,” those bits are lost. For example, the next code fragment shifts the value 35 to the right two positions, which causes the two low-order bits to be lost, resulting again in a being set to 8.
int a = 35;
a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens:
00100011 35 >> 2
00001000 8
Each time you shift a value to the right, it divides that value by two—and discards any remainder. You can take advantage of this for high-performance integer division by 2. Of course, you must be sure that you are not shifting any bits off the right end.
When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with the previous contents of the top bit. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right. For example, –8 >> 1
is –4
, which, in binary, is
11111000 –8 >>1
11111100 –4
It is interesting to note that if you shift –1 right, the result always remains –1, since sign extension keeps bringing in more ones in the high-order bits. Sometimes it is not desirable to sign-extend values when you are shifting them to the right. For example, the following program converts a byte value to its hexadecimal string representation. Notice that the shifted value is masked by ANDing it with 0x0f to discard any sign-extended bits so that the value can be used as an index into the array of hexadecimal characters.
// Masking sign extension.
class HexByte {
static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
byte b = (byte) 0xf1;
System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
}
}
Here is the output of this program:
b = 0xf1
Installed it using pip on Ubuntu 15.10 using a normal user, it was put in ~/.local/bin/virtualenvwrapper.sh
which I found by running:
$ find / -name virtualenvwrapper.sh 2>/dev/null
You are getting confused with transclude: true
, which would append the inner content.
replace: true
means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1>
tag.
http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview
For example without replace:true
<div myd1><span class="replaced" myd1="">directive template1</span></div>
and with replace:true
<span class="replaced" myd1="">directive template1</span>
As you can see in the latter example, the div tag is indeed replaced.
The latest version of angular
is only setup for evergreen browsers by default...
The current setup is for so-called "evergreen" browsers; the last versions of browsers that automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
This also includes firefox, although not mentioned.
See here for more information on browser support along with a list of suggested polyfills for specific browsers. https://angular.io/guide/browser-support#polyfill-libs
To achieve this, go into polyfills.ts
(in the src
folder by default) and just uncomment the following imports:
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';
Note that the comment is literally in the file, so this is easy to find.
If you are still having issues, you can downgrade the target
property to es5
in tsconfig.json
as @MikeDub
suggested. What this does is change the compilation output of any es6
definitions to es5
definitions. For example, fat arrow functions (()=>{}
) will be compiled to anonymous functions (function(){}
). You can find a list of es6 supported browsers here.
• I was asked in the comments by @jackOfAll
whether IE11 polyfills are loaded even if the user is in an evergreen browser which doesn't need them. The answer is, yes they are! The inclusion of the IE11 polyfills will take your polyfill file from ~162KB
to ~258KB
as of Aug 8 '17. I have invested in trying to solve this however it does not seem possible at this time.
• If you are getting errors in IE10 and below, go into you package.json
and downgrade webpack-dev-server
to 2.7.1
specifically. Versions higher than this no longer support "older" IE versions.
Having is only used with aggregation but where with non aggregation statements If you have where word put it before aggregation (group by)
Use the finish
method. It is the simpler and easier method.
this.finish();
The current answers suggest a workaround but it's bugged me why this doesn't exist, so I've created a babel
plugin which does this.
Install it using:
npm i --save-dev babel-plugin-wildcard
then add it to your .babelrc
with:
{
"plugins": ["wildcard"]
}
see the repo for detailed install info
This allows you to do this:
import * as Things from './lib/things';
// Do whatever you want with these :D
Things.ThingA;
Things.ThingB;
Things.ThingC;
again, the repo contains further information on what exactly it does, but doing it this way avoids creating index.js
files and also happens at compile-time to avoid doing readdir
s at runtime.
Also with a newer version you can do exactly like your example:
import { ThingsA, ThingsB, ThingsC } from './lib/things/*';
works the same as the above.
It is rule of thumb that the first layer in your network should be the same shape as your data. For example our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.
As of Elasticsearch 7.7, you have to specify the content type also:
curl -s -H "Content-Type: application/json" -XPOST localhost:9200/_bulk --data-binary @<absolute path to JSON file>
Refactored the code from balexandre a little so objects gets disposed and the new language features of C# 3.5+ are used (Linq, var, etc). Also renamed the variables to more meaningful names. I also merged some of the functions to be able to do more configuration with less WMI interaction. I removed the WINS code as I don't need to configure WINS anymore. Feel free to add the WINS code if you need it.
For the case anybody likes to use the refactored/modernized code I put it back into the community here.
/// <summary>
/// Helper class to set networking configuration like IP address, DNS servers, etc.
/// </summary>
public class NetworkConfigurator
{
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="ipAddress">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public void SetIP(string ipAddress, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"]))
{
using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
{
// Set new IP address and subnet if needed
if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
{
if (!String.IsNullOrEmpty(ipAddress))
{
newIP["IPAddress"] = new[] { ipAddress };
}
if (!String.IsNullOrEmpty(subnetMask))
{
newIP["SubnetMask"] = new[] { subnetMask };
}
managementObject.InvokeMethod("EnableStatic", newIP, null);
}
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
{
newGateway["DefaultIPGateway"] = new[] { gateway };
newGateway["GatewayCostMetric"] = new[] { 1 };
managementObject.InvokeMethod("SetGateways", newGateway, null);
}
}
}
}
}
}
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nic">NIC address</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public void SetNameservers(string nic, string dnsServers)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
{
using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
{
newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
}
}
I had an issue with the same thing. ChromeOptions is very weird because it's not integrated with the desiredcapabilities like you would think. I forget the exact details, but basically ChromeOptions will reset to default certain values based on whether you did or did not pass a desired capabilities dict.
I did the following monkey-patch that allows me to specify my own dict without worrying about the complications of ChromeOptions
change the following code in /selenium/webdriver/chrome/webdriver.py:
def __init__(self, executable_path="chromedriver", port=0,
chrome_options=None, service_args=None,
desired_capabilities=None, service_log_path=None, skip_capabilities_update=False):
"""
Creates a new instance of the chrome driver.
Starts the service and then creates new instance of chrome driver.
:Args:
- executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
- port - port you would like the service to run, if left as 0, a free port will be found.
- desired_capabilities: Dictionary object with non-browser specific
capabilities only, such as "proxy" or "loggingPref".
- chrome_options: this takes an instance of ChromeOptions
"""
if chrome_options is None:
options = Options()
else:
options = chrome_options
if skip_capabilities_update:
pass
elif desired_capabilities is not None:
desired_capabilities.update(options.to_capabilities())
else:
desired_capabilities = options.to_capabilities()
self.service = Service(executable_path, port=port,
service_args=service_args, log_path=service_log_path)
self.service.start()
try:
RemoteWebDriver.__init__(self,
command_executor=self.service.service_url,
desired_capabilities=desired_capabilities)
except:
self.quit()
raise
self._is_remote = False
all that changed was the "skip_capabilities_update" kwarg. Now I just do this to set my own dict:
capabilities = dict( DesiredCapabilities.CHROME )
if not "chromeOptions" in capabilities:
capabilities['chromeOptions'] = {
'args' : [],
'binary' : "",
'extensions' : [],
'prefs' : {}
}
capabilities['proxy'] = {
'httpProxy' : "%s:%i" %(proxy_address, proxy_port),
'ftpProxy' : "%s:%i" %(proxy_address, proxy_port),
'sslProxy' : "%s:%i" %(proxy_address, proxy_port),
'noProxy' : None,
'proxyType' : "MANUAL",
'class' : "org.openqa.selenium.Proxy",
'autodetect' : False
}
driver = webdriver.Chrome( executable_path="path_to_chrome", desired_capabilities=capabilities, skip_capabilities_update=True )
Try using required="true"
in bootstrap 3
Another way round it would be to stop UAC then restart it. Create a CMD file with the following code;
Rem Stop UAC %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f rem force reboot Start ShutDown /R /F /T 30
You'll need to right click on the CMD file and use run as admin. once you have finished what you are doing restart UAC with the following code (no need to use run as admin this time);
%windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f
rem force reboot Start ShutDown /R /F /T 30
The down sides to using this method is have to right click and use run as admin to close UAC down and you have to reboot for it to take effect.
BTW there are several reasons why you would need to write to the forbidden areas...the first two that springs to mind would be to run a batch file to append host to prevent your browser going to dodgy sites or to copy license keys in a silent install.
It also posible string replacement with stringByReplacingCharactersInRange:withString:
for (int i = 0; i < card.length - 4; i++) {
if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
NSRange range = NSMakeRange(i, 1);
card = [card stringByReplacingCharactersInRange:range withString:@"*"];
}
} //out: **** **** **** 1234
I think you cannot get it as String
but you can get it as int
by get resource id
:
int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());
children()
only looks at the immediate children of the node, while find()
traverses the entire DOM below the node, so children()
should be faster given equivalent implementations. However, find()
uses native browser methods, while children()
uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.
Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM, i.e., choose the appropriate method based on the results you desire, not the speed of the method. If performance is truly an issue, then experiment to find the best solution and use that (or see some of the benchmarks in the other answers here).
AngularJS has some methods called JQlite so we can use it. see link
Select the element in DOM is
angular.element( document.querySelector( '#div1' ) );
add the class like .addClass('alpha');
So finally
var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');
I got the answer to my own question, ant this is:
select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))
Where N is the number of characters to remove. This avoids to write the complex column/string twice
Below are some common Big-O functions while analyzing algorithms.
(n = size of input, c = some constant)
Here is the model graph representing Big-O complexity of some functions
cheers :-)
graph credits http://bigocheatsheet.com/
Array
in JSON
are indexed array only, so the structure you're trying to get is not valid Json/Javascript.
PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.
If you want to get such structure you can do:
$indexedOnly = array();
foreach ($associative as $row) {
$indexedOnly[] = array_values($row);
}
json_encode($indexedOnly);
Will returns something like:
[
[0, "name1", "n1"],
[1, "name2", "n2"],
]
Here are some I've used to filter programmers applying for jobs as C# programmers:
What's the difference between a reference type and a value type?
Explain the IDisposable interface, which C# language construct requires it and how you would implement it.
Which exception would you throw if a null is passed as an argument to a method which has a contract that doesn't allow nulls for that parameter?
preferred way, using MySQLi extension:
$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
$result = $mysqli->query("SELECT id FROM mytable WHERE city = 'c7'");
if($result->num_rows == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
$mysqli->close();
deprecated:
$result = mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
I prefer a closure approach.
I still use new
.
I don't use Object.create
.
I don't use this
.
I still use new
as I like the declarative nature of it.
Consider this for simple inheritance.
window.Quad = (function() {
function Quad() {
const wheels = 4;
const drivingWheels = 2;
let motorSize = 0;
function setMotorSize(_) {
motorSize = _;
}
function getMotorSize() {
return motorSize;
}
function getWheelCount() {
return wheels;
}
function getDrivingWheelCount() {
return drivingWheels;
}
return Object.freeze({
getWheelCount,
getDrivingWheelCount,
getMotorSize,
setMotorSize
});
}
return Object.freeze(Quad);
})();
window.Car4wd = (function() {
function Car4wd() {
const quad = new Quad();
const spareWheels = 1;
const extraDrivingWheels = 2;
function getSpareWheelCount() {
return spareWheels;
}
function getDrivingWheelCount() {
return quad.getDrivingWheelCount() + extraDrivingWheels;
}
return Object.freeze(Object.assign({}, quad, {
getSpareWheelCount,
getDrivingWheelCount
}));
}
return Object.freeze(Car4wd);
})();
let myQuad = new Quad();
let myCar = new Car4wd();
console.log(myQuad.getWheelCount()); // 4
console.log(myQuad.getDrivingWheelCount()); // 2
console.log(myCar.getWheelCount()); // 4
console.log(myCar.getDrivingWheelCount()); // 4 - The overridden method is called
console.log(myCar.getSpareWheelCount()); // 1
Feedback encouraged.
CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
-- Add the parameters for the stored procedure here
@SatrtDate as DateTime,
@EndDate as dateTime,
@DatePart as varchar(2),
@OutPutFormat as int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
Declare @DateList Table
(Date varchar(50))
WHILE @SatrtDate<= @EndDate
BEGIN
INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
IF Upper(@DatePart)='DD'
SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
IF Upper(@DatePart)='MM'
SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
IF Upper(@DatePart)='YY'
SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
END
SELECT * FROM @DateList
END
Just put this Code and call the SP in This way
exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106
A Docker container might be built without a shell (e.g. https://github.com/fluent/fluent-bit-docker-image/issues/19).
In this case, you can copy-in a statically compiled shell and execute it, e.g.
docker create --name temp-busybox busybox:1.31.0
docker cp temp-busybox:/bin/busybox busybox
docker cp busybox mycontainerid:/busybox
docker exec -it mycontainerid /bin/busybox sh
What you need is a quadrangle instead of a rotated rectangle.
RotatedRect
will give you incorrect results. Also you will need a perspective projection.
Basicly what must been done is:
I implemented a class Quadrangle
which takes care of contour to quadrangle conversion and will also transform it over the right perspective.
See a working implementation here: Java OpenCV deskewing a contour
The class below should do the trick. Just create an instance, call the "multiply" method, and provide the source input stream and the amount of duplicates you need.
Important: you must consume all cloned streams simultaneously in separate threads.
package foo.bar;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class InputStreamMultiplier {
protected static final int BUFFER_SIZE = 1024;
private ExecutorService executorService = Executors.newCachedThreadPool();
public InputStream[] multiply(final InputStream source, int count) throws IOException {
PipedInputStream[] ins = new PipedInputStream[count];
final PipedOutputStream[] outs = new PipedOutputStream[count];
for (int i = 0; i < count; i++)
{
ins[i] = new PipedInputStream();
outs[i] = new PipedOutputStream(ins[i]);
}
executorService.execute(new Runnable() {
public void run() {
try {
copy(source, outs);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return ins;
}
protected void copy(final InputStream source, final PipedOutputStream[] outs) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int n = 0;
try {
while (-1 != (n = source.read(buffer))) {
//write each chunk to all output streams
for (PipedOutputStream out : outs) {
out.write(buffer, 0, n);
}
}
} finally {
//close all output streams
for (PipedOutputStream out : outs) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
First check To see how many aliases you have and what are they, you can initiate this command git remote -v
Then see in which repository you are in then try git remote set-url --add [Then your repositpory link] git push -u origin master
For a somewhat narrow use case, docker issue 8838 mentions this sort-of-hack:
You just stop docker daemon and change container config in /var/lib/docker/containers/[container-id]/config.json (sic)
This solution updates the environment variables without the need to delete and re-run the container, having to migrate volumes and remembering parameters to run
.
However, this requires a restart of the docker daemon. And, until issue issue 2658 is addressed, this includes a restart of all containers.
Most Java ".properties" files can be split by assuming the "=" is the separator - but the format is significantly more complicated than that and allows for embedding spaces, equals, newlines and any Unicode characters in either the property name or value.
I needed to load some Java properties for a C# application so I have implemented JavaProperties.cs to correctly read and write ".properties" formatted files using the same approach as the Java version - you can find it at http://www.kajabity.com/index.php/2009/06/loading-java-properties-files-in-csharp/.
There, you will find a zip file containing the C# source for the class and some sample properties files I tested it with.
Enjoy!
Imports System.Net.NetworkInformation
Public Function PingHost(ByVal nameOrAddress As String) As Boolean
Dim pingable As Boolean = False
Dim pinger As Ping
Dim lPingReply As PingReply
Try
pinger = New Ping()
lPingReply = pinger.Send(nameOrAddress)
MessageBox.Show(lPingReply.Status)
If lPingReply.Status = IPStatus.Success Then
pingable = True
Else
pingable = False
End If
Catch PingException As Exception
pingable = False
End Try
Return pingable
End Function
I fixed this issue on Windows 10 by uninstalling node from Add or remove programs -> Node.js
Then I installed version 11.15.0 from https://nodejs.org/download/release/v11.15.0/
Choose node-v11.15.0-x64.msi if your running windows 64bit.
I really don't like the fact that, because of the "promise" way of doing things, the consumer of the service that uses $http has to "know" about how to unpack the response.
I just want to call something and get the data out, similar to the old $scope.items = Data.getData();
way, which is now deprecated.
I tried for a while and didn't come up with a perfect solution, but here's my best shot (Plunker). It may be useful to someone.
app.factory('myService', function($http) {
var _data; // cache data rather than promise
var myService = {};
myService.getData = function(obj) {
if(!_data) {
$http.get('test.json').then(function(result){
_data = result.data;
console.log(_data); // prove that it executes once
angular.extend(obj, _data);
});
} else {
angular.extend(obj, _data);
}
};
return myService;
});
Then controller:
app.controller('MainCtrl', function( myService,$scope) {
$scope.clearData = function() {
$scope.data = Object.create(null);
};
$scope.getData = function() {
$scope.clearData(); // also important: need to prepare input to getData as an object
myService.getData($scope.data); // **important bit** pass in object you want to augment
};
});
Flaws I can already spot are
getData
can only accept the obj
parameter in the form of an object (although it could also accept an array), which won't be a problem for many applications, but it's a sore limitation$scope.data
with = {}
to make it an object (essentially what $scope.clearData()
does above), or = []
for an array, or it won't work (we're already having to assume something about what data is coming). I tried to do this preparation step IN getData
, but no luck.Nevertheless, it provides a pattern which removes controller "promise unwrap" boilerplate, and might be useful in cases when you want to use certain data obtained from $http in more than one place while keeping it DRY.
The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website.
You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does.
Use the following command:
sudo apt-get install python3-tk
The following commands do not work:
sudo apt-get install python3-tkinter
sudo apt-get install python3-Tkinter
pip3 install Tkinter
pip3 install tkinter
2 ways to enable TLSv1.1 and TLSv1.2:
schemeRegistry.register(new Scheme("https", new TlsSniSocketFactory(), port));
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
I don't think you should ever provide the False
value in square brackets (ever), also the column values when they are more than one, then only they are provided as a list! Not like ['one']
.
test = df.sort_values(by='one', ascending = False)
You could also do:
del /s /p *.{your extension here}
The /p
will prompt you for each found file, if you're nervous about deleting something you shouldn't.
To answer the question : if you want to exclude certain files of a checkout, you can use sparse-checkout
In .git/info/sparse-checkout
, define what you want to keep. Here, we want all (*) but (note the exclamation mark) config.php :
/* !/config.php
Tell git you want to take sparse-checkout into account
git config core.sparseCheckout true
If you already have got this file locally, do what git does on a sparse checkout (tell it it must exclude this file by setting the "skip-worktree" flag on it)
git update-index --skip-worktree config.php
Enjoy a repository where your config.php file is yours - whatever changes are on the repository.
Please note that configuration values SHOULDN'T be in source control :
- It is a potential security breach
- It causes problems like this one for deployment
This means you MUST exclude them (put them in .gitignore before first commit), and create the appropriate file on each instance where you checkout your app (by copying and adapting a "template" file)
Note that, once a file is taken in charge by git, .gitignore won't have any effect.
Given that, once the file is under source control, you only have two choices () :
rebase all your history to remove the file (with git filter-branch
)
create a commit that removes the file. It is like fighting a loosing battle, but, well, sometimes you have to live with that.
A class that will play a WAV file, blocking until the sound has finished playing:
class Sound implements Playable {
private final Path wavPath;
private final CyclicBarrier barrier = new CyclicBarrier(2);
Sound(final Path wavPath) {
this.wavPath = wavPath;
}
@Override
public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {
try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
final Clip clip = AudioSystem.getClip()) {
listenForEndOf(clip);
clip.open(audioIn);
clip.start();
waitForSoundEnd();
}
}
private void listenForEndOf(final Clip clip) {
clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
});
}
private void waitOnBarrier() {
try {
barrier.await();
} catch (final InterruptedException ignored) {
} catch (final BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
private void waitForSoundEnd() {
waitOnBarrier();
}
}
Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
Use of the netstat -a
command will give you a list of connections to your system/server where you are executing the command.
For example it will display as below, where 35070 is the port number
TCP 10.144.0.159:**52121** sd-s-fgh:35070 ESTABLISHED
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;
if you run this with node it would console log 200 as long as google is not down.
For me it works without the AbstractBinder
if I include the following dependencies in my web application (running on Tomcat 8.5, Jersey 2.27):
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-cdi1x</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey-version}</version>
</dependency>
It works with CDI 1.2 / CDI 2.0 for me (using Weld 2 / 3 respectively).
db.query(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
TABLE_ROW_ID + "=" + rowID
, here =
is the where
clause. To select all values you will have to give all column names:
or you can use a raw query like this
db.rawQuery("SELECT * FROM permissions_table WHERE name = 'Comics' ", null);
and here is a good tutorial for database.
Try this using HTML like here:
var myDate = window.document.getElementById("startdate").value;
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue
Basically it's because MS Excel can't decide how to open the file with such content.
When you put ID
as the first character in a Spreadsheet type file, it matches the specification of a SYLK file and MS Excel (and potentially other Spreadsheet Apps) try to open it as a SYLK file. But at the same time, it does not meet the complete specification of a SYLK file since rest of the values in the file are comma separated. Hence, the error is shown.
To solve the issue, change "ID"
to "id"
and it should work as expected.
This is weird. But, yeah!
Also trying to minimize file access by using file object less.
I tested and the code below works perfect.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CsvWriter {
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {
StringBuilder sb = new StringBuilder();
sb.append("id,");
sb.append(',');
sb.append("Name");
sb.append('\n');
sb.append("1");
sb.append(',');
sb.append("Prashant Ghimire");
sb.append('\n');
writer.write(sb.toString());
System.out.println("done!");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
This constructor was deprecated in API level 26.1.0. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.
You can simply use the zoom property:
#myContainer{
zoom: 0.5;
-moz-transform: scale(0.5);
}
Where myContainer contains all the elements you're editing. This is supported in all major browsers.
Another good solution. You need create a file typings.json in root directory of project with content:
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160725163759",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160909174046"
}
}
Then install global or local typings package, if it not installed (i am install it global):
sudo npm install --global typings
In project root directory run command:
typings install
After that problem is solved. Not needed to change tsconfig target to es6 or es7. Your web application do not support after that some old version of browsers.
I faced the same problem and here's the solution I implemented with ES6
code
let id = 0; // This is a kind of global variable accessible for every instance
class Animal {
constructor(name){
this.name = name;
this.id = id++;
}
foo(){}
// Executes some cool stuff
}
cat = new Animal("Catty");
console.log(cat.id) // 1
Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::
.
Here is setting headers from github sample:
StringRequest myReq = new StringRequest(Method.POST,
"http://ave.bolyartech.com/params.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws
com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality.
However, as of php7.1, you can define your class constants with access modifiers (public
, private
or protected
).
A work around would be to define your constant as private
or protected
and then make them readable via a static function
. This function should only return the constant values if called from the static context.
You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.
Credits: http://dwellupper.io/post/48/defining-class-constants-in-php
For me, I was writing to a file that is opened in Excel.
You may want one of these, so to correspond to the Bootstrap layout:
<div class="col-xs-12">
<hr >
</div>
<!-- or -->
<div class="col-xs-12">
<hr style="border-style: dashed; border-top-width: 2px;">
</div>
<!-- or -->
<div class="col-xs-12">
<hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>
Without a DIV
grid element included, layout may brake on different devices.
A Radio Button List instead of a Radio button creates unique id tags name_0, name_1 etc. An easy way to test which is selected is by assigning a css class like
var deliveryService;
$('.deliveryservice input').each(function () {
if (this.checked) {
deliveryService = this.value
}
If you only want to strip the quotes from the ends of the string (not the middle), and there is a chance that there can be spaces at either end of the string (i.e. parsing a CSV format file where there is a space after the commas), then you need to call the Trim function twice...for example:
string myStr = " \"sometext\""; //(notice the leading space)
myStr = myStr.Trim('"'); //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"'); //(would get what you want: sometext)
Use WORKSPACE environment variable to change workspace directory.
If doing using Jenkinsfile, use following code :
dir("${env.WORKSPACE}/aQA"){
sh "pwd"
}
To copy remote-to-remote files you can use the synchronize module with 'delegate_to: source-server
' keyword:
- hosts: serverB
tasks:
- name: Copy Remote-To-Remote (from serverA to serverB)
synchronize: src=/copy/from_serverA dest=/copy/to_serverB
delegate_to: serverA
This playbook can run from your machineC.
The query below will result in dd-mmm-yy format.
select
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+
Right(Year(getdate()),2)
As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */
in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.
Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME
which has a unique constraint on a column called IDX_COL_NAME
.
INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */
INTO TABLE_NAME(
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n)
SELECT
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n);
This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.
If CSS writing-mode: sideways-lr
is what you prefer, and you happen to run into chromium/chrome based browser. You may try
{
writing-mode: vertical-rl;
transform: rotate(180deg);
}
so all modern browsers support it now.
reference: https://bugs.chromium.org/p/chromium/issues/detail?id=680331#c4
Here's some sample code. This worked for me.
<LinearLayout
android:gravity="center"
>
<TextView
android:layout_gravity="center"
/>
<Button
android:layout_gravity="center"
/>
</LinearLayout>
So you're designing the Linear Layout to place all its contents (TextView and Button) in its center, and then the TextView and Button are placed relative to the center of the Linear Layout.
System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));
Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.
A Magento Module is a group of directories containing blocks, controllers, helpers, and models that are needed to create a specific store feature. It is the unit of customization in the Magento platform. Magento Modules can be created to perform multiple functions with supporting logic to influence user experience and storefront appearance. It has a life cycle that allows them to be installed, deleted, or disabled. From the perspective of both merchants and extension developers, modules are the central unit of the Magento platform.
Declaration of Module
We have to declare the module by using the configuration file. As Magento 2 search for configuration module in etc directory of the module. So now we will create configuration file module.xml.
The code will look like this:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Cloudways_Mymodule" setup_version="1.0.0"></module> </config>
Registration of Module The module must be registered in the Magento 2 system by using Magento Component Registrar class. Now we will create the file registration.php in the module root directory:
app/code/Cloudways/Mymodule/registration.php
The Code will look like this:
?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Cloudways_Mymodule',
__DIR__
);
Check Module Status After following the steps above, we would have created a simple module. Now we are going to check the status of the module and whether it is enabled or disabled by using the following command line:
php bin/magento module:status
php bin/magento module:enable Cloudways_Mymodule
Share your feedback once you have gone through complete process
An alternative: you can use a "hidden" applet element which implements this exist-check using a privileged action object and override your run method by:
File file = new File(yourPath);
return file.exists();
If you want to add a default value for the already created column, this works for me:
ALTER TABLE Persons
ALTER credit SET DEFAULT 0.0;
One thing that hasn't been mentioned is that a SOAP envelope can contain headers as well as body parts. This lets you use the full expressiveness of XML to send and receive out of band information. REST, as far as I know, limits you to HTTP Headers and result codes.
(otoh, can you use cookies with a REST service to send "header"-type out of band data?)
with open('one.txt','r')as myFile:
str1=myFile.read()
print(str1)
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
for i in punctuation:
str1 = str1.replace(i," ")
myList=[]
myList.extend(str1.split(" "))
print (str1)
for i in myList:
print(i,end='\n')
print ("____________")
Make a script like this:
#!/bin/bash
echo $((0x$1)).$((0x$2)).$((0x$3)).$((0x$4))
Example:
sh converthextoip.sh c0 a8 00 0b
Result:
192.168.0.11
Here is the example:
var charCode = "a".charCodeAt(0);_x000D_
console.log(charCode);
_x000D_
Or if you have longer strings:
var string = "Some string";_x000D_
_x000D_
for (var i = 0; i < string.length; i++) {_x000D_
console.log(string.charCodeAt(i));_x000D_
}
_x000D_
String.charCodeAt(x)
method will return ASCII character code at a given position.
Probably because it's trying to execute "export" as an external command, and it's a shell internal.
Although this is the accepted answer, toto_tico's answer below is better :)
Try making the onclick js use 'return' to ensure the desired return value gets used...
<button type="button" value="click me" onclick="return check_me();" />
Just return the following:
return Unauthorized();
1-press CTRL F
2-paste the copied text in search bar
3-press CTRL A followed by CTRL C to copy the text again from search
4-paste in Notepad++
5-replace 'space'
with ','
Definitely not both. Other than that I'd have to say it's a personal preference. I'd use css if I had many images the same size to reduce code.
.my_images img {width: 20px; height:20px}
In the long term CSS may win out due to HTML attribute deprecation and more likely due to the growth of vector image formats like SVG where it can actually make sense to scale images using non-pixel based units like % or em.
Google is right :-)
Google's formula creates numbers between: min and max Your formula creates numbers between: min and (min+max)
You can do as @Hugo of @Laurent said, or you can use git rebase
to delete the commits you want to get rid off, if you know which ones. I tend to use git rebase -i head~N
(where N is a number, allowing you to manipulate the last N commits) for this kind of operations.
apply
and transform
There are two major differences between the transform
and apply
groupby methods.
apply
implicitly passes all the columns for each group as a DataFrame to the custom function.transform
passes each column for each group individually as a Series to the custom function.apply
can return a scalar, or a Series or DataFrame (or numpy array or even list).transform
must return a sequence (a one dimensional Series, array or list) the same length as the group.So, transform
works on just one Series at a time and apply
works on the entire DataFrame at once.
It can help quite a bit to inspect the input to your custom function passed to apply
or transform
.
Let's create some sample data and inspect the groups so that you can see what I am talking about:
import pandas as pd
import numpy as np
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'],
'a':[4,5,1,3], 'b':[6,10,3,11]})
State a b
0 Texas 4 6
1 Texas 5 10
2 Florida 1 3
3 Florida 3 11
Let's create a simple custom function that prints out the type of the implicitly passed object and then raised an error so that execution can be stopped.
def inspect(x):
print(type(x))
raise
Now let's pass this function to both the groupby apply
and transform
methods to see what object is passed to it:
df.groupby('State').apply(inspect)
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
RuntimeError
As you can see, a DataFrame is passed into the inspect
function. You might be wondering why the type, DataFrame, got printed out twice. Pandas runs the first group twice. It does this to determine if there is a fast way to complete the computation or not. This is a minor detail that you shouldn't worry about.
Now, let's do the same thing with transform
df.groupby('State').transform(inspect)
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
RuntimeError
It is passed a Series - a totally different Pandas object.
So, transform
is only allowed to work with a single Series at a time. It is impossible for it to act on two columns at the same time. So, if we try and subtract column a
from b
inside of our custom function we would get an error with transform
. See below:
def subtract_two(x):
return x['a'] - x['b']
df.groupby('State').transform(subtract_two)
KeyError: ('a', 'occurred at index a')
We get a KeyError as pandas is attempting to find the Series index a
which does not exist. You can complete this operation with apply
as it has the entire DataFrame:
df.groupby('State').apply(subtract_two)
State
Florida 2 -2
3 -8
Texas 0 -2
1 -5
dtype: int64
The output is a Series and a little confusing as the original index is kept, but we have access to all columns.
It can help even more to display the entire pandas object within the custom function, so you can see exactly what you are operating with. You can use print
statements by I like to use the display
function from the IPython.display
module so that the DataFrames get nicely outputted in HTML in a jupyter notebook:
from IPython.display import display
def subtract_two(x):
display(x)
return x['a'] - x['b']
The other difference is that transform
must return a single dimensional sequence the same size as the group. In this particular instance, each group has two rows, so transform
must return a sequence of two rows. If it does not then an error is raised:
def return_three(x):
return np.array([1, 2, 3])
df.groupby('State').transform(return_three)
ValueError: transform must return a scalar value for each group
The error message is not really descriptive of the problem. You must return a sequence the same length as the group. So, a function like this would work:
def rand_group_len(x):
return np.random.rand(len(x))
df.groupby('State').transform(rand_group_len)
a b
0 0.962070 0.151440
1 0.440956 0.782176
2 0.642218 0.483257
3 0.056047 0.238208
transform
If you return just a single scalar from your custom function, then transform
will use it for each of the rows in the group:
def group_sum(x):
return x.sum()
df.groupby('State').transform(group_sum)
a b
0 9 16
1 9 16
2 4 14
3 4 14
The method newLine()
ensures a platform-compatible new line is added (0Dh 0Ah
for DOS, 0Dh
for older Macs, 0Ah
for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.
I was able to absolutely position a right-floated element with one layer of nesting and a tricky margin:
function test() {_x000D_
document.getElementById("box").classList.toggle("hide");_x000D_
}
_x000D_
.right {_x000D_
float:right;_x000D_
}_x000D_
#box {_x000D_
position:absolute; background:#feb;_x000D_
width:20em; margin-left:-20em; padding:1ex;_x000D_
}_x000D_
#box.hide {_x000D_
display:none;_x000D_
}
_x000D_
<div>_x000D_
<div class="right">_x000D_
<button onclick="test()">box</button>_x000D_
<div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</p>_x000D_
</div>
_x000D_
I decided to make this toggleable so you can see how it does not affect the flow of the surrounding text (run it and press the button to show/hide the floated absolute box).
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'>
attribute for the inner html.
For example, for the inner html, use the this
html parameter (yes - this
is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.
With recent matplotlib versions you might want to try Constrained Layout.
Too bad pandas does not handle it well...
For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd
Oh ye of little faith:
SELECT *, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx
I'm simply using this:
On Error Resume Next
Worksheets("Sheet1").ListObjects("Table1").DataBodyRange.Rows.Delete
The first line stays in all cases (it is cleared, of course).
I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.
Here is a good post on permanent generation.
I like the descriptions given for each space in Oracle's guide on JConsole:
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.
- Eden Space (heap): The pool from which memory is initially allocated for most objects.
- Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
- Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
- Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
- Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.
--parents
is copying the directory structure, so you should get rid of that.
The way you've written this, the find
executes, and the output is put onto the command line such that cp
can't distinguish between the spaces separating the filenames, and the spaces within the filename. It's better to do something like
$ find . -name \*.xls -exec cp {} newDir \;
in which cp
is executed for each filename that find
finds, and passed the filename correctly. Here's more info on this technique.
Instead of all the above, you could use zsh and simply type
$ cp **/*.xls target_directory
zsh
can expand wildcards to include subdirectories and makes this sort of thing very easy.
package com.test;
import java.util.Arrays;
public class Person implements Comparable {
private int age;
private Person(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Object o) {
Person other = (Person)o;
if (this == other)
return 0;
if (this.age < other.age) return 1;
else if (this.age == other.age) return 0;
else return -1;
}
public static void main(String[] args) {
Person[] arr = new Person[4];
arr[0] = new Person(50);
arr[1] = new Person(20);
arr[2] = new Person(10);
arr[3] = new Person(90);
Arrays.sort(arr);
for (int i=0; i < arr.length; i++ ) {
System.out.println(arr[i].age);
}
}
}
Here is one way of doing it.
One option is to use an attribute on the image, and modify that using jQuery. Then take that value in CSS:
HTML (note I'm assuming .cloumn
is a div
but it could be anything):
<div class="column" bf-width=100 >
<img src="..." />
</div>
jQuery:
// General use:
$('.column').attr('bf-width', 100);
// With your image, along the lines of:
$('.column').attr('bf-width', $('img').width());
And then in order to use that value in CSS:
.column:before {
content: attr(data-content) 'px';
/* ... */
}
This will grab the attribute value from .column
, and apply it on the before.
Sources: CSS attr (note the examples with before), jQuery attr.
This doesn't have anything to do with app.js
at all. Instead, this warning is logged when you include the Angular JS library more than once.
I've managed to reproduce the error in this JSBin. Note the two script tags (two different versions):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
Relevant Angular code at GitHub.
I think this is the Easiest way to populate a table with ResultSet with a method like
FillTable(MyTable, "select * Customers;");
And a very simple method can be made as
public void FillTable(JTable table, String Query)
{
try
{
CreateConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(Query);
//To remove previously added rows
while(table.getRowCount() > 0)
{
((DefaultTableModel) table.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while(rs.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow()-1,row);
}
rs.close();
stat.close();
conn.close();
}
catch(InstantiationException | IllegalAccessException | SQLException e)
{
}
}
Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:
you can change
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
at the component level in constructor like bellow
constructor(private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
If the datepicker is in a row of a grid, try something like
editoptions : {
dataInit : function (e) {
$(e).datepicker({
onSelect : function (ev) {
// here your code
}
});
}
}
jQuery makes it easy to set any attributes for an element - just use the .attr()
method:
$(document).ready(function() {
$("input").attr({
"max" : 10, // substitute your own
"min" : 2 // values (or variables) here
});
});
The document ready handler is not required if your script block appears after the element(s) you want to manipulate.
Using a selector of "input"
will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:
$("#idHere").attr(...
...or with a class:
$(".classHere").attr(...
I prefer to use a table driven approach for most state machines:
typedef enum { STATE_INITIAL, STATE_FOO, STATE_BAR, NUM_STATES } state_t;
typedef struct instance_data instance_data_t;
typedef state_t state_func_t( instance_data_t *data );
state_t do_state_initial( instance_data_t *data );
state_t do_state_foo( instance_data_t *data );
state_t do_state_bar( instance_data_t *data );
state_func_t* const state_table[ NUM_STATES ] = {
do_state_initial, do_state_foo, do_state_bar
};
state_t run_state( state_t cur_state, instance_data_t *data ) {
return state_table[ cur_state ]( data );
};
int main( void ) {
state_t cur_state = STATE_INITIAL;
instance_data_t data;
while ( 1 ) {
cur_state = run_state( cur_state, &data );
// do other program logic, run other state machines, etc
}
}
This can of course be extended to support multiple state machines, etc. Transition actions can be accommodated as well:
typedef void transition_func_t( instance_data_t *data );
void do_initial_to_foo( instance_data_t *data );
void do_foo_to_bar( instance_data_t *data );
void do_bar_to_initial( instance_data_t *data );
void do_bar_to_foo( instance_data_t *data );
void do_bar_to_bar( instance_data_t *data );
transition_func_t * const transition_table[ NUM_STATES ][ NUM_STATES ] = {
{ NULL, do_initial_to_foo, NULL },
{ NULL, NULL, do_foo_to_bar },
{ do_bar_to_initial, do_bar_to_foo, do_bar_to_bar }
};
state_t run_state( state_t cur_state, instance_data_t *data ) {
state_t new_state = state_table[ cur_state ]( data );
transition_func_t *transition =
transition_table[ cur_state ][ new_state ];
if ( transition ) {
transition( data );
}
return new_state;
};
The table driven approach is easier to maintain and extend and simpler to map to state diagrams.
From the spec, §15.9.1.1:
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.
Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.
The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000)
, which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).
My favorite smtp server is hMailServer.
It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.
It can proxy through your gmail/yahoo/etc account or send email directly.
Once it is installed, email in xampp just works with no config changes.
Please refer to the official Advanced Content Filter guide and plugin integration tutorial.
You'll find much more than this about this powerful feature. Also see config.extraAllowedContent that seems suitable for your needs.
Just try LikeGrep java utility. It may help you in very many cases. As you wish, it can also replace some text, found in files. It garantees its work on large files (up-to 8 Gb tested)
Here is a solution using Microsoft's System.Text.Json library:
static string FormatJsonText(string jsonString)
{
using var doc = JsonDocument.Parse(
jsonString,
new JsonDocumentOptions
{
AllowTrailingCommas = true
}
);
MemoryStream memoryStream = new MemoryStream();
using (
var utf8JsonWriter = new Utf8JsonWriter(
memoryStream,
new JsonWriterOptions
{
Indented = true
}
)
)
{
doc.WriteTo(utf8JsonWriter);
}
return new System.Text.UTF8Encoding()
.GetString(memoryStream.ToArray());
}
Looking under the hood, the two statements will be transformed into different query representations. Depending on the QueryProvider
of Collection
, this might be optimized away or not.
When this is a linq-to-object call, multiple where clauses will lead to a chain of IEnumerables that read from each other. Using the single-clause form will help performance here.
When the underlying provider translates it into a SQL statement, the chances are good that both variants will create the same statement.
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
In the old days, when we could assume that most computers used ASCII, we would just do
int i = c[0] - '0';
But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.
Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.
Asp.net 4.0 has not been registered
Visual Studio 2013 Download Visual Studio 2013 Update 4 For more information on the Visual Studio 2013 Update 4, please refer to: Visual Studio 2013 Update 4 KB Article
Visual Studio 2012 An update to address this issue for Microsoft Visual Studio 2012 has been published: KB3002339 To install this update directly from the Microsoft Download Center, here
Visual Studio 2010 SP1 An update to address this issue for Microsoft Visual Studio 2010 SP1 has been published: KB3002340 This update is available from Windows Update To install this update directly from the Microsoft Download Center, here http://download.microsoft.com/download/6/7/E/67E041A1-00DA-4948-90BE-75A0146C08F5/VS10SP1-KB3002340-x86.exe
Out of the box, the == operator only works for primitives. To get your code to work, you need to overload the == operator for your struct.
I'd just like to point out something in these answers. In a date/time format string, '/' will be replaced with whatever the user's date separator is, and ':' will be replaced with whatever the user's time separator is. That is, if I've defined my date separator to be '.' (in the Regional and Language Options control panel applet, "intl.cpl"), and my time separator to be '?' (just pretend I'm crazy like that), then
DateTime.Now.ToString("MM/dd/yyyy h:mm tt")
would return
01.05.2009 6?01 PM
In most cases, this is what you want, because you want to respect the user's settings. If, however, you require the format be something specific (say, if it's going to parsed back out by somebody else down the wire), then you need to escape these special characters:
DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt")
or
DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt")
which would now return
01/05/2009 6:01 PM
EDIT:
Then again, if you really want to respect the user's settings, you should use one of the standard date/time format strings, so that you respect not only the user's choices of separators, but also the general format of the date and/or time.
DateTime.Now.ToShortDateString()
DateTime.Now.ToString("d")
Both would return "1/5/2009" using standard US options, or "05/01/2009" using standard UK options, for instance.
DateTime.Now.ToLongDateString()
DateTime.Now.ToString("D")
Both would return "Monday, January 05, 2009" in US locale, or "05 January 2009" in UK.
DateTime.Now.ToShortTimeString()
DateTime.Now.ToString("t");
"6:01 PM" in US, "18:01" in UK.
DateTime.Now.ToLongTimeString()
DateTime.Now.ToString("T");
"6:01:04 PM" in US, "18:01:04" in UK.
DateTime.Now.ToString()
DateTime.Now.ToString("G");
"1/5/2009 6:01:04 PM" in US, "05/01/2009 18:01:04" in UK.
Many other options are available. See docs for standard date and time format strings and custom date and time format strings.
Note that you also can use insert in order to put number into the required position within list:
initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]
And also note that in python you can always get a list length using method len()
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Initially, I was running php composer.phar self-update and got the same error message.
As a resolve, you should use composer command directly after install it.From the command prompt, just type composer and press enter.
If composer is installed correctly then you should able to see a lot of suggestion and command list from composer.
If you are up to this point then you should able to run composer self-update directly.
In my case it worked at first and after a while stopped working and IIS Express reported that the port was in use.
netstat -ab
showed that Chrome was using the port. After I quit Chrome, it started working again.
I am not sure however, why Chrome would occupy that port.