Every performance problem with PyCharm is unique, a solution that helps to one person will not work for another. The only proper way to fix your specific performance problem is by capturing the CPU profiler snapshot as described in this document and sending it to PyCharm support team, either by submitting a ticket or directly into the issue tracker.
After the CPU snapshot is analyzed, PyCharm team will work on a fix and release a new version which will (hopefully) not be affected by this specific performance problem. The team may also suggest you some configuration change or workaround to remedy the problem based on the analysis of the provided data.
All the other "solutions" (like enabling Power Save mode and changing the highlighting level) will just hide the real problems that should be fixed.
Functionally, they are identical. So to choose which one to use is totally a personal preference. Semantically in English, they are different. Die sounds negative. When I have a function which returns JSON data to the client and terminate the program, it can be awful if I call this function jsonDie(), and it is more appropriate to call it jsonExit(). For that reason, I always use exit instead of die.
Python 3 has a different and simpler syntax for calling parent method.
If Foo
class inherits from Bar
, then from Bar.__init__
can be invoked from Foo
via super().__init__()
:
class Foo(Bar):
def __init__(self, *args, **kwargs):
# invoke Bar.__init__
super().__init__(*args, **kwargs)
Use COALESCE. Instead of your_column
use COALESCE(your_column, '')
. This will return the empty string instead of NULL.
If you have Cygwin installed in your PC, you can simply use the supplied executable for touch (also via windows command prompt):
C:\cygwin64\bin\touch.exe <file_path>
I was finding same but lastly i found an answer. I hope this answer help you so much.
when your array is empty then you can send empty array just like
if(!empty($result))
{
echo json_encode($result);
}
else
{
echo json_encode(array('data'=>''));
}
Thank you
First go through this tutorial for getting familiar with Android Google Maps and this for API 2.
To retrive the current location of device see this answer or this another answer and for API 2
Then you can get places near by your location using Google Place API and for use of Place Api see this blog.
After getting Placemarks of near by location use this blog with source code to show markers on map with balloon overlay with API 2.
You also have great sample to draw route between two points on map look here in these links Link1 and Link2 and this Great Answer.
After following these steps you will be easily able to do your application. The only condition is, you will have to read it and understand it, because like magic its not going to be complete in a click.
It depends on exactly what the requirements are. In particular, how do you want to handle "\r" on its own? Should that count as a line break or not? As an example, how should "a\n\rb" be treated? Is that one very odd line break, one "\n" break and then a rogue "\r", or two separate linebreaks? If "\r" and "\n" can both be linebreaks on their own, why should "\r\n" not be treated as two linebreaks?
Here's some code which I suspect is reasonably efficient.
using System;
using System.Text;
class LineBreaks
{
static void Main()
{
Test("a\nb");
Test("a\nb\r\nc");
Test("a\r\nb\r\nc");
Test("a\rb\nc");
Test("a\r");
Test("a\n");
Test("a\r\n");
}
static void Test(string input)
{
string normalized = NormalizeLineBreaks(input);
string debug = normalized.Replace("\r", "\\r")
.Replace("\n", "\\n");
Console.WriteLine(debug);
}
static string NormalizeLineBreaks(string input)
{
// Allow 10% as a rough guess of how much the string may grow.
// If we're wrong we'll either waste space or have extra copies -
// it will still work
StringBuilder builder = new StringBuilder((int) (input.Length * 1.1));
bool lastWasCR = false;
foreach (char c in input)
{
if (lastWasCR)
{
lastWasCR = false;
if (c == '\n')
{
continue; // Already written \r\n
}
}
switch (c)
{
case '\r':
builder.Append("\r\n");
lastWasCR = true;
break;
case '\n':
builder.Append("\r\n");
break;
default:
builder.Append(c);
break;
}
}
return builder.ToString();
}
}
You can test whether an array has a certain element at all or not with isset() or sometimes even better array_key_exists() (the documentation explains the differences). If you can't be sure if the array has an element with the index 'say' you should test that first or you might get 'warning: undefined index....' messages.
As for the test whether the element's value is equal to a string you can use == or (again sometimes better) the identity operator === which doesn't allow type juggling.
if( isset($something['say']) && 'bla'===$something['say'] ) {
// ...
}
You can also use super-assignment.
Rather than "<-" type "<<-". The function will recursively and repeatedly search one functional level higher for an object of that name. If it can't find one, it will create one on the global level.
If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.
COPY . destinatio-directory/
I used this:
$('.nav-list li.active').removeClass('active');
$(this).parent().addClass('active');
Since the active class is in the <li>
element and what is clicked is the <a>
element, the first line removes .active
from all <li>
and the second one (again, $(this)
represents <a>
which is the clicked element) adds .active
to the direct parent, which is <li>
.
I understand that the C syntax !=
is in SQL Server due to its Unix heritage (back in the Sybase SQL Server days, pre Microsoft SQL Server 6.5).
You can do this. It looks more wordy than a tuple, but it's a big improvement because you get type checking.
Edit: Replaced snippet with complete working example, following Nick's suggestion. Playground link: http://play.golang.org/p/RNx_otTFpk
package main
import "fmt"
func main() {
queue := make(chan struct {string; int})
go sendPair(queue)
pair := <-queue
fmt.Println(pair.string, pair.int)
}
func sendPair(queue chan struct {string; int}) {
queue <- struct {string; int}{"http:...", 3}
}
Anonymous structs and fields are fine for quick and dirty solutions like this. For all but the simplest cases though, you'd do better to define a named struct just like you did.
One (quick & dirty) way to resize images it to use HTML & specify the new size in the image element. This even works for animated images with transparency.
Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.
private enum Fruit {
apple, carrot, mango, orange;
}
String value; // assume input
Fruit fruit = Fruit.valueOf(value); // surround with try/catch
switch(fruit) {
case apple:
method1;
break;
case carrot:
method2;
break;
// etc...
}
I use the dialog as an dialog file browser and uploader then I rewrite the code like this
var dialog1 = $("#dialog").dialog({
autoOpen: false,
height: 480,
width: 640
});
$('#tikla').click(function() {
dialog1.load('./browser.php').dialog('open');
});
everything seems to work great.
Put style="float:left"
on each of your divs:
<div style="float:left;">...........
Example:
<div style="float:left;">
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>
<div style="float:left;">
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
To put an element on new line, put this div below it:
<div style="clear:both;"> </div>
Of course, you can also create classes in the CSS file:
.left{
float:left;
}
.clear{
clear:both;
}
And then your html should look like this:
<div class="left">
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>
<div class="left">
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
To put an element on new line, put this div below it:
<div class="clear"> </div>
More Info:
Use the new CSS viewport units vw
and vh
(viewport width / viewport height)
Resize vertically and horizontally and you'll see that the element will always fill the maximum viewport size without breaking the ratio and without scrollbars!
div
{
width: 100vw;
height: 56.25vw; /* height:width ratio = 9/16 = .5625 */
background: pink;
max-height: 100vh;
max-width: 177.78vh; /* 16/9 = 1.778 */
margin: auto;
position: absolute;
top:0;bottom:0; /* vertical center */
left:0;right:0; /* horizontal center */
}
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
div {_x000D_
width: 100vw;_x000D_
height: 56.25vw;_x000D_
/* 100/56.25 = 1.778 */_x000D_
background: pink;_x000D_
max-height: 100vh;_x000D_
max-width: 177.78vh;_x000D_
/* 16/9 = 1.778 */_x000D_
margin: auto;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
/* vertical center */_x000D_
left: 0;_x000D_
right: 0;_x000D_
/* horizontal center */_x000D_
}
_x000D_
<div></div>
_x000D_
If you want to use a maximum of say 90% width and height of the viewport: FIDDLE
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
div {_x000D_
width: 90vw;_x000D_
/* 90% of viewport vidth */_x000D_
height: 50.625vw;_x000D_
/* ratio = 9/16 * 90 = 50.625 */_x000D_
background: pink;_x000D_
max-height: 90vh;_x000D_
max-width: 160vh;_x000D_
/* 16/9 * 90 = 160 */_x000D_
margin: auto;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
}
_x000D_
<div></div>
_x000D_
Also, browser support is pretty good too: IE9+, FF, Chrome, Safari- caniuse
I had some struggle to access the previous url inside a guard.
Without implementing a custom solution, this one is working for me.
public constructor(private readonly router: Router) {
};
public ngOnInit() {
this.router.getCurrentNavigation().previousNavigation.initialUrl.toString();
}
The initial url will be the previous url page.
This is incredibly ugly, but it also fixed the problem quickly for me. Your table needs a unique key which you will use to fix the tainted columns. In this example, the primary key is called 'id' and the broken timestamp column is called 'BadColumn'.
Select the IDs of the tainted columns.
select id from table where BadColumn='0000-00-00 00:00:00'
Collect the IDs into a comma-delimited string. Example: 1, 22, 33
. I used an external wrapper for this (a Perl script) to quickly spit them all out.
Use your list of IDs to update the old columns with a valid date (1971 through 2038).
update table set BadColumn='2000-01-01 00:00:00' where id in (1, 22, 33)
Initialize the SQL Server Browser Service.
I believe what you're trying to do is impossible.
The junk that BinaryFormatter
creates is necessary to recover the object from the file after your program stopped.
However it is possible to get the object data, you just need to know the exact size of it (more difficult than it sounds) :
public static unsafe byte[] Binarize(object obj, int size)
{
var r = new byte[size];
var rf = __makeref(obj);
var a = **(IntPtr**)(&rf);
Marshal.Copy(a, r, 0, size);
return res;
}
this can be recovered via:
public unsafe static dynamic ToObject(byte[] bytes)
{
var rf = __makeref(bytes);
**(int**)(&rf) += 8;
return GCHandle.Alloc(bytes).Target;
}
The reason why the above methods don't work for serialization is that the first four bytes in the returned data correspond to a RuntimeTypeHandle
. The RuntimeTypeHandle
describes the layout/type of the object but the value of it changes every time the program is ran.
EDIT: that is stupid don't do that -->
If you already know the type of the object to be deserialized for certain you can switch those bytes for BitConvertes.GetBytes((int)typeof(yourtype).TypeHandle.Value)
at the time of deserialization.
First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”
In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.
The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.
You can handle this error by putting :
is_private = request.POST.get('is_private', False);
<span style='color:blue '> your message/text </span>
So here it is a perfect html css style entry inside a notebook ipynb file.
Of course you can choose your favourite color here and then your text.
Because someone asked for the Data.Table version of this, and because the given data.frame solution does not work with data.table, I am providing the solution below.
Basically, use the :=
operator --> DT[x == 0, x := NA]
library("data.table")
status = as.data.table(occupationalStatus)
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 0
8: 8 1 0
9: 1 2 19
10: 2 2 40
status[N == 0, N := NA]
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 NA
8: 8 1 NA
9: 1 2 19
10: 2 2 40
Have you heard of "SQuirreL SQL Client"?
if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
//do stuff if yess
}
else
{
//do stuff if No
}
Aspx
<ajax:ModalPopupExtender runat="server" ID="modalPop"
PopupControlID="pnlpopup"
TargetControlID="btnGo"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="btnCancel" X="470" Y="300" />
//Codebehind
protected void OkButton_Clicked(object sender, EventArgs e)
{
modalPop.Hide();
//Do something in codebehind
}
And don't set the OK button as OkControlID.
Since pip v1.5
, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:
pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory
Note: As a pip module author, ideally you'd probably want to publish your module in it's own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.
If preg_match
did not find a match, $matches
is an empty array. So you should check if preg_match
found an match before accessing $matches[0]
, for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
You can flip both vertical and horizontal at the same time
-moz-transform: scaleX(-1) scaleY(-1);
-o-transform: scaleX(-1) scaleY(-1);
-webkit-transform: scaleX(-1) scaleY(-1);
transform: scaleX(-1) scaleY(-1);
And with the transition property you can get a cool flip
-webkit-transition: transform .4s ease-out 0ms;
-moz-transition: transform .4s ease-out 0ms;
-o-transition: transform .4s ease-out 0ms;
transition: transform .4s ease-out 0ms;
transition-property: transform;
transition-duration: .4s;
transition-timing-function: ease-out;
transition-delay: 0ms;
Actually it flips the whole element, not just the background-image
SNIPPET
function flip(){_x000D_
var myDiv = document.getElementById('myDiv');_x000D_
if (myDiv.className == 'myFlipedDiv'){_x000D_
myDiv.className = '';_x000D_
}else{_x000D_
myDiv.className = 'myFlipedDiv';_x000D_
}_x000D_
}
_x000D_
#myDiv{_x000D_
display:inline-block;_x000D_
width:200px;_x000D_
height:20px;_x000D_
padding:90px;_x000D_
background-color:red;_x000D_
text-align:center;_x000D_
-webkit-transition:transform .4s ease-out 0ms;_x000D_
-moz-transition:transform .4s ease-out 0ms;_x000D_
-o-transition:transform .4s ease-out 0ms;_x000D_
transition:transform .4s ease-out 0ms;_x000D_
transition-property:transform;_x000D_
transition-duration:.4s;_x000D_
transition-timing-function:ease-out;_x000D_
transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
-moz-transform:scaleX(-1) scaleY(-1);_x000D_
-o-transform:scaleX(-1) scaleY(-1);_x000D_
-webkit-transform:scaleX(-1) scaleY(-1);_x000D_
transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
Static linking includes the files that the program needs in a single executable file.
Dynamic linking is what you would consider the usual, it makes an executable that still requires DLLs and such to be in the same directory (or the DLLs could be in the system folder).
(DLL = dynamic link library)
Dynamically linked executables are compiled faster and aren't as resource-heavy.
So I figured out what is wrong with this statement:
Import-Csv H:\Programs\scripts\SomeText.csv |`
(Original)
Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"
(Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)
It requires the -Delimiter "|"
, in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.
I cannot say that I would recommend the |
operator, since it is used to pipe cmdlets into one another.
I still cannot get the if statement to return true and output the values entered via the prompt.
If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!
For a local copy, the only advantage of rsync is that it will avoid copying if the file already exists in the destination directory. The definition of "already exists" is (a) same file name (b) same size (c) same timestamp. (Maybe same owner/group; I am not sure...)
The "rsync algorithm" is great for incremental updates of a file over a slow network link, but it will not buy you much for a local copy, as it needs to read the existing (partial) file to run it's "diff" computation.
So if you are running this sort of command frequently, and the set of changed files is small relative to the total number of files, you should find that rsync is faster than cp. (Also rsync has a --delete
option that you might find useful.)
Late answer, but I think it is simple and worthy:
public boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
Test Cases:
For production purpose, Domain Name validations should be performed network-wise.
Use jquery animate and give it a long duration say 2000
$("#Friends").animate({
top: "-=30px",
}, duration );
The -= means that the animation will be relative to the current top position.
Note that the Friends
element must have position set to relative in the css:
#Friends{position:relative;}
In case you have to deal with the arguably unfriendly logs
client (CloudWatch Logs put-log-events
), this is what I had to do to properly catch Boto3 client exceptions:
try:
### Boto3 client code here...
except boto_exceptions.ClientError as error:
Log.warning("Catched client error code %s",
error.response['Error']['Code'])
if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
"InvalidSequenceTokenException"]:
Log.debug(
"Fetching sequence_token from boto error response['Error']['Message'] %s",
error.response["Error"]["Message"])
# NOTE: apparently there's no sequenceToken attribute in the response so we have
# to parse response["Error"]["Message"] string
sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
Log.debug("Setting sequence_token to %s", sequence_token)
This works both at first attempt (with empty LogStream) and subsequent ones.
Mozilla provides a simple framework for reading and writing cookies with full unicode support along with examples of how to use it.
Once included on the page, you can set a cookie:
docCookies.setItem(name, value);
read a cookie:
docCookies.getItem(name);
or delete a cookie:
docCookies.removeItem(name);
For example:
// sets a cookie called 'myCookie' with value 'Chocolate Chip'
docCookies.setItem('myCookie', 'Chocolate Chip');
// reads the value of a cookie called 'myCookie' and assigns to variable
var myCookie = docCookies.getItem('myCookie');
// removes the cookie called 'myCookie'
docCookies.removeItem('myCookie');
See more examples and details on Mozilla's document.cookie page.
A version of this simple js file is on github.
When a URL is like domain/search/?q=haha
, you would use request.GET.get('q', '')
.
q
is the parameter you want, and ''
is the default value if q
isn't found.
However, if you are instead just configuring your URLconf
**, then your captures from the regex
are passed to the function as arguments (or named arguments).
Such as:
(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
Then in your views.py
you would have
def profile_page(request, username):
# Rest of the method
If you are willing to give up a tiny amount of speed for a cleaner look, then you could use numpy.concatenate().tolist()
or numpy.concatenate().ravel().tolist()
:
import numpy
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] * 99
%timeit numpy.concatenate(l).ravel().tolist()
1000 loops, best of 3: 313 µs per loop
%timeit numpy.concatenate(l).tolist()
1000 loops, best of 3: 312 µs per loop
%timeit [item for sublist in l for item in sublist]
1000 loops, best of 3: 31.5 µs per loop
You can find out more here in the docs numpy.concatenate and numpy.ravel
apt-get install python3-pip
pip3 install pyftpdlib
python3 -m pyftpdlib -p 21 -w --user=username --password=password
-w = write permission
-p = desired port
--user = give your username
--password = give your password
Another nice and reusable solution is to create a directive like this:
app.directive( 'backButton', function() {
return {
restrict: 'A',
link: function( scope, element, attrs ) {
element.on( 'click', function () {
history.back();
scope.$apply();
} );
}
};
} );
then just use it like this:
<a href back-button>back</a>
In python 3.4, while in a virtual environment, make sure you have the build dependencies first:
sudo apt-get build-dep python3-psycopg2
Then install it:
pip install psycopg2
The question is a bit old but I just solved a very similar problem. We have several intranet sites here including the one I'm responsible for, and the others require compatibility mode or they break. For that reason, site rules default IE to compatibility mode on intranet sites. I am upgrading my own stuff and no longer need it; in fact, some of the features I'm trying to use don't look right in compat mode. I'm using the meta IE-Edge tag like you are.
IE assumes websites without the fully-qualified address are intranet, and acts accordingly. With that in mind I just altered the bindings in IIS to only listen to the fully-qualified address, then set up a dummy website that listened for the unqualified address. The second one redirects all traffic to the fully-qualified address, making IE believe it's an external site. The site renders correctly with or without the Compatibility Mode on Intranet Sites box checked.
If you don't need the seeding capability just use Math.random()
and build helper functions around it (eg. randRange(start, end)
).
I'm not sure what RNG you're using, but it's best to know and document it so you're aware of its characteristics and limitations.
Like Starkii said, Mersenne Twister is a good PRNG, but it isn't easy to implement. If you want to do it yourself try implementing a LCG - it's very easy, has decent randomness qualities (not as good as Mersenne Twister), and you can use some of the popular constants.
EDIT: consider the great options at this answer for short seedable RNG implementations, including an LCG option.
function RNG(seed) {_x000D_
// LCG using GCC's constants_x000D_
this.m = 0x80000000; // 2**31;_x000D_
this.a = 1103515245;_x000D_
this.c = 12345;_x000D_
_x000D_
this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));_x000D_
}_x000D_
RNG.prototype.nextInt = function() {_x000D_
this.state = (this.a * this.state + this.c) % this.m;_x000D_
return this.state;_x000D_
}_x000D_
RNG.prototype.nextFloat = function() {_x000D_
// returns in range [0,1]_x000D_
return this.nextInt() / (this.m - 1);_x000D_
}_x000D_
RNG.prototype.nextRange = function(start, end) {_x000D_
// returns in range [start, end): including start, excluding end_x000D_
// can't modulu nextInt because of weak randomness in lower bits_x000D_
var rangeSize = end - start;_x000D_
var randomUnder1 = this.nextInt() / this.m;_x000D_
return start + Math.floor(randomUnder1 * rangeSize);_x000D_
}_x000D_
RNG.prototype.choice = function(array) {_x000D_
return array[this.nextRange(0, array.length)];_x000D_
}_x000D_
_x000D_
var rng = new RNG(20);_x000D_
for (var i = 0; i < 10; i++)_x000D_
console.log(rng.nextRange(10, 50));_x000D_
_x000D_
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];_x000D_
for (var i = 0; i < 10; i++)_x000D_
console.log(rng.choice(digits));
_x000D_
All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray
, and you need to retain the shape of array.
I have compare just two, but it will retain the shape of ndarray
. I have used the array with 1 million entries for comparison. Here I use square function, which is also inbuilt in numpy and has great performance boost, since there as was need of something, you can use function of your choice.
import numpy, time
def timeit():
y = numpy.arange(1000000)
now = time.time()
numpy.array([x * x for x in y.reshape(-1)]).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.fromiter((x * x for x in y.reshape(-1)), y.dtype).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.square(y)
print(time.time() - now)
Output
>>> timeit()
1.162431240081787 # list comprehension and then building numpy array
1.0775556564331055 # from numpy.fromiter
0.002948284149169922 # using inbuilt function
here you can clearly see numpy.fromiter
works great considering to simple approach, and if inbuilt function is available please use that.
You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)
So to insert Employee / Department pairs that do not currently exist you might try something like the following.
CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e
on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
You have to make sure that the proxy is enabled on the server. You can do so by using the following commands:
a2enmod proxy
a2enmod proxy_http
service apache2 restart
.click()
does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:
function fireClick(node){
if (document.createEvent) {
var evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, false);
node.dispatchEvent(evt);
} else if (document.createEventObject) {
node.fireEvent('onclick') ;
} else if (typeof node.onclick == 'function') {
node.onclick();
}
}
From this post
You must specify the type of the column before the auto_increment
directive, i.e. ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT
.
I use SyntaxHighlighter with my Blogger powered blog. The actual site is hosted on my own server rather than Blogger's though (Blogger has an option of ftping posts to your own site), but having your own domain and web hosting only costs a couple of dollars a month.
I had a similar problem last week. I received a number of CSV files with varying encodings. Before importing into the database I then used the chardet libary to automatically sniff out the correct encoding.
Chardet is a port from Mozillas character detection engine and if the sample size is large enough (one accentuated character will not do) works really well.
i entered in Mysql Workbench and i changed the password. It seem the password was expired. it works!
I know this question is old, however I ran into this problem on Windows 8.1 while trying to use .htaccess files for rewriting. My solution was simple, I forgot to modify the following line in httpd.conf
#LoadModule rewrite_module modules/mod_rewrite.so
to
LoadModule rewrite_module modules/mod_rewrite.so
Restarted the apache monitor, now all works well. Just posting this as an answer because someone in the future may run across the same issue with a simple fix.
Good luck!
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="@+id/myScreen"
</LinearLayout>
In other words, "android:background" is the tag in the XML you want to change.
If you need to dynamically update the background value, see the following:
The time_t
value for midnight GMT is always divisible by 86400
(24 * 3600
). The value for seconds-since-midnight GMT is thus time %% 86400
.
The hour in GMT is (time %% 86400) / 3600
and this can be used as the x-axis of the plot:
plot((as.numeric(times) %% 86400)/3600, val)
To adjust for a time zone, adjust the time before taking the modulus, by adding the number of seconds that your time zone is ahead of GMT. For example, US central daylight saving time (CDT) is 5 hours behind GMT. To plot against the time in CDT, the following expression is used:
plot(((as.numeric(times) - 5*3600) %% 86400)/3600, val)
You should install these as devDependencies:
- gulp-util
- gulp-load-plugins
Then, you can use them either this way:
var plugins = require('gulp-load-plugins')();
Use gulp-util as : plugins.util()
or this:
var util = require('gulp-util')
Try to use (focus)
and (focusout)
instead of onfocus
and onfocusout
like this : -
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
also you can use like this :-
some people prefer the on- prefix alternative, known as the canonical form:
<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">
Know more about event binding see here.
you have to use HostListner for your use case
Angular will invoke the decorated method when the host element emits the specified event.
@HostListener
is a decorator for the callback/event handler method
See my Update working Plunker.
Working Example Working Stackblitz
Some other events can be used in angular -
(focus)="myMethod()"
(blur)="myMethod()"
(submit)="myMethod()"
(scroll)="myMethod()"
Ctrl+Shift+F to invoke the Auto Formatter
Ctrl+I to indent the selected part (or all) of you code.
With styled components this can be easily achieved
First Design a styled button
import styled from "styled-components";
import {Link} from "react-router-dom";
const Button = styled.button`
background: white;
color:red;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid red;
border-radius: 3px;
`
render(
<Button as={Link} to="/home"> Text Goes Here </Button>
);
check styled component's home for more
For what it's worth, with iOS7 dropping support for datetime
you need to use datetime-local
which doesn't accept timezone portion (which makes sense).
Doesn't work (iOS anyway):
<input type="datetime-local" value="2000-01-01T00:00:00+05:00" />
Works:
<input type="datetime-local" value="2000-01-01T00:00:00" />
PHP for value (windows safe):
strftime('%Y-%m-%dT%H:%M:%S', strtotime($my_datetime_input))
In addition to the "raw" tools provided by MutationObserver
API, there exist "convenience" libraries to work with DOM mutations.
Consider: MutationObserver represents each DOM change in terms of subtrees. So if you're, for instance, waiting for a certain element to be inserted, it may be deep inside the children of mutations.mutation[i].addedNodes[j]
.
Another problem is when your own code, in reaction to mutations, changes DOM - you often want to filter it out.
A good convenience library that solves such problems is mutation-summary
(disclaimer: I'm not the author, just a satisfied user), which enables you to specify queries of what you're interested in, and get exactly that.
Basic usage example from the docs:
var observer = new MutationSummary({
callback: updateWidgets,
queries: [{
element: '[data-widget]'
}]
});
function updateWidgets(summaries) {
var widgetSummary = summaries[0];
widgetSummary.added.forEach(buildNewWidget);
widgetSummary.removed.forEach(cleanupExistingWidget);
}
Well, does sleep
even exist on your Windows XP box? According to this post: http://malektips.com/xp_dos_0002.html sleep
isn't available on Windows XP, and you have to download the Windows 2003 Resource Kit in order to get it.
Chakrit's answer gives you another way to pause, too.
Try running sleep 10
from a command prompt.
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
Bart Kiers, your regex has a couple issues. The best way to do that is this:
(.*[a-z].*) // For lower cases
(.*[A-Z].*) // For upper cases
(.*\d.*) // For digits
In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.
You can run your program by: Debug -> Start Without Debugging
. It will keep a console opened after the program will be finished.
I don't have much time and your jsfidle did not work right now.
But maybe this will help you getting started.
First of all you should avoid to put css in your html tags. Like align="center"
.
Put stuff like that in your css since it is much clearer and won't deprecate that fast.
If you want to design responsive layouts you should use media queries wich were introduced in css3 and are supported very well by now.
Example css:
@media screen and (min-width: 100px) and (max-width: 199px)
{
.button
{
width: 25px;
}
}
@media screen and (min-width: 200px) and (max-width: 299px)
{
.button
{
width: 50px;
}
}
You can use any css you want inside a media query.
http://www.w3.org/TR/css3-mediaqueries/
Apparently you want:
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
Have a further read in Jeez People, Stop Fretting Over Installing RMagic.
Maybe you are using:
$(document).ready(function(){
// Your code here
});
Try this instead:
window.onload = function(){ }
We can simply have if & else .if suppose your input is empty we can have
if($(#name).val() != '') {
$('input[type="submit"]').attr('disabled' , false);
}
else we can change false into true
Consider the following case:
First, o1.compareTo(o2)
is called. card1.getSet() == card2.getSet()
happens to be true and so is card1.getRarity() < card2.getRarity()
, so you return 1.
Then, o2.compareTo(o1)
is called. Again, card1.getSet() == card2.getSet()
is true. Then, you skip to the following else
, then card1.getId() == card2.getId()
happens to be true, and so is cardType > item.getCardType()
. You return 1 again.
From that, o1 > o2
, and o2 > o1
. You broke the contract.
Here is code based on bestsss' answer:
Enumeration<URL> en = getClass().getClassLoader().getResources(
"META-INF");
List<String> profiles = new ArrayList<>();
while (en.hasMoreElements()) {
URL url = en.nextElement();
JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
try (JarFile jar = urlcon.getJarFile();) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String entry = entries.nextElement().getName();
System.out.println(entry);
}
}
}
Those are Java varargs. They let you pass any number of objects of a specific type (in this case they are of type JID).
In your example, the following function calls would be valid:
MessageBuilder msgBuilder; //There should probably be a call to a constructor here ;)
MessageBuilder msgBuilder2;
msgBuilder.withRecipientJids(jid1, jid2);
msgBuilder2.withRecipientJids(jid1, jid2, jid78_a, someOtherJid);
See more here: http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html
In your example you will also need to strip slash from right the right side to return c
:
>>> import os
>>> path = 'a/b/c/'
>>> path = path.rstrip(os.sep) # strip the slash from the right side
>>> os.path.basename(path)
'c'
Second level:
>>> os.path.filename(os.path.dirname(path))
'b'
update: I think lazyr
has provided the right answer. My code will not work with windows-like paths on unix systems and vice versus with unix-like paths on windows system.
Check out the WatiN project:
Inspired by Watir development of WatiN started in December 2005 to make a similar kind of Web Application Testing possible for the .Net languages. Since then WatiN has grown into an easy to use, feature rich and stable framework. WatiN is developed in C# and aims to bring you an easy way to automate your tests with Internet Explorer and FireFox using .Net...
TLDR: use theString = theString.replace("\\", "\\\\");
instead.
replaceAll(target, replacement)
uses regular expression (regex) syntax for target
and partially for replacement
.
Problem is that \
is special character in regex (it can be used like \d
to represents digit) and in String literal (it can be used like "\n"
to represent line separator or \"
to escape double quote symbol which normally would represent end of string literal).
In both these cases to create \
symbol we can escape it (make it literal instead of special character) by placing additional \
before it (like we escape "
in string literals via \"
).
So to target
regex representing \
symbol will need to hold \\
, and string literal representing such text will need to look like "\\\\"
.
So we escaped \
twice:
\\
"\\\\"
(each \
is represented as "\\"
). In case of replacement
\
is also special there. It allows us to escape other special character $
which via $x
notation, allows us to use portion of data matched by regex and held by capturing group indexed as x
, like "012".replaceAll("(\\d)", "$1$1")
will match each digit, place it in capturing group 1 and $1$1
will replace it with its two copies (it will duplicate it) resulting in "001122"
.
So again, to let replacement
represent \
literal we need to escape it with additional \
which means that:
\\
\\
looks like "\\\\"
BUT since we want replacement
to hold two backslashes we will need "\\\\\\\\"
(each \
represented by one "\\\\"
).
So version with replaceAll
can look like
replaceAll("\\\\", "\\\\\\\\");
To make out life easier Java provides tools to automatically escape text into target
and replacement
parts. So now we can focus only on strings, and forget about regex syntax:
replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement))
which in our case can look like
replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))
If we don't really need regex syntax support lets not involve replaceAll
at all. Instead lets use replace
. Both methods will replace all target
s, but replace
doesn't involve regex syntax. So you could simply write
theString = theString.replace("\\", "\\\\");
The pythonic way to read a file and put every lines in a list:
from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
lines = f.readlines()
Then, assuming that each lines contains a number,
numbers =[int(e.strip()) for e in lines]
I was having a lot of problems to get this working, every single solution I found didn't seem to work.
I realized that I had to set the div display to flex, so basically this is my CSS:
div{
display: flex;
}
div img{
max-height: 100%;
max-width: 100%;
}
Here is a forum thread that provides a C# image resizing code sample. You could use one of the GD library binders to do resampling in C#.
Basically we use cd..
to come back from every directory. I thought to make it more easy by giving the number of directories with which you need to come back at a time. You can implement this using a separate script file using the alias command . For example:
code.sh
#!/bin/sh
_backfunc(){
if [ "$1" -eq 1 ]; then
cd ..
elif [ "$1" -eq 2 ]; then
cd ../..
elif [ "$1" -eq 3 ]; then
cd ../../..
elif [ "$1" -eq 4 ]; then
cd ../../../..
elif ["$1" -eq 10]; then
cd /home/arun/Documents/work
fi
}
alias back='_backfunc'
After using source code.sh
in the current shell you can use :
$back 2
to come two steps back from the current directory. Explained in detail over here. It is also explained over there how to put the code in ~/.bashrc so that every new shell opened will automatically have this new alias command. You can add new command to go to specific directories by modifying the code by adding more if conditions
and different arguments. You can also pull the code from git over here.
The jQuery you're using is manipulates the DOM, not the CSS itself. Try changing the word span
in your CSS to .mySpan
, then apply that class to one or more DOM elements in your HTML like so:
...
<span class="mySpan">...</span>
...
Then, change your jQuery as follows:
$(".mySpan").css({ display : inline });
This should work much better.
Good luck!
Autoplay only works the second time through. on android 4.1+ you have to have some kind of user event to get the first play() to work. Once that has happened then autostart works.
This is so that the user is acknowledging that they are using bandwidth.
There is another question that answers this . Autostart html5 video using android 4 browser
Here is my jquery print plugin
(function ($) {
$.fn.printme = function () {
return this.each(function () {
var container = $(this);
var hidden_IFrame = $('<iframe></iframe>').attr({
width: '1px',
height: '1px',
display: 'none'
}).appendTo(container);
var myIframe = hidden_IFrame.get(0);
var script_tag = myIframe.contentWindow.document.createElement("script");
script_tag.type = "text/javascript";
script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
script_tag.appendChild(script);
myIframe.contentWindow.document.body.innerHTML = container.html();
myIframe.contentWindow.document.body.appendChild(script_tag);
myIframe.contentWindow.Print();
hidden_IFrame.remove();
});
};
})(jQuery);
You can set your tint color and font as setTitleTextattribute:
UIFont *font= (kUIScreenHeight>KipadHeight)?[UIFont boldSystemFontOfSize:32.0f]:[UIFont boldSystemFontOfSize:16.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,
tintColorLight, NSForegroundColorAttributeName, nil];
[[UINavigationBar appearance] setTitleTextAttributes:attributes];
$(function(){
$(window).resize(function(){
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
});
});
Scrollbars etc have an effect on the window size so you may want to tweak to desired size.
I faced the same problem, it turned out to be VPN related. If you are testing on a device against a corporate network, chances are your Mac has proper VPN set up, but your phone does not. Connect phone to the corporate VPN for your apps deployed to device to see corporate servers.
I know this is a little late, but I just figured out how to do this by modifying (read, "hacking") the manifest of the devenv.exe file. I should have come here first because the stated solutions seem a little easier, and probably more supported by Microsoft. :)
Here's how I did it:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"></requestedExecutionLevel>
You've just saved the copy of the executable that was added to your project. Now you need to back up the original and copy your modified exe to your installation directory.
As I said, this is probably not the right way to do it, but it seems to work. If anyone knows of any negative fallout or requisite wrist-slapping that needs to happen, please chime in!
This is the way that I did it for a uni project, works fine, prob not safe tho
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$pass = $_POST['password'];
$cpass = $_POST['cpassword'];
$check = 1;
if (){
}
else{
$check = 1;
}
if ($check == 1){
require_once('website_data_collecting/db.php');
$sel_user = "SELECT * FROM users WHERE user_email='$email'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if ($check_user > 0){
echo '<div style="margin: 0 0 10px 20px;">Email already exists!</br>
<a href="recover.php">Recover Password</a></div>';
}
else{
$users_tb = "INSERT INTO users ".
"(user_name, user_email, user_password) ".
"VALUES('$name','$email','$pass')";
$users_info_tb = "INSERT INTO users_info".
"(user_title, user_surname)".
"VALUES('$title', '$surname')";
mysql_select_db('dropbox');
$run_users_tb = mysql_query( $users_tb, $conn );
$run_users_info_tb = mysql_query( $users_info_tb, $conn );
if(!$run_users_tb || !$run_users_info_tb){
die('Could not enter data: ' . mysql_error());
}
else{
echo "Entered data successfully\n";
}
mysql_close($conn);
}
}
Save all Control + S Command + S
Synchronize Control + Alt + Y Command + Option + Y
Maximize/minimize editor Control + Shift + F12 Control + Command + F12
Add to favorites Alt + Shift + F Option + Shift + F
Inspect current file with current profile Alt + Shift + I Option + Shift + I
Quick switch scheme Control + (backquote) Control +
(backquote)
Open settings dialogue Control + Alt + S Command + , (comma)
Open project structure dialog Control + Alt + Shift + S Command + ; (semicolon)
Switch between tabs and tool window Control + Tab Control + Tab
Navigating and searching within Studio
Search everything (including code and menus) Press Shift twice Press Shift twice
Find Control + F Command + F
Find next F3 Command + G
Find previous Shift + F3 Command + Shift + G
Replace Control + R Command + R
Find action Control + Shift + A Command + Shift + A
Search by symbol name Control + Alt + Shift + N Command + Option + O
Find class Control + N Command + O
Find file (instead of class) Control + Shift + N Command + Shift + O
Find in path Control + Shift + F Command + Shift + F
Open file structure pop-up Control + F12 Command + F12
Navigate between open editor tabs Alt + Right/Left Arrow Control + Right/Left Arrow
Jump to source F4 / Control + Enter F4 / Command + Down Arrow
Open current editor tab in new window Shift + F4 Shift + F4
Recently opened files pop-up Control + E Command + E
Recently edited files pop-up Control + Shift + E Command + Shift + E
Go to last edit location Control + Shift + Backspace Command + Shift + Backspace
Close active editor tab Control + F4 Command + W
Return to editor window from a tool window Esc Esc
Hide active or last active tool window Shift + Esc Shift + Esc
Go to line Control + G Command + L
Open type hierarchy Control + H Control + H
Open method hierarchy Control + Shift + H Command + Shift + H
Open call hierarchy Control + Alt + H Control + Option + H
Writing code
Generate code (getters, setters, constructors, hashCode/equals, toString, new file, new class) Alt + Insert Command + N
Override methods Control + O Control + O
Implement methods Control + I Control + I
Surround with (if...else / try...catch / etc.) Control + Alt + T Command + Option + T
Delete line at caret Control + Y Command + Backspace
Collapse/expand current code block Control + minus/plus Command + minus/plus Collapse/expand all code blocks Control + Shift + minus/plus Command + Shift +
minus/plus
Duplicate current line or selection Control + D Command + D
Basic code completion Control + Space Control + Space
Smart code completion (filters the list of methods and variables by expected type)
Control + Shift + Space Control + Shift + Space
Complete statement Control + Shift + Enter Command + Shift + Enter
Quick documentation lookup Control + Q Control + J
Show parameters for selected method Control + P Command + P
Go to declaration (directly) Control + B or Control + Click Command + B or Command + Click
Go to implementations Control + Alt + B Command + Alt + B
Go to super-method/super-class Control + U Command + U
Open quick definition lookup Control + Shift + I Command + Y
Toggle project tool window visibility Alt + 1 Command + 1
Toggle bookmark F11 F3
Toggle bookmark with mnemonic Control + F11 Option + F3
Comment/uncomment with line comment Control + / Command + /
Comment/uncomment with block comment Control + Shift + / Command + Shift + /
Select successively increasing code blocks Control + W Option + Up
Decrease current selection to previous state Control + Shift + W Option + Down
Move to code block start Control + [ Option + Command + [
Move to code block end Control + ] Option + Command + ]
Select to the code block start Control + Shift + [ Option + Command + Shift + [
Select to the code block end Control + Shift + ] Option + Command + Shift + ]
Delete to end of word Control + Delete Option + Delete
Delete to start of word Control + Backspace Option + Backspace
Optimize imports Control + Alt + O Control + Option + O
Project quick fix (show intention actions and quick fixes) Alt + Enter Option + Enter
Reformat code Control + Alt + L Command + Option + L
Auto-indent lines Control + Alt + I Control + Option + I
Indent/unindent lines Tab/Shift + Tab Tab/Shift + Tab
Smart line join Control + Shift + J Control + Shift + J
Smart line split Control + Enter Command + Enter
Start new line Shift + Enter Shift + Enter
Next/previous highlighted error F2 / Shift + F2 F2 / Shift + F2
Build and run
Build Control + F9 Command + F9
Build and run Shift + F10 Control + R
Apply changes (with Instant Run) Control + F10 Control + Command + R
Debugging
Debug Shift + F9 Control + D
Step over F8 F8
Step into F7 F7
Smart step into Shift + F7 Shift + F7
Step out Shift + F8 Shift + F8
Run to cursor Alt + F9 Option + F9
Evaluate expression Alt + F8 Option + F8
Resume program F9 Command + Option + R
Toggle breakpoint Control + F8 Command + F8
View breakpoints Control + Shift + F8 Command + Shift + F8
Refactoring
Copy F5 F5
Move F6 F6
Safe delete Alt + Delete Command + Delete
Rename Shift + F6 Shift + F6
Change signature Control + F6 Command + F6
Inline Control + Alt + N Command + Option + N
Extract method Control + Alt + M Command + Option + M
Extract variable Control + Alt + V Command + Option + V
Extract field Control + Alt + F Command + Option + F
Extract constant Control + Alt + C Command + Option + C
Extract parameter Control + Alt + P Command + Option + P
Version control / local history
Commit project to VCS Control + K Command + K
Update project from VCS Control + T Command + T
View recent changes Alt + Shift + C Option + Shift + C
Open VCS popup Alt + ` (backquote) Control + V
iText is really easy to use.
If you requiere doc files you can call abiword (free lightweigh multi-os text procesor) from the command line, it has several conversion format convert options.
If you encode the & in your URL to %26 it works correctly. Just tested and verified.
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
The above error can occur for multiple cases during servlet startup / request. Hope you check the full stack trace of the server log, If you have tomcat, you can also see the exact causes in html preview of the 500 Internal Server Error page.
Weird thing is, if you try to hit the request url a second time, you would get 404 Not Found page.
You can also debug this issue, by placing breakpoints on all the classes constructor initialization block, whose objects are created during servlet startup/request.
In my case, I didn't had javaassist jar loaded for the Weld CDI injection to work. And it shown NoClassDefFound Error.
I'd say the code you need is:
test = input("enter the test")
print(test)
Otherwise it shouldn't run at all, due to a syntax error. The print
function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?
file Sfx.swift
import AVFoundation
public let sfx = Sfx.shared
public final class Sfx: NSObject {
static let shared = Sfx()
var apCheer: AVAudioPlayer? = nil
private override init() {
guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else {
return print("Sfx woe")
}
do {
apComment = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s))
} catch {
return print("Sfx woe")
}
}
func cheer() { apCheer?.play() }
func plonk() { apPlonk?.play() }
func crack() { apCrack?.play() } .. etc
}
Anywhere at all in code
sfx.explosion()
sfx.cheer()
One option you could consider is using CSS variables. The idea is that you set the property you want to change to a CSS variable. Then, within your JS, change that variable's value.
See example below
function changeColor(newColor) {
document.documentElement.style.setProperty("--anchor-hover-color", newColor);
// ^^^^^^^^^^^-- select the root
}
_x000D_
:root {
--anchor-hover-color: red;
}
a:hover {
color: var(--anchor-hover-color);
}
_x000D_
<a href="#">Hover over me</a>
<button onclick="changeColor('lime')">Change to lime</button>
<button onclick="changeColor('red')">Change to red</button>
_x000D_
Try Atatus which provides Advanced Error Tracking and Real User Monitoring for modern web apps.
Let me explain how to get stacktraces that are reasonably complete in all browsers.
Modern Chrome and Opera fully support the HTML 5 draft spec for ErrorEvent and window.onerror
. In both of these browsers you can either use window.onerror
, or bind to the 'error' event properly:
// Only Chrome & Opera pass the error object.
window.onerror = function (message, file, line, col, error) {
console.log(message, "from", error.stack);
// You can send data to your server
// sendError(data);
};
// Only Chrome & Opera have an error attribute on the event.
window.addEventListener("error", function (e) {
console.log(e.error.message, "from", e.error.stack);
// You can send data to your server
// sendError(data);
})
Unfortunately Firefox, Safari and IE are still around and we have to support them too. As the stacktrace is not available in window.onerror
we have to do a little bit more work.
It turns out that the only thing we can do to get stacktraces from errors is to wrap all of our code in a try{ }catch(e){ }
block and then look at e.stack
. We can make the process somewhat easier with a function called wrap that takes a function and returns a new function with good error handling.
function wrap(func) {
// Ensure we only wrap the function once.
if (!func._wrapped) {
func._wrapped = function () {
try{
func.apply(this, arguments);
} catch(e) {
console.log(e.message, "from", e.stack);
// You can send data to your server
// sendError(data);
throw e;
}
}
}
return func._wrapped;
};
This works. Any function that you wrap manually will have good error handling, but it turns out that we can actually do it for you automatically in most cases.
By changing the global definition of addEventListener
so that it automatically wraps the callback we can automatically insert try{ }catch(e){ }
around most code. This lets existing code continue to work, but adds high-quality exception tracking.
var addEventListener = window.EventTarget.prototype.addEventListener;
window.EventTarget.prototype.addEventListener = function (event, callback, bubble) {
addEventListener.call(this, event, wrap(callback), bubble);
}
We also need to make sure that removeEventListener
keeps working. At the moment it won't because the argument to addEventListener
is changed. Again we only need to fix this on the prototype
object:
var removeEventListener = window.EventTarget.prototype.removeEventListener;
window.EventTarget.prototype.removeEventListener = function (event, callback, bubble) {
removeEventListener.call(this, event, callback._wrapped || callback, bubble);
}
You can send error data using image tag as follows
function sendError(data) {
var img = newImage(),
src = 'http://yourserver.com/jserror&data=' + encodeURIComponent(JSON.stringify(data));
img.crossOrigin = 'anonymous';
img.onload = function success() {
console.log('success', data);
};
img.onerror = img.onabort = function failure() {
console.error('failure', data);
};
img.src = src;
}
Disclaimer: I am a web developer at https://www.atatus.com/.
You may think JDBC is a rich API and ResultSet has got so many methods then why not just a getCount() method? Well, For many databases e.g. Oracle, MySQL and SQL Server, ResultSet is a streaming API, this means that it does not load (or maybe even fetch) all the rows from the database server. By iterating to the end of the ResultSet you may add significantly to the time taken to execute in certain cases.
Btw, if you have to there are a couple of ways to do it e.g. by using ResultSet.last() and ResultSet.getRow() method, that's not the best way to do it but it works if you absolutely need it.
Though, getting the column count from a ResultSet is easy in Java. The JDBC API provides a ResultSetMetaData class which contains methods to return the number of columns returned by a query and hold by ResultSet.
If you want to have other than 1 significant decimal (otherwise the same as Evgeny):
>>> from math import log10, floor
>>> def round_sig(x, sig=2):
... return round(x, sig-int(floor(log10(abs(x))))-1)
...
>>> round_sig(0.0232)
0.023
>>> round_sig(0.0232, 1)
0.02
>>> round_sig(1234243, 3)
1230000.0
Conda needs to know where to find you SSL certificate store.
conda config --set ssl_verify <pathToYourFile>.crt
No need to disable SSL verification.
This command add a line to your $HOME/.condarc
file or %USERPROFILE%\.condarc
file on Windows that looks like:
ssl_verify: <pathToYourFile>.crt
If you leave your organization's network, you can just comment out that line in .condarc
with a #
and uncomment when you return.
If it still doesn't work, make sure that you are using the latest version of curl
, checking both the conda-forge
and anaconda
channels.
You could add the default rule with the alter table,
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()
then immediately set to null all the current existing rows:
UPDATE mytable SET created_at = NULL
Then from this point on the DEFAULT
will take effect.
This worked for me in newer browsers:
autocomplete="new-password"
append
is appending an element to a list. if you want to extend the list with the new list you need to use extend
.
>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]
If you're planning to generate a single JAR file with all of its dependencies (the typical xxxx-all.jar), then provided scope matters, because the classes inside this scope won't be package in the resulting JAR.
See maven-assembly-plugin for more information
I solved this on 12.10 by installing libssl-dev.
sudo apt-get install libssl-dev
This might be helpful
from bs4 import UnicodeDammit
with open('automate_data/billboard.csv', 'rb') as file:
content = file.read()
suggestion = UnicodeDammit(content)
suggestion.original_encoding
#'iso-8859-1'
I would answer this with multiple options actually, the some of which actually render in the body.
<input onclick="myfunction()"/>
- better to put it in event handlers in your script body instead.Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).
EDIT: references:
Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; }
on the div)
Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html
EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.
You can directly export the query result with export option in the result grig. This export has various options to export. I think this will work.
A handy timestamp format:
%date:~3,2%/%date:~0,2%/%date:~6,2%-%time:~0,8%
Your #container should be outside of the #header-wrap, then specify a fixed height for #header-wrap, after, specify margin-top for #container equal to the #header-wrap's height. Something like this:
#header-wrap {
position: fixed;
height: 200px;
top: 0;
width: 100%;
z-index: 100;
}
#container{
margin-top: 200px;
}
Hope this is what you need: http://jsfiddle.net/KTgrS/
This single line works better imho:
Application.Evaluate("SUMPRODUCT(--(E10:E14<>""""))=0")
in this case, it evaluates if range E10:E14 is empty.
simple way :
-(void) viewDidLoad {
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.png"]];
[super viewDidLoad];
}
This is how you do it
SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS
FROM TABLE
ORDER BY SUM_COUNTS LIMIT 20
The SUM function will add up all rows, so the order by
clause is useless, instead you will have to use the group by
clause.
Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in
/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf (its called Catalina Base and is often hidden)
instead of the apacahe installation directory.
open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.
<user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>
restart the server . That's all
In Visual Studio 2008 + , go to the
Tools menu --> select Options
In Options Window --> expand Source Control --> Select Subversion User Tools --> Select Beyond Compare
and click OK button..
Update: This answer is outdated as newer versions of libraries mentioned are released since then.
Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.
"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.
See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539
The following creates a generic function, taking an array of any size and of any type by reference:
template<typename T, std::size_t S>
void my_func(T (&arr)[S]) {
// do stuff
}
You can resolve this issue by reinstalling pip.
Use one of the following command line commands to reinstall pip:
Python2:
python -m pip uninstall pip && sudo apt install python-pip --reinstall
Python3:
python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall
KEYS command should not be used on Redis production instances if you have a lot of keys, since it may block the Redis event loop for several seconds.
I would generate a dump (bgsave), and then use the following Python package to parse it and extract the data:
https://github.com/sripathikrishnan/redis-rdb-tools
You can have json output, or customize your own output in Python.
You should have a look at moment
which is a python port of the excellent js lib momentjs
.
One advantage of it is the support of ISO 8601
strings formats, as well as a generic "% format" :
import moment
time_string='2012-10-09T19:00:55Z'
m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday
Result:
2012-10-09 19:10
2
Here is my Approach based on DarKalimHero's Suggestion by selecting only on Explorer.exe processes
Function Get-RdpSessions
{
param(
[string]$computername
)
$processinfo = Get-WmiObject -Query "select * from win32_process where name='explorer.exe'" -ComputerName $computername
$processinfo | ForEach-Object { $_.GetOwner().User } | Sort-Object -Unique | ForEach-Object { New-Object psobject -Property @{Computer=$computername;LoggedOn=$_} } | Select-Object Computer,LoggedOn
}
When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.
Strings using set()
:
set(MyString "Some Text")
set(MyStringWithVar "Some other Text: ${MyString}")
set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")
Or with string()
:
string(APPEND MyStringWithContent " ${MyString}")
Lists using set()
:
set(MyList "a" "b" "c")
set(MyList ${MyList} "d")
Or better with list()
:
list(APPEND MyList "a" "b" "c")
list(APPEND MyList "d")
Lists of File Names:
set(MySourcesList "File.name" "File with Space.name")
list(APPEND MySourcesList "File.name" "File with Space.name")
add_excutable(MyExeTarget ${MySourcesList})
set()
Commandstring()
Commandlist()
CommandFirst there are the "Normal Variables" and things you need to know about their scope:
CMakeLists.txt
they are set in and everything called from there (add_subdirectory()
, include()
, macro()
and function()
).add_subdirectory()
and function()
commands are special, because they open-up their own scope.
set(...)
there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).set(... PARENT_SCOPE)
function(xyz _resultVar)
is setting set(${_resultVar} 1 PARENT_SCOPE)
include()
or macro()
scripts will modify variables directly in the scope of where they are called from. Second there is the "Global Variables Cache". Things you need to know about the Cache:
CMakeCache.txt
file in your binary output directory.The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type
and a docstring
. I normally don't use the GUI so I use set(... CACHE INTERNAL "")
to set my global and persistant values.
Please note that the INTERNAL
cache variable type does imply FORCE
In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE)
syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.
cmake -D var:type=value
, just cmake -D var=value
or with cmake -C CMakeInitialCache.cmake
.unset(... CACHE)
.The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...)
and set_property(GLOBAL APPEND PROPERTY ...)
syntax to define my own non-persistant global variables.
To avoid pitfalls you should know the following about variables:
find_...
commands - if successful - do write their results as cached variables "so that no call will search again"set(MyVar a b c)
is "a;b;c"
and set(MyVar "a b c")
is "a b c"
list()
command for handling listsfunctions()
instead of macros()
because you don't want your local variables to show up in the parent scope. project()
and enable_language()
calls. So it could get important to set some variables before those commands are used.Sometimes only debugging variables helps. The following may help you:
printf
debugging style by using the message()
command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmakeCMakeCache.txt
file in your binary output directory. This file is even generated if the actual generation of your make environment fails.cmake --trace ...
to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.$ENV{...}
and write set(ENV{...} ...)
environment variables$<...>
are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)${${...}}
you can give variable names in a variable and reference its content.if()
command)
if(MyVariable)
you can directly check a variable for true/false (no need here for the enclosing ${...}
)1
, ON
, YES
, TRUE
, Y
, or a non-zero number. 0
, OFF
, NO
, FALSE
, N
, IGNORE
, NOTFOUND
, the empty string, or ends in the suffix -NOTFOUND
.if(MSVC)
, but it can be confusing for someone who does not know this syntax shortcut.set(CMAKE_${lang}_COMPILER ...)
if()
commands. Here is an example where CMAKE_CXX_COMPILER_ID
is "MSVC"
and MSVC
is "1"
:
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
is true, because it evaluates to if("1" STREQUAL "1")
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
is false, because it evaluates to if("MSVC" STREQUAL "1")
if(MSVC)
cmake_policy(SET CMP0054 NEW)
to "only interpret if()
arguments as variables or keywords when unquoted."option()
command
ON
or OFF
and they allow some special handling like e.g. dependenciesoption
with the set
command. The value given to option
is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.Set
dgv.CurrentCell = null;
when user clicks on a blank part of the dgv.
You can use pd.DataFrame constructor, giving a numpy array (data) and a list of the names of the columns (columns). To have everything in one DataFrame, you can concatenate the features and the target into one numpy array with np.c_[...] (note the square brackets and not parenthesis). Also, you can have some trouble if you don't convert the feature names (iris['feature_names']) to a list before concatenation:
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= list(iris['feature_names']) + ['target'])
An optimized Imran Tariq's version
Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();
Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.
In my project with netcore 2.2 I use this code:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
OkObjectResult result = Ok( payload );
// currently result.Formatters is empty but we'd like to ensure it will be so in the future
result.Formatters.Clear();
// force response as xml
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
It forces only one action within a controller to return a xml without effect to other actions. Also this code doesn't contain neither HttpResponseMessage or StringContent or ObjectContent which are disposable objects and hence should be handled appropriately (it is especially a problem if you use any of code analyzers that reminds you about it).
Going further you could use a handy extension like this:
public static class ObjectResultExtensions
{
public static T ForceResultAsXml<T>( this T result )
where T : ObjectResult
{
result.Formatters.Clear();
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
}
And your code will become like this:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
return Ok( payload ).ForceResultAsXml();
}
In addition, this solution looks like an explicit and clean way to force return as xml and it is easy to add to your existent code.
P.S. I used fully-qualified name Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter just to avoid ambiguity.
Faced the same problem as OP:
Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.
Interfaces are not part of the ES6 but classes are.
If you really need them, you should look at TypeScript which support them.
Try:
/usr/local/mysql/bin/mysqladmin -u root -p shutdown
Or:
sudo mysqld stop
Or:
sudo /usr/local/mysql/bin/mysqld stop
Or:
sudo mysql.server stop
If you install the Launchctl in OSX you can try:
sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql.plist
Note: this is persistent after reboot.
launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart
I found that in: https://stackoverflow.com/a/102094/58768
class Testclass
{
public $testvar;
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething(); ////It will print "another value"
new
/delete
is C++, malloc
/free
comes from good old C.
In C++, new
calls an objects constructor and delete
calls the destructor.
malloc
and free
, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.
Think more about what you are installing and navigate Gemfile folder, then try using sudo bundle install
As others have said, the minumum/maximum values the column can store and how much storage it takes in bytes is only defined by the type, not the length.
A lot of these answers are saying that the (11)
part only affects the display width which isn't exactly true, but mostly.
A definition of int(2)
with no zerofill specified will:
100
100
when output (not 0
or 00
)The only thing the (2)
will do is if zerofill is also specified:
1
will be shown 01
. The best way to see all the nuances is to run:
CREATE TABLE `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`int1` int(10) NOT NULL,
`int2` int(3) NOT NULL,
`zf1` int(10) ZEROFILL NOT NULL,
`zf2` int(3) ZEROFILL NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `mytable`
(`int1`, `int2`, `zf1`, `zf2`)
VALUES
(10000, 10000, 10000, 10000),
(100, 100, 100, 100);
select * from mytable;
which will output:
+----+-------+-------+------------+-------+
| id | int1 | int2 | zf1 | zf2 |
+----+-------+-------+------------+-------+
| 1 | 10000 | 10000 | 0000010000 | 10000 |
| 2 | 100 | 100 | 0000000100 | 100 |
+----+-------+-------+------------+-------+
This answer is tested against MySQL 5.7.12 for Linux and may or may not vary for other implementations.
This works for me (tested OK!):
HTML:
<div class="mydiv">
<p>Item to be centered!</p>
</div>
CSS:
.mydiv {
height: 100%; /* Or other */
position: relative;
}
.mydiv p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%); /* To compensate own width and height */
}
You can choose other values than 50%. For example, 25% to center at 25% of parent.
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads
and then you can parse it with index.
Instead of using .read()
to intermediately save it to memory and then read it to json
, allow json
to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it.
Visual Studio can also open the files directly if was created with the right version of SQL Compact.
There are also some third-party tools for manipulating them.
ASCII is a subset of UTF-8, so if a document is ASCII then it is already UTF-8.
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
An abstract class cannot be instantiated by definition. In order to use this class, you must create a concrete subclass which implements all virtual functions of the class. In this case, you most likely have not implemented all the virtual functions declared in Light
. This means that AmbientOccluder
defaults to an abstract class. For us to further help you, you should include the details of the Light
class.
As far as I know there are three methods you can do that.
1.use regular expression to get query string.
2.you can use the browser api. image the current url is like this:
http://www.google.com.au?token=123
we just want to get 123;
First
const query = new URLSearchParams(this.props.location.search);
Then
const token = query.get('token')
console.log(token)//123
3. use a third library called 'query-string'. First install it
npm i query-string
Then import it to the current javascript file:
import queryString from 'query-string'
Next step is to get 'token' in the current url, do the following:
const value=queryString.parse(this.props.location.search);
const token=value.token;
console.log('token',token)//123
Hope it helps.
Updated on 25/02/2019
http://www.google.com.au?app=home&act=article&aid=160990
we define a function to get the parameters:
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
console.log(query)//"app=article&act=news_content&aid=160990"
var vars = query.split("&");
console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ]
if(pair[0] == variable){return pair[1];}
}
return(false);
}
We can get 'aid' by :
getQueryVariable('aid') //160990
Solved mine with
File -> Settings -> Build, Execution, Deployment -> Build Tools ->
Gradle -> Offline work
Gradle builds went from 8 minutes to 3 seconds.
In my project I had the same error, I restarted Tomcat and it worked, withtout killing the java process.
Here's a straight forward implementation of the md5sum
command that computes and displays the MD5 of the file specified on the command-line. It needs to be linked against the OpenSSL library (gcc md5.c -o md5 -lssl
) to work. It's pure C, but you should be able to adapt it to your C++ application easily enough.
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
unsigned char result[MD5_DIGEST_LENGTH];
// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md) {
int i;
for(i=0; i <MD5_DIGEST_LENGTH; i++) {
printf("%02x",md[i]);
}
}
// Get the size of the file by its file descriptor
unsigned long get_size_by_fd(int fd) {
struct stat statbuf;
if(fstat(fd, &statbuf) < 0) exit(-1);
return statbuf.st_size;
}
int main(int argc, char *argv[]) {
int file_descript;
unsigned long file_size;
char* file_buffer;
if(argc != 2) {
printf("Must specify the file\n");
exit(-1);
}
printf("using file:\t%s\n", argv[1]);
file_descript = open(argv[1], O_RDONLY);
if(file_descript < 0) exit(-1);
file_size = get_size_by_fd(file_descript);
printf("file size:\t%lu\n", file_size);
file_buffer = mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0);
MD5((unsigned char*) file_buffer, file_size, result);
munmap(file_buffer, file_size);
print_md5_sum(result);
printf(" %s\n", argv[1]);
return 0;
}
I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.
However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
As per the Font Awesome Documentation:
<ul class="fa-ul">
<li><i class="fa-li fa fa-check"></i>Barbabella</li>
<li><i class="fa-li fa fa-check"></i>Barbaletta</li>
<li><i class="fa-li fa fa-check"></i>Barbalala</li>
</ul>
Or, using Jade:
ul.fa-ul
li
i.fa-li.fa.fa-check
| Barbabella
li
i.fa-li.fa.fa-check
| Barbaletta
li
i.fa-li.fa.fa-check
| Barbalala
Assume that the source file you want to compile is main.cpp and your example_dll.dll and example_dll.lib . now run cl.exe main.cpp /EHsc /link example_dll.lib
now you may get main.exe
You can use the str.format() to make Python recognize any objects to strings.
You could simply do :
double d = (double)15552451L;
Or you could get double from Long object as :
Long l = new Long(15552451L);
double d = l.doubleValue();
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
I was going through the textbook:Computer System: a programmer's perspective, and there is a problem to determine which endian is this by C program.
I used the feature of the pointer to do that as following:
#include <stdio.h>
int main(void){
int i=1;
unsigned char* ii = &i;
printf("This computer is %s endian.\n", ((ii[0]==1) ? "little" : "big"));
return 0;
}
As the int takes up 4 bytes, and char takes up only 1 bytes. We could use a char pointer to point to the int with value 1. Thus if the computer is little endian, the char that char pointer points to is with value 1, otherwise, its value should be 0.
Here is another way that is simple, and very effective:
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = new Array(11);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');
document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());
</script></div><!-- #time -->
For HTTP Basic Auth:
curl -H "Authorization: Basic <_your_token_>" http://www.example.com
replace _your_token_
and the URL.
I had this problem, did not find any ini file in Windows, but the solution that worked for me was very simple.
1. Open the mysql installer.
2. Reconfigure mysql server, it is the first link.
3. Go to authentication method.
4. Choose 'Legacy authentication'.
5. Give your password(next field).
6. Apply changes.
That's it, hope my solution works fine for you as well!
If you haven't created migrations, there are 2 options
1.create the database and tables from application Main:
var context = services.GetRequiredService<YourRepository>();
context.Database.EnsureCreated();
2.create the tables if the database already exists:
var context = services.GetRequiredService<YourRepository>();
context.Database.EnsureCreated();
RelationalDatabaseCreator databaseCreator =
(RelationalDatabaseCreator)context.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();
Thanks to Bubi's answer
The %run
magic has a parameter file_finder
that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending ".py" if necessary.
There doesn't seem to be a way to specify which file finder to use from the %run
magic, but there's nothing to stop you from defining your own magic command that calls into %run
with an appropriate file finder.
As a very nasty hack, you could override the default file_finder
with your own:
IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder
To be honest, at the rate the IPython API is changing that's as likely to continue to work as defining your own magic is.
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
I replaced all the single quotes ['] to double quotes ["] and then it worked perfectly. Thanks for the input by @LogicalKip.
I went back to the JavaDoc for org.hibernate.Session
and found the following:
Transient instances may be made persistent by calling
save()
,persist()
orsaveOrUpdate()
. Persistent instances may be made transient by callingdelete()
. Any instance returned by aget()
orload()
method is persistent. Detached instances may be made persistent by callingupdate()
,saveOrUpdate()
,lock()
orreplicate()
. The state of a transient or detached instance may also be made persistent as a new persistent instance by callingmerge()
.
Thus update()
, saveOrUpdate()
, lock()
, replicate()
and merge()
are the candidate options.
update()
: Will throw an exception if there is a persistent instance with the same identifier.
saveOrUpdate()
: Either save or update
lock()
: Deprecated
replicate()
: Persist the state of the given detached instance, reusing the current identifier value.
merge()
: Returns a persistent object with the same identifier. The given instance does not become associated with the session.
Hence, lock()
should not be used straightway and based on the functional requirement one or more of them can be chosen.
I'm using version 4.0.3 of MAMP along with phpmyadmin. The top of /Applications/MAMP/bin/phpMyAdmin/libraries/config.default.php reads:
DO NOT EDIT THIS FILE, EDIT config.inc.php INSTEAD !!!
Changing the following line in /Applications/MAMP/bin/phpMyAdmin/config.inc.php and restarting MAMP worked for me.
$cfg['ExecTimeLimit'] = 0;
If you offer cbind
a set of arguments all of whom are vectors, you will get not a dataframe, but rather a matrix, in this case an all character matrix. They have different features. You can get a dataframe if some of your arguments remain dataframes, Try:
merger <- cbind(Date =as.character(Date),
weather1[ , c("High", "Low", "Avg..High", "Avg.Low")] ,
ScnMov =sale$Scanned.Movement[a] )
Here is my solution which works fine with ajax loaded content too.
/*
* popover handler assigned document (or 'body')
* triggered on hover, show content from data-content or
* ajax loaded from url by using data-remotecontent attribute
*/
$(document).popover({
selector: 'a.preview',
placement: get_popover_placement,
content: get_popover_content,
html: true,
trigger: 'hover'
});
function get_popover_content() {
if ($(this).attr('data-remotecontent')) {
// using remote content, url in $(this).attr('data-remotecontent')
$(this).addClass("loading");
var content = $.ajax({
url: $(this).attr('data-remotecontent'),
type: "GET",
data: $(this).serialize(),
dataType: "html",
async: false,
success: function() {
// just get the response
},
error: function() {
// nothing
}
}).responseText;
var container = $(this).attr('data-rel');
$(this).removeClass("loading");
if (typeof container !== 'undefined') {
// show a specific element such as "#mydetails"
return $(content).find(container);
}
// show the whole page
return content;
}
// show standard popover content
return $(this).attr('data-content');
}
function get_popover_placement(pop, el) {
if ($(el).attr('data-placement')) {
return $(el).attr('data-placement');
}
// find out the best placement
// ... cut ...
return 'left';
}
Please try with the steps below:
P.S. I experienced the same problem when I was playing with the options to redirect the console input / output to text file and have selected the option Properties - Debug - (Start Action section) - Start external program. When I moved the Solution to another location on my computer the problem occurred because it was searching for an absolute path to the executable file. Restoring the Visual Studio Project default settings (see above) fixed the problem. For your reference I am using Visual Studio 2013 Professional.
To add to svick's answer, the -m
option simply adds a message to your stash, and is entirely optional. Thus, the command
git stash push [paths you wish to stash]
is perfectly valid. So for instance, if I want to only stash changes in the src/
directory, I can just run
git stash push src/
So based on what you said, these files are libraries/documentation you don't want to delete but also don't want to push to github
. Let say you have your project in folder your_project
and a doc directory: your_project/doc
.
git rm --cached doc/*
.gitignore
, you can make one right inside of your project folder: project/.gitignore
. doc/*
in the .gitignore git add project/.gitignore
git commit -m "message"
. github
.DATE
is a reserved keyword in Oracle, so I'm using column-name your_date
instead.
If you have an index on your_date
, I would use
WHERE your_date >= TO_DATE('2010-08-03', 'YYYY-MM-DD')
AND your_date < TO_DATE('2010-08-04', 'YYYY-MM-DD')
or BETWEEN
:
WHERE your_date BETWEEN TO_DATE('2010-08-03', 'YYYY-MM-DD')
AND TO_DATE('2010-08-03 23:59:59', 'YYYY-MM-DD HH24:MI:SS')
If there is no index or if there are not too many records
WHERE TRUNC(your_date) = TO_DATE('2010-08-03', 'YYYY-MM-DD')
should be sufficient. TRUNC
without parameter removes hours, minutes and seconds from a DATE
.
If performance really matters, consider putting a Function Based Index
on that column:
CREATE INDEX trunc_date_idx ON t1(TRUNC(your_date));
If you would like to work with a textbox, be aware that setting the TextMode property to "Date" will not work on Internet Explorer 11, because it does not currently support the "Date", "DateTime", nor "Time" values.
This example illustrates how to implement it using a textbox, including validation of the dates (since the user could enter just numbers). It will work on Internet Explorer 11 as well other web browsers.
<asp:Content ID="Content"
ContentPlaceHolderID="MainContent"
runat="server">
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#
<%= txtBoxDate.ClientID %>").datepicker();
});
</script>
<asp:TextBox ID="txtBoxDate"
runat="server"
Width="135px"
AutoPostBack="False"
TabIndex="1"
placeholder="mm/dd/yyyy"
autocomplete="off"
MaxLength="10"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ControlToValidate="txtBoxDate"
Operator="DataTypeCheck"
Type="Date">Date invalid, please check format.
</asp:CompareValidator>
</asp:Content>
This line causes the [unchecked] warning:
List<String> list = new LinkedList();
So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?
I think, it would be much more difficult task then adding <>
feature.
UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.
You can pass the extension of the format you want as the end of the url. like http://localhost:8080/xx/xxx/xxxx.json
or
http://localhost:8080/xx/xxx/xxxx.xml
Note: you need to add jackson and jaxb maven dependencies in your pom.
For example :
<div style="height:100px; width:100px; background:#000000"></div>
_x000D_
here.
you give css to div of height and width having 100px and background as black.
PS : try to avoid inline-css you can make external CSS and import in your html file.
you can refer here for CSS
hope this helps.
if You want daily backup // following sql script store in C:\Users\admin\Desktop\DBScript\DBBackUpSQL.sql
DECLARE @pathName NVARCHAR(512),
@databaseName NVARCHAR(512) SET @databaseName = 'Databasename' SET @pathName = 'C:\DBBackup\DBData\DBBackUp' + Convert(varchar(8), GETDATE(), 112) + '_' + Replace((Convert(varchar(8), GETDATE(), 108)),':','-')+ '.bak' BACKUP DATABASE @databaseName TO DISK = @pathName WITH NOFORMAT,
INIT,
NAME = N'',
SKIP,
NOREWIND,
NOUNLOAD,
STATS = 10
GO
open the Task scheduler
create task-> select Triggers
tab Select New
.
Button Select Daily Radio button
click Ok
Button
then click Action
tab Select New.
Button Put "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE"
-S ADMIN-PC -i "C:\Users\admin\Desktop\DBScript\DBBackUpSQL.sql"
in the program/script text box(make sure Match your files path and Put the double quoted path in start-> search box and if it find then click it and see the backup is there or not)
-- the above path may be insted 100 write 90 "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -S ADMIN-PC -i
"C:\Users\admin\Desktop\DBScript\DBBackUpSQL.sql"
then click ok button
the Script will execute on time which you select on Trigger tab on daily basis
enjoy it.............
Should it not be foreach
instead of for!?
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("MyRow", **typeof**(System.Int32));
foreach(DataRow dr in dt.Rows)
{
//need to set value to MyRow column
dr["MyRow"] = 0; // or set it to some other value
}
I was able to get this to work thanks to this post utilizing VisualWGet. It worked great for me. The important part seems to be to check the -recursive
flag (see image).
Also found that the -no-parent
flag is important, othewise it will try to download everything.
I think a more readable and flexible option is to use Where function:
var result = from x in entity1
from y in entity2
.Where(y => y.field1 == x.field1 && y.field2 == x.field2)
This also allows to easily change from inner join to left join by appending .DefaultIfEmpty().
followings programs will execute,"one number is multiple of another" in
#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}
You likely have other files (such as the default
configuration) located in /etc/nginx/sites-enabled
that needs to be removed.
This issue is caused by a repeat of the default_server
parameter supplied to one or more listen
directives in your files. You'll likely find this conflicting directive reads something similar to:
listen 80 default_server;
As the nginx core module documentation for listen
states:
The
default_server
parameter, if present, will cause the server to become the default server for the specifiedaddress:port
pair. If none of the directives have thedefault_server
parameter then the first server with theaddress:port
pair will be the default server for this pair.
This means that there must be another file or server
block defined in your configuration with default_server
set for port 80. nginx is encountering that first before your mysite.com
file so try removing or adjusting that other configuration.
If you are struggling to find where these directives and parameters are set, try a search like so:
grep -R default_server /etc/nginx
Consider the following:
int n;
for(n = 0; n < 10; ++n) {
break;
}
System.out.println(n);
break causes the loop to terminate and the value of n is 0.
int n;
for(n = 0; n < 10; ++n) {
continue;
}
System.out.println(n);
continue causes the program counter to return to the first line of the loop (the condition is checked and the value of n is increment) and the final value of n is 10.
It should also be noted that break only terminates the execution of the loop it is within:
int m;
for(m = 0; m < 5; ++m)
{
int n;
for(n = 0; n < 5; ++n) {
break;
}
System.out.println(n);
}
System.out.println(m);
Will output something to the effect of
0
0
0
0
0
5
I encountered this problem on my laptop. I found the solution for this problem.
Then do this
If there is no patch number, ~
is equivalent to appending .x
to the non-tilde version. If there is a patch number, ~
allows all patch numbers >= the specified one.
~1 := 1.x
~1.2 := 1.2.x
~1.2.3 := (>=1.2.3 <1.3.0)
I don't have enough points to comment on the accepted answer, but some of the tilde information is at odds with the linked semver documentation: "angular": "~1.2"
will not match 1.3, 1.4, 1.4.9. Also "angular": "~1"
and "angular": "~1.0"
are not equivalent. This can be verified with the npm semver calculator.
ES7
class member syntax:ES7
has a solution for 'junking' your constructor function. Here is an example:
class Car {_x000D_
_x000D_
wheels = 4;_x000D_
weight = 100;_x000D_
_x000D_
}_x000D_
_x000D_
const car = new Car();_x000D_
console.log(car.wheels, car.weight);
_x000D_
The above example would look the following in ES6
:
class Car {_x000D_
_x000D_
constructor() {_x000D_
this.wheels = 4;_x000D_
this.weight = 100;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
const car = new Car();_x000D_
console.log(car.wheels, car.weight);
_x000D_
Be aware when using this that this syntax might not be supported by all browsers and might have to be transpiled an earlier version of JS.
function generateCar(wheels, weight) {_x000D_
_x000D_
class Car {_x000D_
_x000D_
constructor() {}_x000D_
_x000D_
wheels = wheels;_x000D_
weight = weight;_x000D_
_x000D_
}_x000D_
_x000D_
return new Car();_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
const car1 = generateCar(4, 50);_x000D_
const car2 = generateCar(6, 100);_x000D_
_x000D_
console.log(car1.wheels, car1.weight);_x000D_
console.log(car2.wheels, car2.weight);
_x000D_
The solution I have used is:
<svg>
<line x1="100" y1="100" x2="500" y2="100" style="stroke:black; stroke-width: 2"/>
<text x="150" y="105" style="stroke:white; stroke-width:0.6em">Hello World!</text>
<text x="150" y="105" style="fill:black">Hello World!</text>
</svg>
_x000D_
A duplicate text item is being placed, with stroke and stroke-width attributes. The stroke should match the background colour, and the stroke-width should be just big enough to create a "splodge" on which to write the actual text.
A bit of a hack and there are potential issues, but works for me!
You could put a _ViewStart.cshtml
file inside the /Views/Public
folder which would override the default one in the /Views
folder and specify the desired layout:
@{
Layout = "~/Views/Shared/_PublicLayout.cshtml";
}
By analogy you could put another _ViewStart.cshtml
file inside the /Views/Staff
folder with:
@{
Layout = "~/Views/Shared/_StaffLayout.cshtml";
}
You could also specify which layout should be used when returning a view inside a controller action but that's per action:
return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);
Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.
UPDATE:
As requested in the comments section here's an example of an action filter which would choose a master page:
public class LayoutInjecterAttribute : ActionFilterAttribute
{
private readonly string _masterName;
public LayoutInjecterAttribute(string masterName)
{
_masterName = masterName;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var result = filterContext.Result as ViewResult;
if (result != null)
{
result.MasterName = _masterName;
}
}
}
and then decorate a controller or an action with this custom attribute specifying the layout you want:
[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
return View();
}
Use a HTML parser like Jsoup. This has my preference above the other HTML parsers available in Java since it supports jQuery like CSS selectors. Also, its class representing a list of nodes, Elements
, implements Iterable
so that you can iterate over it in an enhanced for loop (so there's no need to hassle with verbose Node
and NodeList
like classes in the average Java DOM parser).
Here's a basic kickoff example (just put the latest Jsoup JAR file in classpath):
package com.stackoverflow.q2835505;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Test {
public static void main(String[] args) throws Exception {
String url = "https://stackoverflow.com/questions/2835505";
Document document = Jsoup.connect(url).get();
String question = document.select("#question .post-text").text();
System.out.println("Question: " + question);
Elements answerers = document.select("#answers .user-details a");
for (Element answerer : answerers) {
System.out.println("Answerer: " + answerer.text());
}
}
}
As you might have guessed, this prints your own question and the names of all answerers.
Your routes.php file needs to be setup correctly.
What I am assuming your current setup is like:
Route::post('/empresas/eliminar/{id}','CompanyController@companiesDelete');
or something. Define a route for the delete method instead.
Route::delete('/empresas/eliminar/{id}','CompanyController@companiesDelete');
Now if you are using a Route resource, the default route name to be used for the 'DELETE' method is .destroy. Define your delete logic in that function instead.
I think this should do the trick using the Collections API:
Note: the copy method runs in linear time.
//assume oldList exists and has data in it.
List<String> newList = new ArrayList<String>();
Collections.copy(newList, oldList);
You don't have to calculate how far to shift everything down, there's a build in property for this. In Interface Builder, highlight your view controller, and then navigate to the attributes inspector. Here you'll see some check boxes next to the words "Extend Edges". As you can see, in the first screenshot, the default selection is for content to appear under top and bottom bars, but not under opaque bars, which is why setting the bar style to not translucent worked for you.
As you can somewhat see in the first screenshot, there are two UI elements hiding below the navigation bar. (I've enabled wireframes in IB to illustrate this) These elements, a UIButton and a UISegmentedControl both have their "y" origin set to zero, and the view controller is set to allow content below the top bar.
This second screenshot shows what happens when you deselect the "Under Top Bars" check box. As you can see, the view controllers view has been shifted down appropriately for its y origin to be right underneath the navigation bar.
This can also be accomplished programmatically through the usage of -[UIViewController edgesForExtendedLayout]
. Here's a link to the class reference for edgeForExtendedLayout, and for UIRectEdge
[self setEdgesForExtendedLayout:UIRectEdgeNone];
Probably the browser first downloaded the validade script and then jQuery. If the validade script be downloaded before loading jQuery you'll get an error. You can see this using a tool like firebug.
Try this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function LoadValidade() {
var a = false;
try {
var teste = $('*');
if(teste == null)
throw 1;
} catch (e) {
a = true;
}
if (a){
setTimeout(LoadValidade, 300);
return;
}
var validadeScript = document.createElement("script");
validadeScript.src = "../common/jquery.validate.js";
$('head')[0].appendChild(validadeScript);
}
setTimeout(LoadValidade, 300);
</script>
The approach you're looking for is FillDown
. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:
Sub FillDown()
Dim strFormulas(1 To 3) As Variant
With ThisWorkbook.Sheets("Sheet1")
strFormulas(1) = "=SUM(A2:B2)"
strFormulas(2) = "=PRODUCT(A2:B2)"
strFormulas(3) = "=A2/B2"
.Range("C2:E2").Formula = strFormulas
.Range("C2:E11").FillDown
End With
End Sub
Screenshots:
Result as of line: .Range("C2:E2").Formula = strFormulas
:
Result as of line: .Range("C2:E11").FillDown
:
Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown
, much like what you did.
Hope this helps!
This is the best solution (IMO) as it requires no jQuery and no JSON decode:
Source: https://wordpress.stackexchange.com/a/179373 and: https://stackoverflow.com/a/1714899/196507
Summary:
//Replacement of jQuery.param
var serialize = function(obj, prefix) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
};
//Your AngularJS application:
var app = angular.module('foo', []);
app.config(function ($httpProvider) {
// send all requests payload as query string
$httpProvider.defaults.transformRequest = function(data){
if (data === undefined) {
return data;
}
return serialize(data);
};
// set all post requests content type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
Example:
...
var data = { id: 'some_id', name : 'some_name' };
$http.post(my_php_url,data).success(function(data){
// It works!
}).error(function() {
// :(
});
PHP code:
<?php
$id = $_POST["id"];
?>
line 2 should be
for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**
For line 3, I'm having to do
JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
Install Qt
sudo apt-get install build-essential
sudo apt-get install qtcreator
sudo apt-get install qt5-default
Install documentation and examples If Qt Creator is installed thanks to the Ubuntu Sofware Center or thanks to the synaptic package manager, documentation for Qt Creator is not installed. Hitting the F1 key will show you the following message : "No documentation available". This can easily be solved by installing the Qt documentation:
sudo apt-get install qt5-doc
sudo apt-get install qt5-doc-html qtbase5-doc-html
sudo apt-get install qtbase5-examples
Restart Qt Creator to make the documentation available.
Error while loading shared libraries
Problem:
radiusd: error while loading shared libraries: libfreeradius-radius-2.1.10.so: cannot open shared object file: No such file or directory
Reason:
Actually, the libraries have been installed in a place where dynamic linker cannot find it.
Solution:
While this is not a guarantee but using the following command may help you solve the “cannot open shared object file” error:
sudo /sbin/ldconfig -v
http://www.lucidarme.me/how-install-documentation-for-qt-creator/
https://ubuntuforums.org/showthread.php?t=2199929
I have faced the same problem few hours ago.
The ".clear()" method actually clears the canvas, but (evidently) it leaves the object alive and reactive.
Reading carefully the official documentation, in the "Advanced usage" section, I have noticed the method ".destroy()", described as follows:
"Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js."
It actually does what it claims and it has worked fine for me, I suggest you to give it a try.
With YAML, remember that it is all about the spaces used to define configuration through the hierarchical structures (indents). Many problems encountered whilst parsing YAML documents simply stems from extra spaces (or not enough spaces) before a key value somewhere in the given YAML file.
If you also have jQuery UI, you can add this:
$(document).ready(function () {
$(document).tooltip();
});
You then need a title instead of a hidden input. RGraham already posted an answer doing this for you :P
You started with a one-dimensional list of numbers. Once you used numpy.newaxis
, you turned it into a two-dimensional matrix, consisting of four rows of one column each.
You could then use that matrix for matrix multiplication, or involve it in the construction of a larger 4 x n matrix.
You had selected the time format wrong
<?php
date_default_timezone_set('GMT');
echo date("Y-m-d,h:m:s");
?>
Maybe I missunderstand the singleton pattern but my solution is this simple and pragmatic (pythonic?). This code fullfills two goals
Foo
accessiable everywhere (global).Foo
can exist.This is the code.
#!/usr/bin/env python3
class Foo:
me = None
def __init__(self):
if Foo.me != None:
raise Exception('Instance of Foo still exists!')
Foo.me = self
if __name__ == '__main__':
Foo()
Foo()
Output
Traceback (most recent call last):
File "./x.py", line 15, in <module>
Foo()
File "./x.py", line 8, in __init__
raise Exception('Instance of Foo still exists!')
Exception: Instance of Foo still exists!
The upcoming change is for chinese, arabic domain names not URIs. The internationalised URIs are called IRIs and are defined in RFC 3987. However, having said that I'd recommend not doing this yourself but relying on an existing, tested library since there are lots of choices of URI encoding/decoding and what are considered safe by specification, versus what are safe by actual use (browsers).