You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document
The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS
setting.
In your project settings.py file,set ALLOWED_HOSTS
like this :
ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']
For further reading read from here.
At the bottom of this answer is an example of GLSL code which allows to output the full float
value as color, encoding IEEE 754 binary32
. I use it like follows (this snippet gives out yy
component of modelview matrix):
vec4 xAsColor=toColor(gl_ModelViewMatrix[1][1]);
if(bool(1)) // put 0 here to get lowest byte instead of three highest
gl_FrontColor=vec4(xAsColor.rgb,1);
else
gl_FrontColor=vec4(xAsColor.a,0,0,1);
After you get this on screen, you can just take any color picker, format the color as HTML (appending 00
to the rgb
value if you don't need higher precision, and doing a second pass to get the lower byte if you do), and you get the hexadecimal representation of the float
as IEEE 754 binary32
.
Here's the actual implementation of toColor()
:
const int emax=127;
// Input: x>=0
// Output: base 2 exponent of x if (x!=0 && !isnan(x) && !isinf(x))
// -emax if x==0
// emax+1 otherwise
int floorLog2(float x)
{
if(x==0.) return -emax;
// NOTE: there exist values of x, for which floor(log2(x)) will give wrong
// (off by one) result as compared to the one calculated with infinite precision.
// Thus we do it in a brute-force way.
for(int e=emax;e>=1-emax;--e)
if(x>=exp2(float(e))) return e;
// If we are here, x must be infinity or NaN
return emax+1;
}
// Input: any x
// Output: IEEE 754 biased exponent with bias=emax
int biasedExp(float x) { return emax+floorLog2(abs(x)); }
// Input: any x such that (!isnan(x) && !isinf(x))
// Output: significand AKA mantissa of x if !isnan(x) && !isinf(x)
// undefined otherwise
float significand(float x)
{
// converting int to float so that exp2(genType) gets correctly-typed value
float expo=float(floorLog2(abs(x)));
return abs(x)/exp2(expo);
}
// Input: x\in[0,1)
// N>=0
// Output: Nth byte as counted from the highest byte in the fraction
int part(float x,int N)
{
// All comments about exactness here assume that underflow and overflow don't occur
const float byteShift=256.;
// Multiplication is exact since it's just an increase of exponent by 8
for(int n=0;n<N;++n)
x*=byteShift;
// Cut higher bits away.
// $q \in [0,1) \cap \mathbb Q'.$
float q=fract(x);
// Shift and cut lower bits away. Cutting lower bits prevents potentially unexpected
// results of rounding by the GPU later in the pipeline when transforming to TrueColor
// the resulting subpixel value.
// $c \in [0,255] \cap \mathbb Z.$
// Multiplication is exact since it's just and increase of exponent by 8
float c=floor(byteShift*q);
return int(c);
}
// Input: any x acceptable to significand()
// Output: significand of x split to (8,8,8)-bit data vector
ivec3 significandAsIVec3(float x)
{
ivec3 result;
float sig=significand(x)/2.; // shift all bits to fractional part
result.x=part(sig,0);
result.y=part(sig,1);
result.z=part(sig,2);
return result;
}
// Input: any x such that !isnan(x)
// Output: IEEE 754 defined binary32 number, packed as ivec4(byte3,byte2,byte1,byte0)
ivec4 packIEEE754binary32(float x)
{
int e = biasedExp(x);
// sign to bit 7
int s = x<0. ? 128 : 0;
ivec4 binary32;
binary32.yzw=significandAsIVec3(x);
// clear the implicit integer bit of significand
if(binary32.y>=128) binary32.y-=128;
// put lowest bit of exponent into its position, replacing just cleared integer bit
binary32.y+=128*int(mod(float(e),2.));
// prepare high bits of exponent for fitting into their positions
e/=2;
// pack highest byte
binary32.x=e+s;
return binary32;
}
vec4 toColor(float x)
{
ivec4 binary32=packIEEE754binary32(x);
// Transform color components to [0,1] range.
// Division is inexact, but works reliably for all integers from 0 to 255 if
// the transformation to TrueColor by GPU uses rounding to nearest or upwards.
// The result will be multiplied by 255 back when transformed
// to TrueColor subpixel value by OpenGL.
return vec4(binary32)/255.;
}
Try -
$('#chkdwn2').change(function(){
if($(this).is(':checked'))
$('#dropdown').removeAttr('disabled');
else
$('#dropdown').attr("disabled","disabled");
})
The syntax is
pid_t waitpid(pid_t pid, int *statusPtr, int options);
1.where pid is the process of the child it should wait.
2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.
3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:
WNOHANG WUNTRACED WCONTINUED
If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.
benifits over wait
1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes
2.waitpid supports job control
3.it supports non blocking of the parent process
Disable safari bounce scrolling effect:
html,
body {
height: 100%;
width: 100%;
overflow: auto;
position: fixed;
}
In addition @Fredrik Mörk's great answer on strings, to add localization to a form do the following:
"Localizable"
to true
Language
property to the language you want (from a nice drop-down with them all in)Edit: This MSDN article on Localizing Windows Forms is not the original one I linked ... but might shed more light if needed. (the old one has been taken away)
I 2nd Chad Grant's answer and also submit this blog article [removed dead link] for your viewing pleasure.
Have you ever tried sylk?
We used to generate excelsheets in classic asp as sylk and right now we're searching for an excelgenerater too.
The advantages for sylk are, you can format the cells.
DECIMAL_DIG
from <float.h>
should give at least a reasonable approximation of that. Since that deals with decimal digits, and it's really stored in binary, you can probably store something a little larger without losing precision, but exactly how much is hard to say. I suppose you should be able to figure it out from FLT_RADIX
and DBL_MANT_DIG
, but I'm not sure I'd completely trust the result.
TimeSpan.FromTicks( 28000000000 ).TotalMinutes;
Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300
Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.
Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.
I've been trawling the net for an answer on how to select an option in a model dropdown and i've used this combination which has helped me out with Angular material.
element(by.model("ModelName")).click().element(By.xpath('xpathlocation')).click();
it appears that when throwing the code all in one line it could find the element in the dropdown.
Took a lot of time for this solution I hope that this helps someone out.
They should have added some kind of simple way to go from Date to Instant and also a method called toISO8601
, which is what a lot of people are looking for.
As a complement to other answers, from a java.util.Date to ISO 8601 format:
Instant.ofEpochMilli(date.getTime()).toString();
It is not really visible when using auto-completion but:
java.time.Instant.toString()
:
A string representation of this instant using ISO-8601
Maybe you can try to add android:layout_marginTop = "15dp" and android:layout_marginBottom = "15dp" in the outermost Layout
'Create Excel
Set objExcel = Wscript.CreateObject("Excel.Application")
objExcel.visible = True
Set objWb = objExcel.Workbooks.Add
objWb.Saveas("D:\Example.xlsx")
objExcel.Quit
I've made a mistake in the last my post. This is working example for how to pass additional argument in callback function:
function custom_func(p1,p2) {
$.post(AJAX_FILE_PATH,{op:'dosomething',p1:p1},
function(data){
return function(){
alert(data);
alert(p2);
}(data,p2)
}
);
return false;
}
You can always roll your own!
#include <stdio.h>
#include <string.h>
#include <math.h>
int my_atoi(const char* snum)
{
int idx, strIdx = 0, accum = 0, numIsNeg = 0;
const unsigned int NUMLEN = (int)strlen(snum);
/* Check if negative number and flag it. */
if(snum[0] == 0x2d)
numIsNeg = 1;
for(idx = NUMLEN - 1; idx >= 0; idx--)
{
/* Only process numbers from 0 through 9. */
if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
accum += (snum[strIdx] - 0x30) * pow(10, idx);
strIdx++;
}
/* Check flag to see if originally passed -ve number and convert result if so. */
if(!numIsNeg)
return accum;
else
return accum * -1;
}
int main()
{
/* Tests... */
printf("Returned number is: %d\n", my_atoi("34574"));
printf("Returned number is: %d\n", my_atoi("-23"));
return 0;
}
This will do what you want without clutter.
If you have McAfee HIPS and if you see the following error in event viewer application log:
The Module DLL C:\Windows\System32\inetsrv\HipIISEngineStub.dll failed to load.
The data is the error.
Then the following resolved the issue in my case: https://kc.mcafee.com/corporate/index?page=content&id=KB72677&actp=LIST
Quote from the page:
- Click Start, Run, type explorer and click OK.
- Navigate to: %windir%\system32\inetsrv\config
- Open the file applicationHost.config as Administrator for editing in Notepad.
Edit the <globalModules> section and remove the following line:
<add name="MfeEngine" image="%windir%\System32\inetsrv\HipIISEngineStub.dll" />Edit the <modules> section and remove the following line:
<add name="MfeEngine" />- After you have finished editing the applicationHost.config file, save the file, then restart the IIS server using iisreset or by restarting the system.
I had faced the same problem a few days ago.
I found the solution.
also, check the username and password.
The problem here is twofold
fgetc()
returns an int instead of a char.The first is easily fixed:
char *orig = code; // the beginning of the array
// ...
do {
*code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end
The second problem is more subtle -fgetc
returns an int so that the EOF
value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF
check and probably a regular while loop instead of do / while.
From the documentation:
Return date object with same year, month and day.
you should use action instead of actionListener:
<h:commandLink id="close" action="#{bean.close}" value="Close" immediate="true"
/>
and in close method you right something like:
public String close() {
return "index?faces-redirect=true";
}
where index is one of your pages(index.xhtml)
Of course, all this staff should be written in our original page, not in the intermediate.
And inside the close()
method you can use the parameters to dynamically choose where to redirect.
In theory: Child => an immediate descendant of an ancestor (e.g. Joe and his father)
Descendant => any element that is descended from a particular ancestor (e.g. Joe and his great-great-grand-father)
In practice: try this HTML:
<div class="one">
<span>Span 1.
<span>Span 2.</span>
</span>
</div>
<div class="two">
<span>Span 1.
<span>Span 2.</span>
</span>
</div>
with this CSS:
span { color: red; }
div.one span { color: blue; }
div.two > span { color: green; }
my solution only works for the next cases: if you are mistaking a multidimensaional array into a single one
$json = file_get_contents('url_json'); //get the json
$objhigher=json_decode($json); //converts to an object
$objlower = $objhigher[0]; // if the json response its multidimensional this lowers it
echo "<pre>"; //box for code
print_r($objlower); //prints the object with all key and values
echo $objlower->access_token; //prints the variable
i know that the answer was has already been answered but for those who came here looking for something i hope this can help you
A control or window object in Windows Forms is just a wrapper around a Win32 window identified by a handle (sometimes called HWND). Most things you do with the control will eventually result in a Win32 API call that uses this handle. The handle is owned by the thread that created it (typically the main thread), and shouldn't be manipulated by another thread. If for some reason you need to do something with the control from another thread, you can use Invoke
to ask the main thread to do it on your behalf.
For instance, if you want to change the text of a label from a worker thread, you can do something like this:
theLabel.Invoke(new Action(() => theLabel.Text = "hello world from worker thread!"));
my solution:
MOVE:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
COPY:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.
Check out the Managed Operating System Alliance (MOSA) Project at www.mosa-project.org. They are designing an AOT/JIT compiler and fully managed operating system in C#. Some of the developers are from the inactive SharpOS project.
I copy-pasted the whole pdf in a text editor and got something like:
...
31 Netherlands (Kingdom of the)
32 Belgium
33 France
34 Spain
350 Gibraltar
351 Portugal
352 Luxembourg
353 Ireland
354 Iceland
...
You could easily parse this to create a xml :)
For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.
Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)
anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved statically, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:
class animal {
public void makeRumor(){
print("thump");
}
}
class dog extends animal {
public void makeRumor(){
print("woff");
}
}
animal a = new dog();
dog b = new dog();
a.makeRumor() -> prints thump
b.makeRumor() -> prints woff
(supposing that makeRumor is NOT virtual)
java doesn't truly offer this level of polymorphism (called also object slicing).
animal a = new dog(); dog b = new dog();
a.makeRumor() -> prints thump
b.makeRumor() -> prints woff
on both case it will only print woff.. since a and b is refering to class dog
If you have them already in a byte[] array, you can use:
int result = ByteBuffer.wrap(bytes).getInt();
source: here
namespace TestCSharp2
{
**public** class Class2
{
int i;
public void setValue(int i)
{
this.i = i;
}
public int getValue()
{
return this.i;
}
}
}
Add the 'Public' declaration before 'class Class2'.
Extracting a specific folder (directory) within war file:
# unzip <war file> '<folder to extract/*>' -d <destination path>
unzip app##123.war 'some-dir/*' -d extracted/
You get ./extracted/some-dir/
as a result.
in your xml file you should set layout_width and layout_height from wrap_content to match_parent. it's fixed for me.
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
If you don't mind importing the json
module, then the best way to handle it is through json.JSONDecodeError
(or json.decoder.JSONDecodeError
as they are the same) as using default errors like ValueError
could catch also other exceptions not necessarily connected to the json decode one.
from json.decoder import JSONDecodeError
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
# do whatever you want
//EDIT (Oct 2020):
As @Jacob Lee noted in the comment, there could be the basic common TypeError
raised when the JSON object is not a str
, bytes
, or bytearray
. Your question is about JSONDecodeError
, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:
from json.decoder import JSONDecodeError
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
# do whatever you want
except TypeError as e:
# do whatever you want in this case
leak prone
I've decided to chime in. The performance impact includes: disk operation + unzip (for jar), class verification, perm-gen space (for Sun's Hotspot JVM). However, worst of all: it's leak prone. You can't simply return.
Set<String> getFlavors(){
return Collections.unmodifiableSet(flavors)
}
So if the set escapes to any other part loaded by a different classloader and a reference is kept there, the entire tree of classes+classloader will be leaked. To avoid that, a copy to HashMap is necessary, new LinkedHashSet(new ArrayList(){{add("xxx);add("yyy");}})
. Not so cute any more.
I don't use the idiom, myself, instead it is like new LinkedHashSet(Arrays.asList("xxx","YYY"));
for ex.
<input b="demo">
And
(input[@b='demo'])[1]
Two issues:
You're passing the jQuery wrapper of the element into parseInt
, which isn't what you want, as parseInt
will call toString
on it and get back "[object Object]"
. You need to use val
or text
or something (depending on what the element is) to get the string you want.
You're not telling parseInt
what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt
guesses which radix to use.
Fix if the element is a form field:
// vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Fix if the element is something else and you want to use the text within it:
// vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Try this:
if(Math.floor(id) == id && $.isNumeric(id))
alert('yes its an int!');
$.isNumeric(id)
checks whether it's numeric or not
Math.floor(id) == id
will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.
One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.
Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images"
Set your Image source like this:
<Image Source={Binding {x:Static UI:Resources.Search}} />
where 'Search' is name of the resource.
The version you have specified, or one of your dependencies has specified is not published to npmjs.com
Executing npm view ionic-native
(see docs) the following output is returned for package versions:
versions:
[ '1.0.7',
'1.0.8',
'1.0.9',
'1.0.10',
'1.0.11',
'1.0.12',
'1.1.0',
'1.1.1',
'1.2.0',
'1.2.1',
'1.2.2',
'1.2.3',
'1.2.4',
'1.3.0',
'1.3.1',
'1.3.2',
'1.3.3',
'1.3.4',
'1.3.5',
'1.3.6',
'1.3.7',
'1.3.8',
'1.3.9',
'1.3.10',
'1.3.11',
'1.3.12',
'1.3.13',
'1.3.14',
'1.3.15',
'1.3.16',
'1.3.17',
'1.3.18',
'1.3.19',
'1.3.20',
'1.3.21',
'1.3.22',
'1.3.23',
'1.3.24',
'1.3.25',
'1.3.26',
'1.3.27',
'2.0.0',
'2.0.1',
'2.0.2',
'2.0.3',
'2.1.2',
'2.1.3',
'2.1.4',
'2.1.5',
'2.1.6',
'2.1.7',
'2.1.8',
'2.1.9',
'2.2.0',
'2.2.1',
'2.2.2',
'2.2.3',
'2.2.4',
'2.2.5',
'2.2.6',
'2.2.7',
'2.2.8',
'2.2.9',
'2.2.10',
'2.2.11',
'2.2.12',
'2.2.13',
'2.2.14',
'2.2.15',
'2.2.16',
'2.2.17',
'2.3.0',
'2.3.1',
'2.3.2',
'2.4.0',
'2.4.1',
'2.5.0',
'2.5.1',
'2.6.0',
'2.7.0',
'2.8.0',
'2.8.1',
'2.9.0' ],
As you can see no version higher than 2.9.0
has been published to the npm repository. Strangely they have versions higher than this on GitHub. I would suggest opening an issue with the maintainers on this.
For now you can manually install the package via the tarball URL of the required release:
npm install https://github.com/ionic-team/ionic-native/tarball/v3.5.0
I had this problem today. It had nothing to do with any of the posted answers. I tried them all. My problem was a misconfiguration with the zaptel.conf (running old asterisk!). I had commented out some span details trying to troubleshoot a PRI issue. When the server got rebooted this issue presented itself. I was able to discover this by looking at the wanrouter messages in the logs. I noticed there were 3 errors, and the corresponding line numbers, once I corrected these issues, and ran an #asterisk -vvvvc
the server came back up and everything worked.
I'm using:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", DEFAULT_NAMESPACE);
using (var stream = new MemoryStream())
{
var someone = new Person
{
FirstName = "Donald",
LastName = "Duck"
};
serializer.Serialize(stream, someone, namespaces);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
To get the following XML:
<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
<FirstName>Donald</FirstName>
<LastName>Duck</LastName>
</Person>
If you don't want the namespace, just set DEFAULT_NAMESPACE to "".
Reflection is your friend, as has been pointed out. But you need to use the correct method;
Assembly.GetEntryAssembly() //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly() // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t ) // gives you the assembly in which the specified type is defined.
The system might be running "rootless". Try to set the firmware nvram variable boot-args to "rootless=0". Try to run set of commands:
sudo nvram boot-args="rootless=0";
sudo reboot
After reboot completes, run:
sudo gem install bundler
T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.
CREATE PROCEDURE SP1 AS
EXEC SP2
PRINT 'Done'
Both classes Rectangle and Ellipse need to override both of the abstract methods.
To work around this, you have 3 options:
Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:
abstract class Shape {
// ...
void draw(Graphics g);
}
And
class Rectangle extends Shape {
void draw(Graphics g) {
// ...
}
}
Finally
class Ellipse extends Shape {
void draw(Graphics g) {
// ...
}
}
And you can switch in between them, like so:
Shape shape = new Ellipse();
shape.draw(/* ... */);
shape = new Rectangle();
shape.draw(/* ... */);
Again, just an example.
As these guys said, just change input type.
But do not forget to change type back as well.
See my simple jquery demo: http://jsfiddle.net/kPJbU/1/
HTML:
<input name="password" class="password" type="password" />
<div class="icon">icon</div>
jQuery:
$('.icon').hover(function () {
$('.password').attr('type', 'text');
}, function () {
$('.password').attr('type', 'password');
});
Yes. You need to stringify
the JSON
data orlse 400 bad request
error occurs as it cannot identify the data.
400 Bad Request
Bad Request. Your browser sent a request that this server could not understand.
Plus you need to add content type
and datatype
as well. If not you will encounter 415
error which says Unsupported Media Type
.
415 Unsupported Media Type
Try this.
var newData = {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
};
var dataJson = JSON.stringify(newData);
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: dataJson,
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.
subprocess.call
Automatically waits , you can also use:
p1.wait()
I'm very late to the party here, but if you use an IDE like PyCharm, there's an option in 'Edit Configurations' under the 'Run' menu (Run > Edit Configurations) where you can specify a default port. This of course is relevant only if you are debugging/testing through PyCharm.
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
<video autoplay muted="muted" loop id="myVideo">
<source src="https://w.r.glob.net/Coastline-3581.mp4" type="video/mp4">
</video>
Something like this
Here is the Swift 4 version.
import Foundation
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
var tableView: UITableView = UITableView()
let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
override func viewDidLoad()
{
super.viewDidLoad()
tableView.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return animals.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = animals[indexPath.row]
return cell
}
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
{
print("You tapped cell number \(indexPath.row).")
}
}
Instead of rand()
, use newid()
, which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid())
can produce -2,147,483,648 and cause integer overflow on abs()
, so we need to use modulo on the checksum return value before converting it to absolute value.
UPDATE CattleProds
SET SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE SheepTherapy IS NULL
This generates a random number between 0 and 9999.
Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:
String to match: "my word"
String to search: "I'm searching for my funny words inside this text"
You need the following regex: /^(?=.*my)(?=.*word).*$/im
Explaining:
^ assert position at start of a line
?= Positive Lookahead
.* matches any character (except newline)
() Groups
$ assert position at end of a line
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
Test the Regex here: https://regex101.com/r/iS5jJ3/1
So, you can create a javascript function that:
Example:
function fullTextCompare(myWords, toMatch){_x000D_
//Replace regex reserved characters_x000D_
myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
//Split your string at spaces_x000D_
arrWords = myWords.split(" ");_x000D_
//Encapsulate your words inside regex groups_x000D_
arrWords = arrWords.map(function( n ) {_x000D_
return ["(?=.*"+n+")"];_x000D_
});_x000D_
//Create a regex pattern_x000D_
sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
//Execute the regex match_x000D_
return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec
Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec
, as I have ~/bin
in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...
Launch it from the root of your project, where you can see src and target dirs.
The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)
$ mvnexec
1) org.jmeld.ui.JMeldComponent
2) org.jmeld.ui.text.FileDocument
3) org.jmeld.JMeld
4) org.jmeld.util.UIDefaultsPrint
5) org.jmeld.util.PrintProperties
6) org.jmeld.util.file.DirectoryDiff
7) org.jmeld.util.file.VersionControlDiff
8) org.jmeld.vc.svn.InfoCmd
9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#?
If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P
)
By default it compiles project every run. but you can avoid that using mvnexec -B
It allows to search only in test classes -M
or --no-main
, or only in main classes -T
or --no-test
. also has a filter by name option -f <whatever>
Hope this could save you some time, for me it does.
This thread is old, but to chime in for Xcode Version 8.3.3, Tyler Crompton's method in the accepted answer still works (some of the names are very slightly different, but not enough to matter).
2 points where I struggled slightly:
Step 16: If the python executable you want is greyed out, right click it and select quick look. Then close the quick look window, and it should now be selectable.
Step 19: If this isn’t working for you, you can enter the name of just the python file in the Arguments tab, and then enter the project root directory explicitly in the Options tab under Working Directory--check the “Use custom working directory” box, and type in your project root directory in the field below it.
You can use the "export" solution just like what other guys have suggested. I'd like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.
Firstly, you need to download a small tool named gost
: https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).
Then you need to run the commands below to unpack it :
$ cd /path/to/your/download/directory
$ tar -xvf gost_linux_amd64.tar.gz
You would get an executable gost
. You can move it to /usr/local/bin
for convenient use:
$ sudo mv gost /usr/local/bin
Run the command below to add the path you want to use as GOPATH into the pathspace gost
maintains. It is required to give the path a name which you would use later.
$ gost add foo /home/foobar/bar # 'foo' is the name and '/home/foobar/bar' is the path
Run any Go command you want in the format:
gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]
For example, you want to run go get github.com/go-sql-driver/mysql
with /home/foobar/bar
as the GOPATH, just do it as below:
$ gost get -p foo -- github.com/go-sql-driver/mysql # 'foo' is the name you give to the path above.
It would help you to set the GOPATH and run the command. But remember that you have added the path into gost
's pathspace. If you are under any level of subdirectories of /home/foobar/bar
, you can even just run the command below which would do the same thing for short :
$ gost get -- github.com/go-sql-driver/mysql
gost
is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName
. For example you want to know more about install
, just type words below in:
$ gost help install
You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md
Following work for me:
Keep following setting blank if you have made in build.gradle.
signingConfigs {
release {
storePassword ""
keyAlias ""
keyPassword ""
}
}
and choose Gradle Task from your Editor window. It will show list of all flavor if you have created.
Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:
df['column_name'].astype(np.float).astype("Int32")
NB: You have to go through numpy float first and then to nullable Int32, for some reason.
The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.
You might want to check https://github.com/Thor1Khan/mongo.git it uses a minimal workaround the 32 bit atomic operations on 64 bits operands (could use assembly but it doesn't seem to be mandatory here) Only digital bugs were harmed before committing
Inside a controller:
$request = $this->getRequest();
$username = $request->get('username');
{{ HTML::style('yourcss.css') }}
{{ HTML::script('yourjs.js') }}
You need to git add my_project
to stage your new folder. Then git add my_project/*
to stage its contents. Then commit what you've staged using git commit
and finally push your changes back to the source using git push origin master
(I'm assuming you wish to push to the master branch).
Also worth checking is if there are any errors in the return type of your interface methods. I could reproduce this issue by having an unintended return type like Call<Call<ResponseBody>>
NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
delete the assemeblyinfo.cs file from project under properties menu and rebulid it.
Add HttpModule
and HttpClientModule
in both imports and providers in app.module.ts solved the issue.
imports -> import {HttpModule} from "@angular/http";
import {HttpClientModule} from "@angular/common/http";
Use '
for a straight apostrophe. This tends to be more readable than the numeric '
(if others are ever likely to read the HTML directly).
Edit: msanders points out that '
isn't valid HTML4, which I didn't know, so follow most other answers and use '
.
I think this is what we like to do very much.
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
If you already created a user and assigned to that database before by doing
USE [yourDB]
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo]
GO
then kindly delete it by doing below and follow the steps
USE yourDB;
GO
DROP USER newlogin;
GO
For more information please follow the links:
Hiding databases for a login on Microsoft Sql Server 2008R2 and above
I had the similar issue with one of the search field in my form. neither autocomplete= "false"
nor autocomplete= "off"
worked for me. turns out when you have aria-label attribute in the input
element is set to something like city
or address
or something similar , chrome overrides all your settings and display the autocomplete anyway
So fix i have done is to remove the city
part from the aria-label and come up with a different value. and finally autocomplete stopped showing
Something else that was not obvious, to me at least, was that the when using Mongoose's third parameter to avoid replacing the actual collection with a new one with the same name, the new Schema(...)
is actually only a placeholder, and doesn't interfere with the exisitng schema so
var User = mongoose.model('User', new Schema({ url: String, text: String, id: Number}, { collection : 'users' })); // collection name;
User.find({}, function(err, data) { console.log(err, data, data.length);});
works fine and returns all fields - even if the actual (remote) Schema contains none of these fields. Mongoose will still want it as new Schema(...)
, and a variable almost certainly won't hack it.
$fp = fopen("$address",'w+');
if(!$fp)
echo 'not Open';
//-----------------------------------
while(!feof($fp))
{
fputs($fp,' ',999);
}
fclose($fp);
JavaScript does not have a built-in map/hashmap. It should be called an associative array.
hash["X"]
is equal to hash.X
, but it allows "X" as a string variable.
In other words, hash[x]
is functionally equal to eval("hash."+x.toString())
.
It is more similar to object.properties rather than key-value mapping. If you are looking for a better key/value mapping in JavaScript, please use the Map object.
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
Try this:
foreach($samplearr as $key => $item){
print "<tr><td>"
. $key
. "</td><td>"
. $item['value1']
. "</td><td>"
. $item['value2']
. "</td></tr>";
}
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
If you have a large number of images, look into a Bloom filter, which uses multiple hashes for a probablistic but efficient result. If the number of images is not huge, then a cryptographic hash like md5 should be sufficient.
Based on @ionden's answer, the call to the delegate could be simplified using null propagation since C# 6.0.
Your code would simply be:
class MyClass {
public event EventHandler MyEvent;
public void Method() {
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
Use it like this:
MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();
You can try this:
var driveName = "C:\\";
var freeSpace = DriveInfo.GetDrives().Where(x => x.Name == driveName && x.IsReady).FirstOrDefault().TotalFreeSpace;
Good luck
Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.
Add the server(tomcat) from Right click on the Project and select the "Properties" go to "Project Factes" "Runtime tab" other wise "Target Runtime"
if it is maven pom.xml issue, try added this to the pom.xml
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
it will solve the issue.
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
As documented here: http://api.jquery.com/height/
Line-based execution
While not a clear benefit in most cases, it can help when trying to update things while they are running. For example:
UpdateSource.bat
copy UpdateSource.bat Current.bat
echo "Hi!"
Current.bat
copy UpdateSource.bat Current.bat
Now, executing Current.bat produces this output.
HI!
Watch out though, the batch execution proceeds by line number. An update like this could end up skipping or moving back a line if the essential lines don't have exactly the same line numbers.
SELECT * FROM table ORDER BY Id DESC LIMIT 1
You have here available an example of DNS Caching in Debian using dnsmasq.
Configuration summary:
# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"
# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888
nameserver 127.0.0.1
Then just restart dnsmasq.
Benchmark test using DNS 1.1.1.1:
for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
Benchmark test using you local cached DNS:
for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
You can set height to -webkit-fill-available
<!-- Maps Container -->
<div id="map_canvas" style="height:-webkit-fill-available;width:100px;"></div>
I saw the same error after using msdeploy to copy the application to a new server. It turned out that the bindings were still using the IP address from the previous server. So, double check IP address in the IIS bindings. (Seems obvious after the fact, but did not immediately occur to me to check it).
t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")
The docs explicitly says that java.sql.Date
will throw:
IllegalArgumentException
- if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d
)
Also you shouldn't need to convert a date to a String
then to a sql.date
, this seems superfluous (and bug-prone!). Instead you could:
java.sql.Date sqlDate := new java.sql.Date(now.getTime());
prs.setDate(2, sqlDate);
prs.setDate(3, sqlDate);
Try this, working fine -
$array = json_decode(json_encode($array), true);
You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?
this.Controls.Add(dataGridView1);
By the way the code is a bit confused
String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql = "SELECT Clients FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
conn.Open();
DataSet ds = new DataSet();
DataGridView dataGridView1 = new DataGridView();
using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
// Of course, before addint the datagrid to the hosting form you need to
// set position, location and other useful properties.
// Why don't you create the DataGrid with the designer and use that instance instead?
this.Controls.Add(dataGridView1);
}
}
EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as
SELECT field_names_list FROM _tablename_
so the correct syntax to use for retrieving all the clients data is
string sql = "SELECT * FROM Clients";
where the *
means -> all the fields present in the table
Try switching to a LinearLayout
instead of RelativeLayout
. I was targeting the 3.0 Honeycomb api when testing.
public class FragmentDialog extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.show);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
DialogFragment newFragment = MyDialogFragment.newInstance();
newFragment.show(ft, "dialog");
}
public static class MyDialogFragment extends DialogFragment {
static MyDialogFragment newInstance() {
MyDialogFragment f = new MyDialogFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
return v;
}
}
}
and the layouts: fragment_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="1000dp"
android:minHeight="1000dp">
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff">
<Button android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="show">
</Button>
</LinearLayout>
You don't need jquery for this, in plain javascript, the following will work!
var intervalId = window.setInterval(function(){
/// call your function here
}, 5000);
To stop the loop you can use
clearInterval(intervalId)
First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.
select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable
Use:
ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);
Changing Command Execute Timeout in Management Studio:
Click on Tools -> Options
Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.
Changing Command Timeout in Server:
In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.
Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property
Remote query timeout (in seconds, 0 = no timeout):
[up/down control]
you can set the value in up/down control.
You can use whereIn
which accepts an array as second paramter.
DB:table('table')
->whereIn('column', [value, value, value])
->get()
You can chain where multiple times.
DB:table('table')->where('column', 'operator', 'value')
->where('column', 'operator', 'value')
->where('column', 'operator', 'value')
->get();
This will use AND
operator. if you need OR
you can use orWhere
method.
For advanced where
statements
DB::table('table')
->where('column', 'operator', 'value')
->orWhere(function($query)
{
$query->where('column', 'operator', 'value')
->where('column', 'operator', 'value');
})
->get();
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
Hey now you can give to body background image
and set the background-position:center center;
as like this
body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}
You can use LineNumberReader instead of BufferedReader. Go through the api. You can find setLineNumber and getLineNumber methods.
If your data has changed every once,you will notice dont tracing the table.for example some table update id ([key]) using tigger.If you tracing ,you will get same id and get the issue.
This is something that worked for me, although it smells a bit wrong:
var iframe = ...
var doc = iframe.contentDocument;
var i = doc.createElement('input');
i.style.display = 'none';
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);
hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.
You need to use a link function in your directive:
link: function(scope, element, attrs) {
element.on('click', function() {
$window.history.back();
});
}
See jsFiddle.
Possibly a little bit of a necromancing post here, but...
here's a function that follows up to 10 redirects, and detects infinite redirect loops. also parses result into JSON
Note - uses a callback helper (shown at the end of this post)
( TLDR; full working demo in context here or remixed-version here)
function getJSON(url,cb){
var callback=errBack(cb);
//var callback=errBack(cb,undefined,false);//replace previous line with this to turn off logging
if (typeof url!=='string') {
return callback.error("getJSON:expecting url as string");
}
if (typeof cb!=='function') {
return callback.error("getJSON:expecting cb as function");
}
var redirs = [url],
fetch = function(u){
callback.info("hitting:"+u);
https.get(u, function(res){
var body = [];
callback.info({statusCode:res.statusCode});
if ([301,302].indexOf(res.statusCode)>=0) {
if (redirs.length>10) {
return callback.error("excessive 301/302 redirects detected");
} else {
if (redirs.indexOf(res.headers.location)<0) {
redirs.push(res.headers.location);
return fetch(res.headers.location);
} else {
return callback.error("301/302 redirect loop detected");
}
}
} else {
res.on('data', function(chunk){
body.push(chunk);
callback.info({onData:{chunkSize:chunk.length,chunks:body.length}});
});
res.on('end', function(){
try {
// convert to a single buffer
var json = Buffer.concat(body);
console.info({onEnd:{chunks:body.length,bodyLength:body.length}});
// parse the buffer as json
return callback.result(JSON.parse(json),json);
} catch (err) {
console.error("exception in getJSON.fetch:",err.message||err);
if (json.length>32) {
console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
} else {
console.error("json==>|"+json.toString('utf-8')+"|<=== json");
}
return callback.error(err,undefined,json);
}
});
}
});
};
fetch(url);
}
Note - uses a callback helper (shown below)
you can paste this into the node console and it should run as is.
( or for full working demo in context see here )
var
fs = require('fs'),
https = require('https');
function errBack (cb,THIS,logger) {
var
self,
EB=function(fn,r,e){
if (logger===false) {
fn.log=fn.info=fn.warn=fn.errlog=function(){};
} else {
fn.log = logger?logger.log : console.log.bind(console);
fn.info = logger?logger.info : console.info.bind(console);
fn.warn = logger?logger.warn : console.warn.bind(console);
fn.errlog = logger?logger.error : console.error.bind(console);
}
fn.result=r;
fn.error=e;
return (self=fn);
};
if (typeof cb==='function') {
return EB(
logger===false // optimization when not logging - don't log errors
? function(err){
if (err) {
cb (err);
return true;
}
return false;
}
: function(err){
if (err) {
self.errlog(err);
cb (err);
return true;
}
return false;
},
function () {
return cb.apply (THIS,Array.prototype.concat.apply([undefined],arguments));
},
function (err) {
return cb.apply (THIS,Array.prototype.concat.apply([typeof err==='string'?new Error(err):err],arguments));
}
);
} else {
return EB(
function(err){
if (err) {
if (typeof err ==='object' && err instanceof Error) {
throw err;
} else {
throw new Error(err);
}
return true;//redundant due to throw, but anyway.
}
return false;
},
logger===false
? self.log //optimization :resolves to noop when logger==false
: function () {
self.info("ignoring returned arguments:",Array.prototype.concat.apply([],arguments));
},
function (err) {
throw typeof err==='string'?new Error(err):err;
}
);
}
}
function getJSON(url,cb){
var callback=errBack(cb);
if (typeof url!=='string') {
return callback.error("getJSON:expecting url as string");
}
if (typeof cb!=='function') {
return callback.error("getJSON:expecting cb as function");
}
var redirs = [url],
fetch = function(u){
callback.info("hitting:"+u);
https.get(u, function(res){
var body = [];
callback.info({statusCode:res.statusCode});
if ([301,302].indexOf(res.statusCode)>=0) {
if (redirs.length>10) {
return callback.error("excessive 302 redirects detected");
} else {
if (redirs.indexOf(res.headers.location)<0) {
redirs.push(res.headers.location);
return fetch(res.headers.location);
} else {
return callback.error("302 redirect loop detected");
}
}
} else {
res.on('data', function(chunk){
body.push(chunk);
console.info({onData:{chunkSize:chunk.length,chunks:body.length}});
});
res.on('end', function(){
try {
// convert to a single buffer
var json = Buffer.concat(body);
callback.info({onEnd:{chunks:body.length,bodyLength:body.length}});
// parse the buffer as json
return callback.result(JSON.parse(json),json);
} catch (err) {
// read with "bypass refetch" option
console.error("exception in getJSON.fetch:",err.message||err);
if (json.length>32) {
console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
} else {
console.error("json==>|"+json.toString('utf-8')+"|<=== json");
}
return callback.error(err,undefined,json);
}
});
}
});
};
fetch(url);
}
var TLDs,TLDs_fallback = "com.org.tech.net.biz.info.code.ac.ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.st.su.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.uk.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.za.zm.zw".split(".");
var TLD_url = "https://gitcdn.xyz/repo/umpirsky/tld-list/master/data/en/tld.json";
var TLD_cache = "./tld.json";
var TLD_refresh_msec = 15 * 24 * 60 * 60 * 1000;
var TLD_last_msec;
var TLD_default_filter=function(dom){return dom.substr(0,3)!="xn-"};
function getTLDs(cb,filter_func){
if (typeof cb!=='function') return TLDs;
var
read,fetch,
CB_WRAP=function(tlds){
return cb(
filter_func===false
? cb(tlds)
: tlds.filter(
typeof filter_func==='function'
? filter_func
: TLD_default_filter)
);
},
check_mtime = function(mtime) {
if (Date.now()-mtime > TLD_refresh_msec) {
return fetch();
}
if (TLDs) return CB_WRAP (TLDs);
return read();
};
fetch = function(){
getJSON(TLD_url,function(err,data){
if (err) {
console.log("exception in getTLDs.fetch:",err.message||err);
return read(true);
} else {
TLDs=Object.keys(data);
fs.writeFile(TLD_cache,JSON.stringify(TLDs),function(err){
if (err) {
// ignore save error, we have the data
CB_WRAP(TLDs);
} else {
// get mmtime for the file we just made
fs.stat(TLD_cache,function(err,stats){
if (!err && stats) {
TLD_last_msec = stats.mtimeMs;
}
CB_WRAP(TLDs);
});
}
});
}
});
};
read=function(bypassFetch) {
fs.readFile(TLD_cache,'utf-8',function(err,json){
try {
if (err) {
if (bypassFetch) {
// after a http errror, we fallback to hardcoded basic list of tlds
// if the disk file is not readable
console.log("exception in getTLDs.read.bypassFetch:",err.messsage||err);
throw err;
}
// if the disk read failed, get the data from the CDN server instead
return fetch();
}
TLDs=JSON.parse(json);
if (bypassFetch) {
// we need to update stats here as fetch called us directly
// instead of being called by check_mtime
return fs.stat(TLD_cache,function(err,stats){
if (err) return fetch();
TLD_last_msec =stats.mtimeMs;
return CB_WRAP(TLDs);
});
}
} catch (e){
// after JSON error, if we aren't in an http fail situation, refetch from cdn server
if (!bypassFetch) {
return fetch();
}
// after a http,disk,or json parse error, we fallback to hardcoded basic list of tlds
console.log("exception in getTLDs.read:",err.messsage||err);
TLDs=TLDs_fallback;
}
return CB_WRAP(TLDs);
});
};
if (TLD_last_msec) {
return check_mtime(TLD_last_msec);
} else {
fs.stat(TLD_cache,function(err,stats){
if (err) return fetch();
TLD_last_msec =stats.mtimeMs;
return check_mtime(TLD_last_msec);
});
}
}
getTLDs(console.log.bind(console));
This warning is useful for programmers that would mistakenly write 'test'
where they should have written "test"
.
This happen much more often than programmers that do actually want multi-char int constants.
based on https://stackoverflow.com/a/19494006/1815624 and desire to make it happen...
updated idea
combining answers from
Relevant code:
if (heightDifference > (usableHeightSansKeyboard / 4)) {
// keyboard probably just became visible
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
} else {
// keyboard probably just became hidden
if(usableHeightPrevious != 0) {
frameLayoutParams.height = usableHeightSansKeyboard;
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Full Source at https://github.com/CrandellWS/AndroidBug5497Workaround/blob/master/AndroidBug5497Workaround.java
Create a static value of the containers height before opening the keyboard
Set the container height based on usableHeightSansKeyboard - heightDifference
when the keyboard opens and set it back to the saved value when it closes
if (heightDifference > (usableHeightSansKeyboard / 4)) {
// keyboard probably just became visible
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
int mStatusHeight = getStatusBarHeight();
frameLayoutParams.topMargin = mStatusHeight;
((MainActivity)activity).setMyMainHeight(usableHeightSansKeyboard - heightDifference);
if(BuildConfig.DEBUG){
Log.v("aBug5497", "keyboard probably just became visible");
}
} else {
// keyboard probably just became hidden
if(usableHeightPrevious != 0) {
frameLayoutParams.height = usableHeightSansKeyboard;
((MainActivity)activity).setMyMainHeight();
}
frameLayoutParams.topMargin = 0;
if(BuildConfig.DEBUG){
Log.v("aBug5497", "keyboard probably just became hidden");
}
}
Methods in MainActivity
public void setMyMainHeight(final int myMainHeight) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ConstraintLayout.LayoutParams rLparams = (ConstraintLayout.LayoutParams) myContainer.getLayoutParams();
rLparams.height = myMainHeight;
myContainer.setLayoutParams(rLparams);
}
});
}
int mainHeight = 0;
public void setMyMainHeight() {
runOnUiThread(new Runnable() {
@Override
public void run() {
ConstraintLayout.LayoutParams rLparams = (ConstraintLayout.LayoutParams) myContainer.getLayoutParams();
rLparams.height = mainHeight;
myContainer.setLayoutParams(rLparams);
}
});
}
Example Container XML
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.constraint.ConstraintLayout
android:id="@+id/my_container"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintHeight_percent=".8">
similarly margins can be added if needed...
Another consideration is use padding an example of this can be found at:
https://github.com/mikepenz/MaterialDrawer/issues/95#issuecomment-80519589
git log
+ git branch
will find it for you:
% git log --all -- somefile
commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date: Tue Dec 16 14:16:22 2008 -0800
added somefile
% git branch -a --contains 55d2069
otherbranch
Supports globbing, too:
% git log --all -- '**/my_file.png'
The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find
).
You can user either
.your-class{
position:absolute;
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
}
or
.your-class{
position:absolute;
transform: rotate(360deg) scaleX(-1);
}
Notice that setting position
to absolute
is very important! If you won't set it, you will need to set display: inline-block;
This might work for you:
cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx
The difference between the project operator (p) in relational algebra and the SELECT keyword in SQL is that if the resulting table/set has more than one occurrences of the same tuple, then p will return only one of them, while SQL SELECT will return all.
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8)
and (int)(1.2)
, which will both "round down" towards 0 and return 1
), simply add 0.5 to the double
that you will typecast to an int
.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1
and y = 1
):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1
and y = 2
):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double
is rounded up or down upon (int)
typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1
whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double
immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int)
typecasting, but 10.23 and 10.7 will be rounded up to 11.
You can edit
/vendor/twig/twig/lib/Twig/Extension/Debug.php
and change the var_dump()
functions to \Doctrine\Common\Util\Debug::dump()
From the documentation:
Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.
The expression
x if C else y
first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.See PEP 308 for more details about conditional expressions.
New since version 2.5.
Try this, it's working for me:
box-shadow: -5px 0 5px -5px #333, 5px 0 5px -5px #333;
Here is my trick:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Main.<String> getClazz());
}
static <T> Class getClazz(T... param) {
return param.getClass().getComponentType();
}
}
The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.
You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.
\1
in double quotes needs to be escaped. So you want either
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1")
or
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, '\1')
see the docs on gsub where it says "If it is a double-quoted string, both back-references must be preceded by an additional backslash."
That being said, if you just want the result of the match you can do:
"Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)
or
"Z_sdsd: sdsd"[/^Z_.*(?=:)/]
Note that the (?=:)
is a non-capturing group so that the :
doesn't show up in your match.
This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?
d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()
At the end of your for() loop, you can use the savefig()
function instead of plt.show() and set the name, dpi and format of your figure.
E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder ./ with names 'Sample1.eps', 'Sample2.eps', etc. you can just add the following code:
for fname in glob("./*.txt"):
# Your previous code goes here
[...]
plt.savefig("./{}.eps".format(fname), bbox_inches='tight', format='eps', dpi=1000)
Just leave it empty: 'default_charset' in WHM :::::: default_charset =''
p.s. - In WHM go --------) Home »Service Configuration »PHP Configuration Editor ----) click 'Advanced Mode' ----) find 'default_charset' and leave it blank ---- just nothing, not utf8, not ISO
As pointed by this the best way to obtain a concurrency-able HashSet is by means of Collections.synchronizedSet()
Set s = Collections.synchronizedSet(new HashSet(...));
This worked for me and I haven't seen anybody really pointing to it.
EDIT This is less efficient than the currently aproved solution, as Eugene points out, since it just wraps your set into a synchronized decorator, while a ConcurrentHashMap
actually implements low-level concurrency and it can back your Set just as fine. So thanks to Mr. Stepanenkov for making that clear.
http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedSet-java.util.Set-
Updated for Swift 4
Swift ranges are more complex than NSRange
, and they didn't get any easier in Swift 3. If you want to try to understand the reasoning behind some of this complexity, read this and this. I'll just show you how to create them and when you might use them.
a...b
This range operator creates a Swift range which includes both element a
and element b
, even if b
is the maximum possible value for a type (like Int.max
). There are two different types of closed ranges: ClosedRange
and CountableClosedRange
.
ClosedRange
The elements of all ranges in Swift are comparable (ie, they conform to the Comparable protocol). That allows you to access the elements in the range from a collection. Here is an example:
let myRange: ClosedRange = 1...3
let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]
However, a ClosedRange
is not countable (ie, it does not conform to the Sequence protocol). That means you can't iterate over the elements with a for
loop. For that you need the CountableClosedRange
.
CountableClosedRange
This is similar to the last one except now the range can also be iterated over.
let myRange: CountableClosedRange = 1...3
let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]
for index in myRange {
print(myArray[index])
}
a..<b
This range operator includes element a
but not element b
. Like above, there are two different types of half-open ranges: Range
and CountableRange
.
Range
As with ClosedRange
, you can access the elements of a collection with a Range
. Example:
let myRange: Range = 1..<3
let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]
Again, though, you cannot iterate over a Range
because it is only comparable, not stridable.
CountableRange
A CountableRange
allows iteration.
let myRange: CountableRange = 1..<3
let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]
for index in myRange {
print(myArray[index])
}
You can (must) still use NSRange
at times in Swift (when making attributed strings, for example), so it is helpful to know how to make one.
let myNSRange = NSRange(location: 3, length: 2)
Note that this is location and length, not start index and end index. The example here is similar in meaning to the Swift range 3..<5
. However, since the types are different, they are not interchangeable.
The ...
and ..<
range operators are a shorthand way of creating ranges. For example:
let myRange = 1..<3
The long hand way to create the same range would be
let myRange = CountableRange<Int>(uncheckedBounds: (lower: 1, upper: 3)) // 1..<3
You can see that the index type here is Int
. That doesn't work for String
, though, because Strings are made of Characters and not all characters are the same size. (Read this for more info.) An emoji like , for example, takes more space than the letter "b".
Problem with NSRange
Try experimenting with NSRange
and an NSString
with emoji and you'll see what I mean. Headache.
let myNSRange = NSRange(location: 1, length: 3)
let myNSString: NSString = "abcde"
myNSString.substring(with: myNSRange) // "bcd"
let myNSString2: NSString = "acde"
myNSString2.substring(with: myNSRange) // "c" Where is the "d"!?
The smiley face takes two UTF-16 code units to store, so it gives the unexpected result of not including the "d".
Swift Solution
Because of this, with Swift Strings you use Range<String.Index>
, not Range<Int>
. The String Index is calculated based on a particular string so that it knows if there are any emoji or extended grapheme clusters.
Example
var myString = "abcde"
let start = myString.index(myString.startIndex, offsetBy: 1)
let end = myString.index(myString.startIndex, offsetBy: 4)
let myRange = start..<end
myString[myRange] // "bcd"
myString = "acde"
let start2 = myString.index(myString.startIndex, offsetBy: 1)
let end2 = myString.index(myString.startIndex, offsetBy: 4)
let myRange2 = start2..<end2
myString[myRange2] // "cd"
a...
and ...b
and ..<b
In Swift 4 things were simplified a bit. Whenever the starting or ending point of a range can be inferred, you can leave it off.
Int
You can use one-sided integer ranges to iterate over collections. Here are some examples from the documentation.
// iterate from index 2 to the end of the array
for name in names[2...] {
print(name)
}
// iterate from the beginning of the array to index 2
for name in names[...2] {
print(name)
}
// iterate from the beginning of the array up to but not including index 2
for name in names[..<2] {
print(name)
}
// the range from negative infinity to 5. You can't iterate forward
// over this because the starting point in unknown.
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true
// You can iterate over this but it will be an infinate loop
// so you have to break out at some point.
let range = 5...
String
This also works with String ranges. If you are making a range with str.startIndex
or str.endIndex
at one end, you can leave it off. The compiler will infer it.
Given
var str = "Hello, playground"
let index = str.index(str.startIndex, offsetBy: 5)
let myRange = ..<index // Hello
You can go from the index to str.endIndex by using ...
var str = "Hello, playground"
let index = str.index(str.endIndex, offsetBy: -10)
let myRange = index... // playground
Notes
Try switching your JVM to eclipse openj9. Its gonna use way less memory. I swapped it and its using 600Mb constantly.
Try:
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
Now test:
var str = "5";
alert(str.lpad("0", 4)); //result "0005"
var str = "10"; // note this is string type
alert(str.lpad("0", 4)); //result "0010"
In ECMAScript 2017 , we have new method padStart
and padEnd
which has below syntax.
"string".padStart(targetLength [,padString]):
So now we can use
const str = "5";
str.padStart(4, "0"); // "0005"
Works for me too
responsive:true
maintainAspectRatio: false
<div class="row">
<div class="col-xs-12">
<canvas id="mycanvas" width="500" height="300"></canvas>
</div>
</div>
Thank You
I've been using the same approach of saving the hidden TabPages in a private list, but the problem is that when I want to show the TabPage again, they doesn't appears in the original position (order). So, finally, I wrote a class in VB to add the TabControl with two methods: HideTabPageByName and ShowTabPageByName. You can just call the methods passing the name (not the TabPage instance).
Public Class CS_Control_TabControl
Inherits System.Windows.Forms.TabControl
Private mTabPagesHidden As New Dictionary(Of String, System.Windows.Forms.TabPage)
Private mTabPagesOrder As List(Of String)
Public Sub HideTabPageByName(ByVal TabPageName As String)
If mTabPagesOrder Is Nothing Then
' The first time the Hide method is called, save the original order of the TabPages
mTabPagesOrder = New List(Of String)
For Each TabPageCurrent As TabPage In Me.TabPages
mTabPagesOrder.Add(TabPageCurrent.Name)
Next
End If
If Me.TabPages.ContainsKey(TabPageName) Then
Dim TabPageToHide As TabPage
' Get the TabPage object
TabPageToHide = TabPages(TabPageName)
' Add the TabPage to the internal List
mTabPagesHidden.Add(TabPageName, TabPageToHide)
' Remove the TabPage from the TabPages collection of the TabControl
Me.TabPages.Remove(TabPageToHide)
End If
End Sub
Public Sub ShowTabPageByName(ByVal TabPageName As String)
If mTabPagesHidden.ContainsKey(TabPageName) Then
Dim TabPageToShow As TabPage
' Get the TabPage object
TabPageToShow = mTabPagesHidden(TabPageName)
' Add the TabPage to the TabPages collection of the TabControl
Me.TabPages.Insert(GetTabPageInsertionPoint(TabPageName), TabPageToShow)
' Remove the TabPage from the internal List
mTabPagesHidden.Remove(TabPageName)
End If
End Sub
Private Function GetTabPageInsertionPoint(ByVal TabPageName As String) As Integer
Dim TabPageIndex As Integer
Dim TabPageCurrent As TabPage
Dim TabNameIndex As Integer
Dim TabNameCurrent As String
For TabPageIndex = 0 To Me.TabPages.Count - 1
TabPageCurrent = Me.TabPages(TabPageIndex)
For TabNameIndex = TabPageIndex To mTabPagesOrder.Count - 1
TabNameCurrent = mTabPagesOrder(TabNameIndex)
If TabNameCurrent = TabPageCurrent.Name Then
Exit For
End If
If TabNameCurrent = TabPageName Then
Return TabPageIndex
End If
Next
Next
Return TabPageIndex
End Function
Protected Overrides Sub Finalize()
mTabPagesHidden = Nothing
mTabPagesOrder = Nothing
MyBase.Finalize()
End Sub
End Class
Make sure you're function is wrapped in a closure, complete with the extra () at the end:
(function(){
var app = angular.module('myApp', []);
})();
In case you're using apache's http-client 4:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext,
new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
You can add pager transform on Viewpager like this
myPager.setPageTransformer(true, new MapPagerTransform());
In the below code I changed my view color on runtime when pager scroll
public class MapPagerTransform implements ViewPager.PageTransformer {
public void transformPage(View view, float position) {
LinearLayout showSelectionLL = (LinearLayout) view.findViewById(R.id.showSelectionLL);
if (position < 0) {
showSelectionLL.setBackgroundColor(Color.WHITE);
} else if (position > 0) {
showSelectionLL.setBackgroundColor(Color.WHITE);
} else {
showSelectionLL.setBackgroundColor(Color.RED);
}
}
}
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
you can also just run it with a shell, for example:
bash example.txt
sh example.txt
<?php
// Example API call
$data = array(array (
"REGION" => "MUMBAI",
"LOCATION" => "NA",
"STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data);
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string) ,
'API-TOKEN-KEY:'.$authToken )); // API-TOKEN-KEY is keyword so change according to ur key word. like authorization
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);
To globally redirect after successful login, find this code in wp-login.php, under section.
<form name="loginform" id="loginform" action="<?php echo esc_url( site_url( 'wp-login.php', 'login_post' ) ); ?>" method="post">
<input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>" />
and replace <?php echo esc_attr($redirect_to); ?>
with your URL where you want to redirect. The URL must start with http:// and ends on /other wise page redirect to default location.
Do same thing form redirect after registration with in same file but under <form name="registerform">
section.
You should stop the submit procedure by returning false on the onsubmit callback.
<script>
function checkRegistration(){
if(!form_valid){
alert('Given data is not correct');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()"...
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
Write google to go to google...<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.
As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.
If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.
http://docs.python.org/library/threading.html#threading.Thread.daemon
I am sure my code will be easier and works faster.
$logon_sessions = get-process -includeusername | Select-Object -Unique -Property UserName, si | ? { $_ -match "server" -and $_ -notmatch "admin" }
foreach ($id in $logon_sessions.si) {
logoff $id
}
You mean that your code is DDL? If so, MSSQL has no difference. Above examples well shows how to invoke this. Just ensure
CommandType = CommandType.Text
The usual way to do this is to set the Form
's AcceptButton
to the button you want "clicked". You can do this either in the VS designer or in code and the AcceptButton
can be changed at any time.
This may or may not be applicable to your situation, but I have used this in conjunction with GotFocus
events for different TextBox
es on my form to enable different behavior based on where the user hit Enter. For example:
void TextBox1_GotFocus(object sender, EventArgs e)
{
this.AcceptButton = ProcessTextBox1;
}
void TextBox2_GotFocus(object sender, EventArgs e)
{
this.AcceptButton = ProcessTextBox2;
}
One thing to be careful of when using this method is that you don't leave the AcceptButton
set to ProcessTextBox1
when TextBox3
becomes focused. I would recommend using either the LostFocus
event on the TextBox
es that set the AcceptButton
, or create a GotFocus
method that all of the controls that don't use a specific AcceptButton
call.
The answer to this is CSS Specificity. You need to be more "specific" in your CSS so that it can override bootstrap css properties.
For example you have a sample code for a bootstrap menu here:
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div id="home-menu-container" class="collapse navbar-collapse">
<ul id="home-menu" class="nav navbar-nav">
<li><a class="navbar-brand" href="#"><img src="images/xd_logo.png" /></a></li>
<li><a href="#intro">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#services">What We Do</a></li>
<li><a href="#process">Our Process</a><br /></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#contact">Contact Us</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
Here, you need to remember the hierarchy of the specificity. It goes like this:
So, for the above if your css has something like this:
.navbar ul li a { color: red; } /* 10(.navbar) + 1(ul) + 1(li) + 1(a) = 13 points */
.navbar a { color: green; } /* 10(.navbar) + 1(a) = 11 points */
So, even if you have defined the .navbar a
after .navbar ul li a
it is still going to override with a red colour, instead of a green since the specificity is more (13 points).
So, basically all you need to do is calculate the points for the element you are wanting to change the css for, via inspect element on your browser. Here, bootstrap has specified its css for the element as
.navbar-inverse .navbar-nav>li>a { /* Total = 22 points */
color: #999;
}
So, even if your css is loading is being loaded after bootstrap.css which has the following line:
.navbar-nav li a {
color: red;
}
it's still going to be rendered as #999. In order to solve this, bootstrap has 22 points (calculate it yourself). So all we need is something more than that. Thus, I have added custom IDs to the elements i.e. home-menu-container and home-menu. Now the following css will work:
#home-menu-container #home-menu li a { color: red; } /* 100 + 100 + 1 + 1 = 202 points :) */
Done.
You can refer to this MDN link.
It's a while from the question but now JSONObject implements "toMap" method so you can try this way:
Map<String, Object> map = Obj1.toMap(); //making an HashMap from obj1
map.putAll(Obj2.toMap()); //moving all the stuff from obj2 to map
JSONObject combined = new JSONObject( map ); //new json from map
Reset - On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.
Revert - Reverting undoes a commit by creating a new commit. This is a safe way to undo changes, as it has no chance of re-writing the commit history. Contrast this with git reset, which does alter the existing commit history. For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch.
You can have a look on this link- Reset, Checkout and Revert
Use svn merge:
svn merge -c -[rev num that deleted the file] http://<path to repository>
So an example:
svn merge -c -12345 https://svn.mysite.com/svn/repo/project/trunk
^ The negative is important
For TortoiseSVN (I think...)
That is completely untested, however.
Edited by OP: This works on my version of TortoiseSVN (the old kind without the next button)
The trick is to merge backwards. Kudos to sean.bright for pointing me in the right direction!
Edit: We are using different versions. The method I described worked perfectly with my version of TortoiseSVN.
Also of note is that if there were multiple changes in the commit you are reverse merging, you'll want to revert those other changes once the merge is done before you commit. If you don't, those extra changes will also be reversed.
If the auditing is enabled on the server, just simply use
SELECT *
FROM ALL_TAB_MODIFICATIONS
WHERE TABLE_NAME IN ()
In case you have an async helperFunction()
called from your test... (one explicilty with the ES7 async
keyword, I mean)
? make sure, you call that as await helperFunction(whateverParams)
(well, yeah, naturally, once you know...)
And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:
it('my test', async () => { ...
Question : What is the best practice of returning/storing variables of multiple threads? A global hash table?
This totally depends on what you want to return and how you would use it? If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.
But, if you want some more information which will be used for further processing then you can use global data structure. But, in that case you need to handle concurrency issues by using appropriate synchronization primitives. Or you can allocate some dynamic memory (preferrably for the structure in which you want to store the data) and send it via pthread_exit and once the thread joins, you update it in another global structure. In this way only the one main thread will update the global structure and concurrency issues are resolved. But, you need to make sure to free all the memory allocated by different threads.
This will do it:
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': my_url,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
The main issue being that $.getJSON
will run asynchronously, thus your Javascript will progress past the expression which invokes it even before its success
callback fires, so there are no guarantees that your variable will capture any data.
Note in particular the 'async': false
option in the above ajax call. The manual says:
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
the function Position
in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.
Position(f, x, right = FALSE, nomatch = NA_integer)
Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem
<style type=text/css>
YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px;
padding-right:30px "to fix the text in the middle
without interfering with the text itself"}
</style>
It worked for me
If want to change port number in angular 2 or 4 we just need to open .angular-cli.json file and we need to keep the code as like below
"defaults": {
"styleExt": "css",
"component": {}
},
"serve": {
"port": 8080
}
}
variable = id if variable.to_s.empty?
After adding a resource folder try this :
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("test.png");
try {
image = ImageIO.read(input);
} catch (IOException e) {
e.printStackTrace();
}
git diff HEAD origin/master
Where origin
is the remote repository and master
is the default branch where you will push. Also, do a git fetch
before the diff
so that you are not diffing against a stale origin/master.
P.S. I am also new to git, so in case the above is wrong, please rectify.
You should be able to adjust the width using the .modal-dialog
class selector (in conjunction with media queries or whatever strategy you're using for responsive design):
.modal-dialog {
width: 400px;
}
Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.
select job, adate, rev, usr, typ
from tbl
where exists ( select 1 from ( select usr, adate, max(rev) as max_rev
from tbl
group by usr, adate
) as cond
where tbl.usr=cond.usr
and tbl.adate =cond.adate
and tbl.rev =cond.max_rev
)
order by adate, job, usr
As of Spring Data 1.7.1.RELEASE you can do it with two different ways,
public interface UserRepository extends CrudRepository<User, Integer> {
long countByName(String name);
}
@Query
annotation. public interface UserRepository extends CrudRepository<User, Integer> {
@Query("SELECT COUNT(u) FROM User u WHERE u.name=?1")
long aMethodNameOrSomething(String name);
}
or using @Param
annotation also,
public interface UserRepository extends CrudRepository<User, Integer> {
@Query("SELECT COUNT(u) FROM User u WHERE u.name=:name")
long aMethodNameOrSomething(@Param("name") String name);
}
Check also this so answer.
def get_dict_from_pd(df, key_col, row_col):
result = dict()
for i in set(df[key_col].values):
is_i = df[key_col] == i
result[i] = list(df[is_i][row_col].values)
return result
this is my sloution, a basic loop
By default Kubernetes looks in the public Docker registry to find images. If your image doesn't exist there it won't be able to pull it.
You can run a local Kubernetes registry with the registry cluster addon.
Then tag your images with localhost:5000
:
docker tag aii localhost:5000/dev/aii
Push the image to the Kubernetes registry:
docker push localhost:5000/dev/aii
And change run-aii.yaml to use the localhost:5000/dev/aii
image instead of aii
. Now Kubernetes should be able to pull the image.
Alternatively, you can run a private Docker registry through one of the providers that offers this (AWS ECR, GCR, etc.), but if this is for local development it will be quicker and easier to get setup with a local Kubernetes Docker registry.
Since uintptr_t
is not guaranteed to be there in C++/C++11, if this is a one way conversion you can consider uintmax_t
, always defined in <cstdint>
.
auto real_param = reinterpret_cast<uintmax_t>(param);
To play safe, one could add anywhere in the code an assertion:
static_assert(sizeof (uintmax_t) >= sizeof (void *) ,
"No suitable integer type for conversion from pointer type");
It sounds like you've already decided that Project Lombok gives you significant technical advantages for your proposed new project. (To be clear from the start, I have no particular views on Project Lombok, one way or the other.)
Before you use Project Lombok (or any other game-changing technology) in some project (open source or other wise), you need to make sure that the project stake holders agree to this. This includes the developers, and any important users (e.g. formal or informal sponsors).
You mention these potential issues:
Flamewars will erupt in the ##Java Freenode channel when I mention it,
Easy. Ignore / don't participate in the flamewars, or simply refrain from mentioning Lombok.
providing code snippets will confuse possible helpers,
If the project strategy is to use Lombok, then the possible helpers will need to get used to it.
people will complain about missing JavaDoc,
That is their problem. Nobody in their right mind tries to rigidly apply their organization's source code / documentation rules to third-party open source software. The project team should be free to set project source code / documentation standards that are appropriate to the technology being used.
(FOLLOWUP - The Lombok developers recognize that not generating javadoc comments for synthesized getter and setter methods is an issue. If this is a major problem for your project(s), then one alternative is to create and submit a Lombok patch to address this.)
and future commiters might just remove it all anyway.
That's not on! If the agreed project strategy is to use Lombok, then commiters who gratuitously de-Lombok the code should be chastised, and if necessary have their commit rights withdrawn.
Of course, this assumes that you've got buy-in from the stakeholders ... including the developers. And it assumes that you are prepared to argue your cause, and appropriately handle the inevitable dissenting voices.
You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect
. You could then make a rule like this:
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite to Category">
<match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
<action type="Rewrite" url="category.aspx?cid={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
I have edited the given above example...
public class YourActivity extends implements OnMarkerClickListener
{
......
private void setMarker()
{
.......
googleMap.setOnMarkerClickListener(this);
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
......
}
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(this,marker.getTitle(),Toast.LENGTH_LONG).show();
}
}
You're grouping with BillDate
, but the bill dates are different for each account so your rows are not being grouped. If you think about it, that doesn't even make sense - they are different bills, and have different dates. The same goes for the Bill
- you're attempting to sum bills for an account, why would you group by that?
If you leave BillDate
and Bill
off of the select and group by clauses you'll get the correct results.
SELECT AccountNumber, SUM(Bill)
FROM Table1
GROUP BY AccountNumber
cat names.txt|while read line; do
echo "$line";
done
Knowing how to write a preset dictionary is useful to know as well:
cmap = {'US':'USA','GB':'Great Britain'}
# Explicitly:
# -----------
def cxlate(country):
try:
ret = cmap[country]
except KeyError:
ret = '?'
return ret
present = 'US' # this one is in the dict
missing = 'RU' # this one is not
print cxlate(present) # == USA
print cxlate(missing) # == ?
# or, much more simply as suggested below:
print cmap.get(present,'?') # == USA
print cmap.get(missing,'?') # == ?
# with country codes, you might prefer to return the original on failure:
print cmap.get(present,present) # == USA
print cmap.get(missing,missing) # == RU
I've modified M-WaJeEh's answer a bit to take into account compound drawables on the sides.
The getCompoundPaddingXXXX()
methods return padding of the view + drawable space
. See for example: TextView.getCompoundPaddingLeft()
Issue: This fixes the measurement of the width and height of the TextView space available for the text. If we don't take the drawable size into account, it is ignored and the text will end up overlapping the drawable.
Updated segment adjustTextSize(String)
:
private void adjustTextSize(final String text) {
if (!mInitialized) {
return;
}
int heightLimit = getMeasuredHeight() - getCompoundPaddingBottom() - getCompoundPaddingTop();
mWidthLimit = getMeasuredWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
mAvailableSpaceRect.right = mWidthLimit;
mAvailableSpaceRect.bottom = heightLimit;
int maxTextSplits = text.split(" ").length;
AutoResizeTextView.super.setMaxLines(Math.min(maxTextSplits, mMaxLines));
super.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
binarySearch((int) mMinTextSize, (int) mMaxTextSize,
mSizeTester, mAvailableSpaceRect));
}
You have to move the css
folder into your web
folder. It seems that your web
folder on the hard drive equals the /ServletApp
folder as seen from the www. Other content than inside your web
folder cannot be accessed from the browsers.
The url of the CSS link is then
<link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
Follow this for Windows operating system with WAMP installed.
System > Advanced System Settings > Environment Variables
Click new
Variable name : path
Variable value : c:\wamp\bin\php\php5.3.13\
Click ok
Your question How can I just get the file-names (with paths)
Your syntax example find . -iname "*php" -exec grep -H myString {} \;
My Command suggestion
sudo find /home -name *.php
The output from this command on my Linux OS:
compose-sample-3/html/mail/contact_me.php
As you require the filename with path, enjoy!
No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:
select * from table1 where somedate between '2000/01/01' and '2099/12/31'
The separator needs to be a /
and it needs to be surrounded by single '
quotes.
Spent a day on finding the easiest way to do this. The purpose was to find the fastest way to achieve this goal. I couldn't make it as fast as running javac command from terminal or compiling from netbeans or sublime text 3. But still got a good speed with android studio.
This looks ruff and tuff way but since we don't initiate projects on daily bases that is why I am okay to do this.
I downloaded IntelliJ IDEA community version and created a simply java project. I added a main class and tested a run. Then simply closed IntelliJ IDEA and opened Android Studio and opened the same project there. Then I had to simply attach JDK where IDE helped me by showing a list of available JDKs and I selected 1.8 and then it compiled well. I can now open any main file and press Control+Shift+R to run that main file.
Then I copied all my Java files into src folder by Mac OS Finder. And I am able to compile anything I want to.
There is nothing related to Gradle or Android and compile speed is pretty good.
Thanks buddies
HTTP and redirects
Let's first recap how ASP.NET MVC works:
Let's also remind ourselves what a redirect is:
An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location
header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult
from an action.
Passing data
If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location
header. This is what would happen if you used something like
return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });
as others have suggested
The reason that this will not work is that the XDocument
is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument
action parameter.
In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.
Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.
Storing data for retrieval on the next request
So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session
(or TempData
, which is more or less the same as the Session
in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:
int documentId = _myDocumentRepository.Save(updatedResultsDocument);
and then you return that key to the client:
return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });
When you want to retrieve the document, you simply fetch it based on the key:
public ActionResult UpdateConfirmation(int id)
{
XDocument doc = _myDocumentRepository.GetById(id);
ConfirmationModel model = new ConfirmationModel(doc);
return View(model);
}
I just replaced ng-model
with ng-checked
and it worked for me.
This issue was when I updated my angular version from 1.2.28
to 1.4.9
Also check if your ng-change
is causing any issue here. I had to remove my ng-change
as-well to make it working.
You need to subscribe to the KeyDown
event on the text box. Then something like this:
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
&& e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*'
&& e.KeyChar != '/')
{
e.Handled = true;
return;
}
e.Handled=false;
return;
}
The important thing to know is that if you changed the Handled
property to true
, it will not process the keystroke. Setting it to false
will.
Oohoo so you want an exhaustive answer? Here's a fun, hopefully complete, and rather lengthy list for you :)
http://jim-mcbeath.blogspot.com/2008/12/scala-operator-cheat-sheet.html
(Disclaimer - the post was written in 2008 so may be a little out of date)
!! AbstractActor
!! Actor // Sends msg to this actor and immediately ...
!! Proxy
! Actor // Sends msg to this actor (asynchronous).
! Channel // Sends a message to this Channel.
! OutputChannel // Sends msg to this ...
! Proxy // Sends msg to this ...
!= Any // o != arg0 is the same as !(o == (arg0)).
!= AnyRef
!= Boolean
!= Byte
!= Char
!= Double
!= Float
!= Int
!= Long
!= Short
!? AbstractActor
!? Actor // Sends msg to this actor and awaits reply ...
!? Channel // Sends a message to this Channel and ...
!? Proxy
% BigInt // Remainder of BigInts
% Byte
% Char
% Double
% Float
% Int
% Long
% Short
% Elem // Returns a new element with updated attributes, resolving namespace uris from this element's scope. ...
&&& Parsers.Parser
&& Boolean
&+ NodeBuffer // Append given object to this buffer, returns reference on this NodeBuffer ...
& BigInt // Bitwise and of BigInts
& Boolean
& Byte
& Char
& Enumeration.Set32 // Equivalent to * for bit sets. ...
& Enumeration.Set64 // Equivalent to * for bit sets. ...
& Enumeration.SetXX // Equivalent to * for bit sets. ...
& Int
& Long
& Short
&~ BigInt // Bitwise and-not of BigInts. Returns a BigInt whose value is (this & ~that).
&~ Enumeration.Set32 // Equivalent to - for bit sets. ...
&~ Enumeration.Set64 // Equivalent to - for bit sets. ...
&~ Enumeration.SetXX // Equivalent to - for bit sets. ...
>>> Byte
>>> Char
>>> Int
>>> Long
>>> Short
>> BigInt // (Signed) rightshift of BigInt
>> Byte
>> Char
>> Int
>> Long
>> Short
>> Parsers.Parser // Returns into(fq)
>> Parsers.Parser // Returns into(fq)
> BigDecimal // Greater-than comparison of BigDecimals
> BigInt // Greater-than comparison of BigInts
> Byte
> Char
> Double
> Float
> Int
> Long
> Ordered
> PartiallyOrdered
> Short
>= BigDecimal // Greater-than-or-equals comparison of BigDecimals
>= BigInt // Greater-than-or-equals comparison of BigInts
>= Byte
>= Char
>= Double
>= Float
>= Int
>= Long
>= Ordered
>= PartiallyOrdered
>= Short
<< BigInt // Leftshift of BigInt
<< Byte
<< Char
<< Int
<< Long
<< Short
<< Buffer // Send a message to this scriptable object.
<< BufferProxy // Send a message to this scriptable object.
<< Map // Send a message to this scriptable object.
<< MapProxy // Send a message to this scriptable object.
<< Scriptable // Send a message to this scriptable object.
<< Set // Send a message to this scriptable object.
<< SetProxy // Send a message to this scriptable object.
<< SynchronizedBuffer // Send a message to this scriptable object.
<< SynchronizedMap // Send a message to this scriptable object.
<< SynchronizedSet // Send a message to this scriptable object.
< BigDecimal // Less-than of BigDecimals
< BigInt // Less-than of BigInts
< Byte
< Char
< Double
< Float
< Int
< Long
< Ordered
< PartiallyOrdered
< Short
< OffsetPosition // Compare this position to another, by first comparing their line numbers, ...
< Position // Compare this position to another, by first comparing their line numbers, ...
<= BigDecimal // Less-than-or-equals comparison of BigDecimals
<= BigInt // Less-than-or-equals comparison of BigInts
<= Byte
<= Char
<= Double
<= Float
<= Int
<= Long
<= Ordered
<= PartiallyOrdered
<= Short
<~ Parsers.Parser // A parser combinator for sequential composition which keeps only the left result
** Enumeration.SetXX
** Set // Intersect. It computes an intersection with set that. ...
** Set // This method is an alias for intersect. ...
* BigDecimal // Multiplication of BigDecimals
* BigInt // Multiplication of BigInts
* Byte
* Char
* Double
* Float
* Int
* Long
* Short
* Set
* RichString // return n times the current string
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser. ...
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser. ...
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser.
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses
++: ArrayBuffer // Prepends a number of elements provided by an iterable object ...
++: Buffer // Prepends a number of elements provided by an iterable object ...
++: BufferProxy // Prepends a number of elements provided by an iterable object ...
++: SynchronizedBuffer // Prepends a number of elements provided by an iterable object ...
++ Array // Returns an array consisting of all elements of this array followed ...
++ Enumeration.SetXX
++ Iterable // Appends two iterable objects.
++ IterableProxy // Appends two iterable objects.
++ Iterator // Returns a new iterator that first yields the elements of this ...
++ List // Appends two list objects.
++ RandomAccessSeq // Appends two iterable objects.
++ RandomAccessSeqProxy // Appends two iterable objects.
++ Seq // Appends two iterable objects.
++ SeqProxy // Appends two iterable objects.
++ IntMap // Add a sequence of key/value pairs to this map.
++ LongMap // Add a sequence of key/value pairs to this map.
++ Map // Add a sequence of key/value pairs to this map.
++ Set // Add all the elements provided by an iterator ...
++ Set // Add all the elements provided by an iterator to the set.
++ SortedMap // Add a sequence of key/value pairs to this map.
++ SortedSet // Add all the elements provided by an iterator ...
++ Stack // Push all elements provided by the given iterable object onto ...
++ Stack // Push all elements provided by the given iterator object onto ...
++ TreeHashMap
++ TreeHashMap // Add a sequence of key/value pairs to this map.
++ Collection // Operator shortcut for addAll.
++ Set // Operator shortcut for addAll.
++ ArrayBuffer // Appends two iterable objects.
++ Buffer // Appends a number of elements provided by an iterable object ...
++ Buffer // Appends a number of elements provided by an iterator ...
++ Buffer // Appends two iterable objects.
++ BufferProxy // Appends a number of elements provided by an iterable object ...
++ Map // Add a sequence of key/value pairs to this map.
++ MapProxy // Add a sequence of key/value pairs to this map.
++ PriorityQueue
++ Set // Add all the elements provided by an iterator ...
++ SynchronizedBuffer // Appends a number of elements provided by an iterable object ...
++ RichString // Appends two iterable objects.
++ RichStringBuilder // Appends a number of elements provided by an iterable object ...
++ RichStringBuilder // Appends two iterable objects.
++= Map // Add a sequence of key/value pairs to this map.
++= MapWrapper // Add a sequence of key/value pairs to this map.
++= ArrayBuffer // Appends a number of elements in an array
++= ArrayBuffer // Appends a number of elements provided by an iterable object ...
++= ArrayStack // Pushes all the provided elements onto the stack.
++= Buffer // Appends a number of elements in an array
++= Buffer // Appends a number of elements provided by an iterable object ...
++= Buffer // Appends a number of elements provided by an iterator
++= BufferProxy // Appends a number of elements provided by an iterable object ...
++= Map // Add a sequence of key/value pairs to this map.
++= MapProxy // Add a sequence of key/value pairs to this map.
++= PriorityQueue // Adds all elements provided by an Iterable object ...
++= PriorityQueue // Adds all elements provided by an iterator into the priority queue.
++= PriorityQueueProxy // Adds all elements provided by an Iterable object ...
++= PriorityQueueProxy // Adds all elements provided by an iterator into the priority queue.
++= Queue // Adds all elements provided by an Iterable object ...
++= Queue // Adds all elements provided by an iterator ...
++= QueueProxy // Adds all elements provided by an Iterable object ...
++= QueueProxy // Adds all elements provided by an iterator ...
++= Set // Add all the elements provided by an iterator ...
++= SetProxy // Add all the elements provided by an iterator ...
++= Stack // Pushes all elements provided by an Iterable object ...
++= Stack // Pushes all elements provided by an iterator ...
++= StackProxy // Pushes all elements provided by an Iterable object ...
++= StackProxy // Pushes all elements provided by an iterator ...
++= SynchronizedBuffer // Appends a number of elements provided by an iterable object ...
++= SynchronizedMap // Add a sequence of key/value pairs to this map.
++= SynchronizedPriorityQueue // Adds all elements provided by an Iterable object ...
++= SynchronizedPriorityQueue // Adds all elements provided by an iterator into the priority queue.
++= SynchronizedQueue // Adds all elements provided by an Iterable object ...
++= SynchronizedQueue // Adds all elements provided by an iterator ...
++= SynchronizedSet // Add all the elements provided by an iterator ...
++= SynchronizedStack // Pushes all elements provided by an Iterable object ...
++= SynchronizedStack // Pushes all elements provided by an iterator ...
++= RichStringBuilder // Appends a number of elements provided by an iterable object ...
+: ArrayBuffer // Prepends a single element to this buffer and return ...
+: Buffer // Prepend a single element to this buffer and return ...
+: BufferProxy // Prepend a single element to this buffer and return ...
+: ListBuffer // Prepends a single element to this buffer. It takes constant ...
+: ObservableBuffer // Prepend a single element to this buffer and return ...
+: SynchronizedBuffer // Prepend a single element to this buffer and return ...
+: RichStringBuilder // Prepend a single element to this buffer and return ...
+: BufferWrapper // Prepend a single element to this buffer and return ...
+: RefBuffer // Prepend a single element to this buffer and return ...
+ BigDecimal // Addition of BigDecimals
+ BigInt // Addition of BigInts
+ Byte
+ Char
+ Double
+ Enumeration.SetXX // Create a new set with an additional element.
+ Float
+ Int
+ List
+ Long
+ Short
+ EmptySet // Create a new set with an additional element.
+ HashSet // Create a new set with an additional element.
+ ListSet.Node // This method creates a new set with an additional element.
+ ListSet // This method creates a new set with an additional element.
+ Map
+ Map // Add a key/value pair to this map.
+ Map // Add two or more key/value pairs to this map.
+ Queue // Creates a new queue with element added at the end ...
+ Queue // Returns a new queue with all all elements provided by ...
+ Set // Add two or more elements to this set.
+ Set // Create a new set with an additional element.
+ Set1 // Create a new set with an additional element.
+ Set2 // Create a new set with an additional element.
+ Set3 // Create a new set with an additional element.
+ Set4 // Create a new set with an additional element.
+ SortedMap // Add a key/value pair to this map.
+ SortedMap // Add two or more key/value pairs to this map.
+ SortedSet // Create a new set with an additional element.
+ Stack // Push all elements provided by the given iterable object onto ...
+ Stack // Push an element on the stack.
+ TreeSet // A new TreeSet with the entry added is returned,
+ Buffer // adds "a" from the collection. Useful for chaining.
+ Collection // adds "a" from the collection. Useful for chaining.
+ Map // Add a key/value pair to this map.
+ Set // adds "a" from the collection. Useful for chaining.
+ Buffer // Append a single element to this buffer and return ...
+ BufferProxy // Append a single element to this buffer and return ...
+ Map // Add a key/value pair to this map.
+ Map // Add two or more key/value pairs to this map.
+ MapProxy // Add a key/value pair to this map.
+ MapProxy // Add two or more key/value pairs to this map.
+ ObservableBuffer // Append a single element to this buffer and return ...
+ PriorityQueue
+ Set // Add a new element to the set.
+ Set // Add two or more elements to this set.
+ SynchronizedBuffer // Append a single element to this buffer and return ...
+ Parsers.Parser // Returns a parser that repeatedly (at least once) parses what this parser parses.
+ Parsers.Parser // Returns a parser that repeatedly (at least once) parses what this parser parses.
+= Collection // adds "a" from the collection.
+= Map // Add a key/value pair to this map.
+= ArrayBuffer // Appends a single element to this buffer and returns ...
+= ArrayStack // Alias for push.
+= BitSet // Sets i-th bit to true. ...
+= Buffer // Append a single element to this buffer.
+= BufferProxy // Append a single element to this buffer.
+= HashSet // Add a new element to the set.
+= ImmutableSetAdaptor // Add a new element to the set.
+= JavaSetAdaptor // Add a new element to the set.
+= LinkedHashSet // Add a new element to the set.
+= ListBuffer // Appends a single element to this buffer. It takes constant ...
+= Map // Add a key/value pair to this map.
+= Map // Add two or more key/value pairs to this map.
+= Map // This method defines syntactic sugar for adding or modifying ...
+= MapProxy // Add a key/value pair to this map.
+= MapProxy // Add two or more key/value pairs to this map.
+= ObservableSet // Add a new element to the set.
+= PriorityQueue // Add two or more elements to this set.
+= PriorityQueue // Inserts a single element into the priority queue.
+= PriorityQueueProxy // Inserts a single element into the priority queue.
+= Queue // Inserts a single element at the end of the queue.
+= QueueProxy // Inserts a single element at the end of the queue.
+= Set // Add a new element to the set.
+= Set // Add two or more elements to this set.
+= SetProxy // Add a new element to the set.
+= Stack // Pushes a single element on top of the stack.
+= StackProxy // Pushes a single element on top of the stack.
+= SynchronizedBuffer // Append a single element to this buffer.
+= SynchronizedMap // Add a key/value pair to this map.
+= SynchronizedMap // Add two or more key/value pairs to this map.
+= SynchronizedPriorityQueue // Inserts a single element into the priority queue.
+= SynchronizedQueue // Inserts a single element at the end of the queue.
+= SynchronizedSet // Add a new element to the set.
+= SynchronizedStack // Pushes a single element on top of the stack.
+= RichStringBuilder // Append a single element to this buffer.
+= Reactions // Add a reaction.
+= RefBuffer // Append a single element to this buffer.
+= CachedFileStorage // adds a node, setting this.dirty to true as a side effect
+= IndexedStorage // adds a node, setting this.dirty to true as a side effect
+= SetStorage // adds a node, setting this.dirty to true as a side effect
-> Map.MapTo
-> Map.MapTo
-- List // Computes the difference between this list and the given list ...
-- Map // Remove a sequence of keys from this map
-- Set // Remove all the elements provided by an iterator ...
-- SortedMap // Remove a sequence of keys from this map
-- MutableIterable // Operator shortcut for removeAll.
-- Set // Operator shortcut for removeAll.
-- Map // Remove a sequence of keys from this map
-- MapProxy // Remove a sequence of keys from this map
-- Set // Remove all the elements provided by an iterator ...
--= Map // Remove a sequence of keys from this map
--= MapProxy // Remove a sequence of keys from this map
--= Set // Remove all the elements provided by an iterator ...
--= SetProxy // Remove all the elements provided by an iterator ...
--= SynchronizedMap // Remove a sequence of keys from this map
--= SynchronizedSet // Remove all the elements provided by an iterator ...
- BigDecimal // Subtraction of BigDecimals
- BigInt // Subtraction of BigInts
- Byte
- Char
- Double
- Enumeration.SetXX // Remove a single element from a set.
- Float
- Int
- List // Computes the difference between this list and the given object ...
- Long
- Short
- EmptyMap // Remove a key from this map
- EmptySet // Remove a single element from a set.
- HashMap // Remove a key from this map
- HashSet // Remove a single element from a set.
- IntMap // Remove a key from this map
- ListMap.Node // Creates a new mapping without the given key. ...
- ListMap // This creates a new mapping without the given key. ...
- ListSet.Node // - can be used to remove a single element from ...
- ListSet // - can be used to remove a single element from ...
- LongMap // Remove a key from this map
- Map // Remove a key from this map
- Map // Remove two or more keys from this map
- Map1 // Remove a key from this map
- Map2 // Remove a key from this map
- Map3 // Remove a key from this map
- Map4 // Remove a key from this map
- Set // Remove a single element from a set.
- Set // Remove two or more elements from this set.
- Set1 // Remove a single element from a set.
- Set2 // Remove a single element from a set.
- Set3 // Remove a single element from a set.
- Set4 // Remove a single element from a set.
- SortedMap // Remove a key from this map
- SortedMap // Remove two or more keys from this map
- TreeHashMap // Remove a key from this map
- TreeMap // Remove a key from this map
- TreeSet // Remove a single element from a set.
- UnbalancedTreeMap.Node // Remove a key from this map
- UnbalancedTreeMap // Remove a key from this map
- Map // Remove a key from this map
- MutableIterable
- Set
- ListBuffer // Removes a single element from the buffer and return ...
- Map // Remove a key from this map
- Map // Remove two or more keys from this map
- MapProxy // Remove a key from this map
- MapProxy // Remove two or more keys from this map
- Set // Remove a new element from the set.
- Set // Remove two or more elements from this set.
-= Buffer // removes "a" from the collection.
-= Collection // removes "a" from the collection.
-= Map // Remove a key from this map, noop if key is not present.
-= BitSet // Clears the i-th bit.
-= Buffer // Removes a single element from this buffer, at its first occurrence. ...
-= HashMap // Remove a key from this map, noop if key is not present.
-= HashSet // Removes a single element from a set.
-= ImmutableMapAdaptor // Remove a key from this map, noop if key is not present.
-= ImmutableSetAdaptor // Removes a single element from a set.
-= JavaMapAdaptor // Remove a key from this map, noop if key is not present.
-= JavaSetAdaptor // Removes a single element from a set.
-= LinkedHashMap // Remove a key from this map, noop if key is not present.
-= LinkedHashSet // Removes a single element from a set.
-= ListBuffer // Remove a single element from this buffer. It takes linear time ...
-= Map // Remove a key from this map, noop if key is not present.
-= Map // Remove two or more keys from this map
-= MapProxy // Remove a key from this map, noop if key is not present.
-= MapProxy // Remove two or more keys from this map
-= ObservableMap // Remove a key from this map, noop if key is not present.
-= ObservableSet // Removes a single element from a set.
-= OpenHashMap // Remove a key from this map, noop if key is not present.
-= Set // Remove two or more elements from this set.
-= Set // Removes a single element from a set.
-= SetProxy // Removes a single element from a set.
-= SynchronizedMap // Remove a key from this map, noop if key is not present.
-= SynchronizedMap // Remove two or more keys from this map
-= SynchronizedSet // Removes a single element from a set.
-= Reactions // Remove the given reaction.
-= CachedFileStorage // removes a tree, setting this.dirty to true as a side effect
-= IndexedStorage // removes a tree, setting this.dirty to true as a side effect
/% BigInt // Returns a pair of two BigInts containing (this / that) and (this % that).
/: Iterable // Similar to foldLeft but can be used as ...
/: IterableProxy // Similar to foldLeft but can be used as ...
/: Iterator // Similar to foldLeft but can be used as ...
/ BigDecimal // Division of BigDecimals
/ BigInt // Division of BigInts
/ Byte
/ Char
/ Double
/ Float
/ Int
/ Long
/ Short
:/: Document
::: List
:: List
:: Document
:\ Iterable // An alias for foldRight. ...
:\ IterableProxy // An alias for foldRight. ...
:\ Iterator // An alias for foldRight. ...
== Any // o == arg0 is the same as o.equals(arg0).
== AnyRef // o == arg0 is the same as if (o eq null) arg0 eq null else o.equals(arg0).
== Boolean
== Byte
== Char
== Double
== Float
== Int
== Long
== Short
? Actor // Receives the next message from this actor's mailbox.
? Channel // Receives the next message from this Channel.
? InputChannel // Receives the next message from this Channel.
? Parsers.Parser // Returns a parser that optionally parses what this parser parses.
? Parsers.Parser // Returns a parser that optionally parses what this parser parses.
\ NodeSeq // Projection function. Similar to XPath, use this \ "foo"
\\ NodeSeq // projection function. Similar to XPath, use this \\ 'foo
^ BigInt // Bitwise exclusive-or of BigInts
^ Boolean
^ Byte
^ Char
^ Int
^ Long
^ Short
^? Parsers.Parser // A parser combinator for partial function application
^? Parsers.Parser // A parser combinator for partial function application
^^ Parsers.Parser // A parser combinator for function application
^^ Parsers.Parser // A parser combinator for function application
^^ Parsers.UnitParser // A parser combinator for function application
^^^ Parsers.Parser
| BigInt // Bitwise or of BigInts
| Boolean
| Byte
| Char
| Enumeration.Set32 // Equivalent to ++ for bit sets. Returns a set ...
| Enumeration.Set32 // Equivalent to + for bit sets. Returns a set ...
| Enumeration.Set64 // Equivalent to ++ for bit sets. Returns a set ...
| Enumeration.Set64 // Equivalent to + for bit sets. Returns a set ...
| Enumeration.SetXX // Equivalent to ++ for bit sets. Returns a set ...
| Enumeration.SetXX // Equivalent to + for bit sets. Returns a set ...
| Int
| Long
| Short
| Parsers.Parser // A parser combinator for alternative composition
| Parsers.Parser // A parser combinator for alternative composition
| Parsers.UnitParser // A parser combinator for alternative composition
|| Boolean
||| Parsers.Parser
||| Parsers.Parser // A parser combinator for alternative with longest match composition
||| Parsers.Parser // A parser combinator for alternative with longest match composition
||| Parsers.UnitParser // A parser combinator for alternative with longest match composition
~! Parsers.Parser // A parser combinator for non-back-tracking sequential composition
~! Parsers.Parser // A parser combinator for non-back-tracking sequential composition with a unit-parser
~! Parsers.Parser // A parser combinator for non-back-tracking sequential composition
~! Parsers.UnitParser // A parser combinator for non-back-tracking sequential composition with a unit-parser
~! Parsers.UnitParser // A parser combinator for non-back-tracking sequential composition
~> Parsers.Parser // A parser combinator for sequential composition which keeps only the right result
~ BigInt // Returns the bitwise complement of this BigNum
~ Parsers.OnceParser // A parser combinator for sequential composition
~ Parsers.Parser // A parser combinator for sequential composition
~ Parsers
~ Parsers.OnceParser // A parser combinator for sequential composition with a unit-parser
~ Parsers.OnceParser // A parser combinator for sequential composition
~ Parsers.Parser // A parser combinator for sequential composition with a unit-parser
~ Parsers.Parser // A parser combinator for sequential composition
~ Parsers.UnitOnceParser // A parser combinator for sequential composition with a unit-parser
~ Parsers.UnitOnceParser // A parser combinator for sequential composition
~ Parsers.UnitParser // A parser combinator for sequential composition with a unit-parser
~ Parsers.UnitParser // A parser combinator for sequential composition
unary_! Boolean
unary_+ Byte
unary_+ Char
unary_+ Double
unary_+ Float
unary_+ Int
unary_+ Long
unary_+ Short
unary_- BigDecimal // Returns a BigDecimal whose value is the negation of this BigDecimal
unary_- BigInt // Returns a BigInt whose value is the negation of this BigInt
unary_- Byte
unary_- Char
unary_- Double
unary_- Float
unary_- Int
unary_- Long
unary_- Short
unary_~ Byte
unary_~ Char
unary_~ Int
unary_~ Long
unary_~ Short
I see that the originator found out that the error occurred when trying to save the filename with an entire path. Actually it's enough to have a ":"
in the file name to get this error. If there might be ":"
in your file name (for instance if you have a date stamp in your file name) make sure you replace these with something else. I.e:
string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];
There are two options:
A: You care about retaining array order:
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
B: You don't care about retaining order (this is probably faster):
a[i] = a[len(a)-1] // Replace it with the last one. CAREFUL only works if you have enough elements.
a = a[:len(a)-1] // Chop off the last one.
See the link to see implications re memory leaks if your array is of pointers.
Here's a way to use the stock AWS CLI to generate a diff
-able list of just object names:
aws s3api list-objects --bucket "$BUCKET" --query "Contents[].{Key: Key}" --output text
(based on https://stackoverflow.com/a/54378943/53529)
This gives you the full object name of every object in the bucket, separated by new lines. Useful if you want to diff between the contents of an S3 bucket and a GCS bucket, for example.
Short answer: you can use bbox_to_anchor
+ bbox_extra_artists
+ bbox_inches='tight'
.
Longer answer:
You can use bbox_to_anchor
to manually specify the location of the legend box, as some other people have pointed out in the answers.
However, the usual issue is that the legend box is cropped, e.g.:
import matplotlib.pyplot as plt
# data
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]
# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)
# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')
fig.savefig('image_output.png', dpi=300, format='png')
In order to prevent the legend box from getting cropped, when you save the figure you can use the parameters bbox_extra_artists
and bbox_inches
to ask savefig
to include cropped elements in the saved image:
fig.savefig('image_output.png', bbox_extra_artists=(lgd,), bbox_inches='tight')
Example (I only changed the last line to add 2 parameters to fig.savefig()
):
import matplotlib.pyplot as plt
# data
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]
# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)
# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')
fig.savefig('image_output.png', dpi=300, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')
I wish that matplotlib would natively allow outside location for the legend box as Matlab does:
figure
x = 0:.2:12;
plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));
hleg = legend('First','Second','Third',...
'Location','NorthEastOutside')
% Make the text of the legend italic and color it brown
set(hleg,'FontAngle','italic','TextColor',[.3,.2,.1])
After adding an item to a list, you can replace it by writing
list[someIndex] = new MyClass();
You can modify an existing item in the list by writing
list[someIndex].SomeProperty = someValue;
EDIT: You can write
var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);
I wrote this function it does just the right thing. Interpolate a word starting with $
with the value of the variable of the same name.
private static String interpol1(String x){
Field[] ffield = Main.class.getDeclaredFields();
String[] test = x.split(" ") ;
for (String v : test ) {
for ( Field n: ffield ) {
if(v.startsWith("$") && ( n.getName().equals(v.substring(1)) )){
try {
x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
}catch (Exception e){
System.out.println("");
}
}
}
}
return x;
}
I do this in a more permanent way - instead of installing the APKs each time with adb
, permanently add them to the system image that the emulator uses. You will need Yaffey on Windows, or a similar utility on other systems, to modify YAFFS2 images. Copy GoogleLoginService.apk
, GoogleServicesFramework.apk
, and Phonesky.apk
(or Vending.apk
in older versions of Android) to the /system/app
folder of the system.img
file of the emulator. Afterwards I can start the emulator normally, without messing with adb, and Play Store is always there.
Downloading Google Apps from some Internet site may not be quite legal, but if you have a phone or tablet with a corresponding Android version, just pull them out of your device:
adb -d root
adb -d pull /system/app/GoogleLoginService.apk
adb -d pull /system/app/GoogleServicesFramework.apk
adb -d pull /system/app/Phonesky.apk
You must have root-level access (run adb root) to the device in order to pull these files from it.
Now start yaffey
on Windows or a similar utility on Linux or Mac, and open system.img
for the emulator image you want to modify. I modify most often the one in [...]\android-sdk\system-images\android-17\x86
.
Rename the original system.img
to system-original.img
. Under yaffey, copy the APK files you pulled from your device to /app folder. Save your modified image as system.img
in the original folder. Then start your emulator (in my case it would be Android 4.2 emulator with Intel Atom processor running under Intel HAX, super-fast on Windows machines) and you'll have Play Store there. I did not find it necessary to delete SdkSetup.apk
and SdkSetup.odex
- the Play Store and other services still work fine for me with these files present.
When finished with your testing, to alleviate your conscience guilty of temporarily pirating the Google Apps from your device, you may delete the modified system.img
and restore the original from system-original.img
.
Check out Xtify Web Push notifications. http://getreactor.xtify.com/ This tool allows you to push content onto a webpage and target visitors as well as trigger messages based on browser DOM events. It's designed specifically with mobile in mind.
Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.
// substring + array push + end precalc
var chunks = [];
for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
chunks.push(str.substring(i, e));
}
Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.
You can try it here
This is the sdk path Android Studio installed for me: "C:\Users\<username>\appdata\local\android\sdk"
I'm running windows 8.1.
You can find the path going into Android Studio -> Configure -> SDK Manager -> On the top left it should say SDK Path.
I don't think it's necessary to install the sdk separately, as the default option for Android Studio is to install the latest sdk too.
teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"
You can also use template matching to detect shapes inside an image.
.Cells(.Rows.Count,"A").End(xlUp).row
I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:
.Cells(Rows.Count,"A").End(xlUp).row
Before the Cells, you can write your worksheet name, for example:
Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
The worksheet name is not necessary when you operate on the same worksheet.
In MS-DOS COMMAND.COM
shell, you have to use:
d:
cd \windows\movie
If by chance you actually meant "Windows command prompt" (which is not MS-DOS and not DOS at all), then you can use cd /d d:\windows\movie
.
Or simply:
\dt
to show tables
\d+ <table name>
to describe a table
Edit: Works using the psql command line client
I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/
Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
s.apply(lambda x: x!=x)
out[252]
0 False
1 True
2 False
dtype: bool
Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:
string* pStr = new string[3] { "hi", "there"};
See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init
You have to make the number to string in order to take length
var num = 123;
alert((num + "").length);
or
alert(num.toString().length);
Take a look at the facilities provided by the time
module
You have several conversion functions there.
Edit: see the datetime
module for more OOP-like solutions. The time
library linked above is kinda imperative.
There are two ways to handle CGI scripts, SetHandler
and AddHandler
.
SetHandler cgi-script
applies to all files in a given context, no matter how they are named, even index.html
or style.css
.
AddHandler cgi-script .pl
is similar, but applies to files ending in .pl
, in a given context. You may choose another extension or several, if you like.
Additionally, the CGI module must be loaded and Options +ExecCGI
configured. To activate the module, issue
a2enmod cgi
and restart or reload Apache. Finally, the Perl CGI script must be executable. So the execute bits must be set
chmod a+x script.pl
and it should start with
#! /usr/bin/perl
as its first line.
When you use SetHandler
or AddHandler
(and Options +ExecCGI
) outside of any directive, it is applied globally to all files. But you may restrict the context to a subset by enclosing these directives inside, e.g. Directory
<Directory /path/to/some/cgi-dir>
SetHandler cgi-script
Options +ExecCGI
</Directory>
Now SetHandler
applies only to the files inside /path/to/some/cgi-dir instead of all files of the web site. Same is with AddHandler
inside a Directory
or Location
directive, of course. It then applies to the files inside /path/to/some/cgi-dir, ending in .pl
.
When you checkout to a commit git checkout <commit-hash>
or to a remote branch your HEAD will get detached and try to create a new commit on it.
Commits that are not reachable by any branch or tag will be garbage collected and removed from the repository after 30 days.
Another way to solve this is by creating a new branch for the newly created commit and checkout to it. git checkout -b <branch-name> <commit-hash>
This article illustrates how you can get to detached HEAD state.