I tested the previous answers found here: Assuming that we want the other four sheets to remain, the previous answers here did not work, because the other four sheets were deleted. In case we want them to remain use xlwings:
import xlwings as xw
import pandas as pd
filename = "test.xlsx"
df = pd.DataFrame([
("a", 1, 8, 3),
("b", 1, 2, 5),
("c", 3, 4, 6),
], columns=['one', 'two', 'three', "four"])
app = xw.App(visible=False)
wb = xw.Book(filename)
ws = wb.sheets["Sheet5"]
ws.clear()
ws["A1"].options(pd.DataFrame, header=1, index=False, expand='table').value = df
# If formatting of column names and index is needed as xlsxwriter does it,
# the following lines will do it (if the dataframe is not multiindex).
ws["A1"].expand("right").api.Font.Bold = True
ws["A1"].expand("down").api.Font.Bold = True
ws["A1"].expand("right").api.Borders.Weight = 2
ws["A1"].expand("down").api.Borders.Weight = 2
wb.save(filename)
app.quit()
For console projects in a step-by-step fashion, you'll have to first add the System.Windows.Forms
reference. The following steps work in Visual Studio Community 2013 with .NET 4.5:
System.Windows.Forms
.Then, add the following using
statement in with the others at the top of your code:
using System.Windows.Forms;
Then, add either of the following Clipboard
.SetText
statements to your code:
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
And lastly, add STAThreadAttribute
to your Main
method as follows, to avoid a System.Threading.ThreadStateException
:
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}
First off, you have to specify you wish to use Document Literal style:
$client = new SoapClient(NULL, array(
'location' => 'https://example.com/path/to/service',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL)
);
Then, you need to transform your data into a SoapVar; I've written a simple transform function:
function soapify(array $data)
{
foreach ($data as &$value) {
if (is_array($value)) {
$value = soapify($value);
}
}
return new SoapVar($data, SOAP_ENC_OBJECT);
}
Then, you apply this transform function onto your data:
$data = soapify(array(
'Acquirer' => array(
'Id' => 'MyId',
'UserId' => 'MyUserId',
'Password' => 'MyPassword',
),
));
Finally, you call the service passing the Data parameter:
$method = 'Echo';
$result = $client->$method(new SoapParam($data, 'Data'));
In jsp you can do it like this:
<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>
If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();
. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.
For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.
Here's a general formula for creating thumbnails:
$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg';
$thumb_width = 200;
$thumb_height = 150;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
Haven't tested this but it should work.
EDIT
Now tested and working.
In the class onCreateView, I put this:
Dialog d = getDialog();
d.setTitle(Html.fromHtml("<font color='#EC407A'>About</font>"));
int dividerId = d.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider = d.findViewById(dividerId);
divider.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
colorPrimary links to our colors.xml file that stores all the colors. Also d.setTitle
provides a hacky way to set the title colour.
In fact, xargs
can run commands in parallel for you. There is a special -P max_procs
command-line option for that. See man xargs
.
The given answers work if you're in a context where conda is in your PATH environment variable, e.g. if you set it up that way during installation, or if you're running the "Anaconda Prompt".
If that's not the case, e.g. if you're trying to locate conda for use in a script, you should be able to pick up its installation location by probing HKCU\Software\Python
for available Python installations. For example:
>for /F "tokens=2,*" %a in ('reg query HKCU\Software\Python /f InstallPath /s /k /ve ^| findstr Default') do @echo %b
C:\Users\<username>\Miniconda3
C:\Users\<username>\Miniconda3
You can use serialize()
like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Make sure MySQL binds to 0.0.0.0 and not 127.0.0.1 or it will not be accessible from outside the machine
You can ensure this by editing your my.conf file and looking for the bind-address
item--you want it to look like bind-address = 0.0.0.0
. Then save this and restart mysql:
sudo service mysql restart
If you are doing this on a production server, you want to be aware of the security implications, discussed here: https://serverfault.com/questions/257513/how-bad-is-setting-mysqls-bind-address-to-0-0-0-0
Passed parameter like below,
Param([parameter(Mandatory=$true,
HelpMessage="Enter name and key values")]
$Name,
$Key)
.\script_name.ps1 -Name name -Key key
You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY
to your curl_setopt_array
method.
For example:
$proxy = '127.0.0.1:8888';
$opt = array (
CURLOPT_URL => "http://www.example.com",
CURLOPT_PROXY => $proxy,
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
);
$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);
Compile this in your database and start using boolean statements in your querys.
note: the function get's a varchar2 param, so be sure to wrap any "strings" in your statement. It will return 1 for true and 0 for false;
select bool('''abc''<''bfg''') from dual;
CREATE OR REPLACE function bool(p_str in varchar2) return varchar2
is
begin
execute immediate ' begin if '||P_str||' then
:v_res := 1;
else
:v_res := 0;
end if; end;' using out v_res;
return v_res;
exception
when others then
return '"'||p_str||'" is not a boolean expr.';
end;
/
This is really similar to another question. How should I load files into my Java application?
How should I load my files into my Java Application?
You do not want to load your files in by:
C:\your\project\file.txt
this is bad!
You should use getResourceAsStream.
InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);
And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.
In his paper, Memory Optimization, Christer Ericson says that while restrict
is not part of the C++ standard yet, that it is supported by many compilers and he recommends it's usage when available:
restrict keyword
! New to 1999 ANSI/ISO C standard
! Not in C++ standard yet, but supported by many C++ compilers
! A hint only, so may do nothing and still be conforming
A restrict-qualified pointer (or reference)...
! ...is basically a promise to the compiler that for the scope of the pointer, the target of the pointer will only be accessed through that pointer (and pointers copied from it).
In C++ compilers that support it it should probably behave the same as in C.
See this SO post for details: Realistic usage of the C99 ‘restrict’ keyword?
Take half an hour to skim through Ericson's paper, it's interesting and worth the time.
Edit
I also found that IBM's AIX C/C++ compiler supports the __restrict__
keyword.
g++ also seems to support this as the following program compiles cleanly on g++:
#include <stdio.h>
int foo(int * __restrict__ a, int * __restrict__ b) {
return *a + *b;
}
int main(void) {
int a = 1, b = 1, c;
c = foo(&a, &b);
printf("c == %d\n", c);
return 0;
}
I also found a nice article on the use of restrict
:
Demystifying The Restrict Keyword
Edit2
I ran across an article which specifically discusses the use of restrict in C++ programs:
Load-hit-stores and the __restrict keyword
Also, Microsoft Visual C++ also supports the __restrict
keyword.
Try something like this when you are applying focus that way if the element is hidden, it won't throw an error:
$("#elementid").filter(':visible').focus();
It may make more sense to make the element visible, though that will require code specific to your layout.
While using replace
seems to solve the problem, I would like to propose an alternative. Problem with mix of numeric and some string values in the column not to have strings replaced with np.nan, but to make whole column proper. I would bet that original column most likely is of an object type
Name: y, dtype: object
What you really need is to make it a numeric column (it will have proper type and would be quite faster), with all non-numeric values replaced by NaN.
Thus, good conversion code would be
pd.to_numeric(df['y'], errors='coerce')
Specify errors='coerce'
to force strings that can't be parsed to a numeric value to become NaN. Column type would be
Name: y, dtype: float64
Under browsers supporting js 1.8:
[i for(i in obj)]
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
simply use delete
, but be aware that you should read fully what the effects are of using this:
delete object.index; //true
object.index; //undefined
but if I was to use like so:
var x = 1; //1
delete x; //false
x; //1
but if you do wish to delete variables in the global namespace, you can use it's global object such as window
, or using this
in the outermost scope i.e
var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true
http://perfectionkills.com/understanding-delete/
another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice
which is a prototype of the array object.
Example Array:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
if I was to do:
delete myCars[1];
the resulting array would be:
["Saab", undefined, "BMW"]
but using splice like so:
myCars.splice(1,1);
would result in:
["Saab", "BMW"]
You have to reset each individual property back to its default value. It's not great, but it's the only way, given the information you've given us.
In your example, you would do:
.c1 {
height: auto;
}
You should search for each property here:
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference
For example, height
:
Initial value :
auto
Another example, max-height
:
Initial value :
none
In 2017, there is now another way, the unset
keyword:
.c1 {
height: unset;
}
Some documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/unset
The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.
Browser support is good: http://caniuse.com/css-unset-value
UPDATE: DO NOT use this old answer, better use this: https://stackoverflow.com/a/39266840/4031815
Ok after some hours of research I found svg-android to be quite easy to use, so I'm leaving here step by step instructions:
download lib from: https://code.google.com/p/svg-android/downloads/list
Latest version at the moment of writing this is: svg-android-1.1.jar
Put jar in lib
dir.
Save your *.svg file in res/drawable
dir (In illustrator is as easy as pressing Save as and select svg)
Code the following in your activity using the svg library:
ImageView imageView = (ImageView) findViewById(R.id.imgView);
SVG svg = SVGParser.getSVGFromResource(getResources(), R.drawable.example);
//The following is needed because of image accelaration in some devices such as samsung
imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
imageView.setImageDrawable(svg.createPictureDrawable());
Very easy I made a simple class to contain past code and reduce boilerplate code, like this:
import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
public class SvgImage {
private static ImageView imageView;
private Activity activity;
private SVG svg;
private int xmlLayoutId;
private int drawableId;
public SvgImage(Activity activity, int layoutId, int drawableId) {
imageView = (ImageView) activity.findViewById(layoutId);
svg = SVGParser.getSVGFromResource(activity.getResources(), drawableId);
//Needed because of image accelaration in some devices such as samsung
imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
imageView.setImageDrawable(svg.createPictureDrawable());
}
}
Now I can call it like this in activity:
SvgImage rainSVG = new SvgImage(MainActivity.this, R.id.rainImageView, R.drawable.rain);
SvgImage thunderSVG = new SvgImage(MainActivity.this, R.id.thunderImageView, R.drawable.thunder);
SvgImage oceanSVG = new SvgImage(MainActivity.this, R.id.oceanImageView, R.drawable.ocean);
SvgImage fireSVG = new SvgImage(MainActivity.this, R.id.fireImageView, R.drawable.fire);
SvgImage windSVG = new SvgImage(MainActivity.this, R.id.windImageView,R.drawable.wind);
SvgImage universeSVG = new SvgImage(MainActivity.this, R.id.universeImageView,R.drawable.universe);
Firstly, your example is looking quite correct and works well on my machine. You may go another way.
curl $CURLARGS $RVMHTTP > ./install.sh
All output now storing in ./install.sh
file, which you can edit and execute.
Without more details as to what the question is exactly asking, I am going to answer the title of the question,
Create an Array
:
String[] myArray = new String[2];
int[] intArray = new int[2];
// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};
Create an ArrayList
:
ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);
This means, create an ArrayList
of String
and Integer
objects. You cannot use int
because thats a primitive data types, see the link for a list of primitive data types.
Create a Stack
:
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
Create an Queue
: (using LinkedList)
Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);
Same thing as an ArrayList
, this declaration means create an Queue
of String
and Integer
objects.
In response to your comment from the other given answer,
i am pretty confused now, why are using string. and what does
<String>
means
We are using String
only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.
I have posted some links to explain the difference between the two, but here are a list of primitive types
byte
short
char
int
long
boolean
double
float
Which means, you are not allowed to make an ArrayList
of integer's like so:
ArrayList<int> numbers = new ArrayList<int>();
^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
^ perfectly valid
Also, you can use your own objects, here is my Monster
object I created,
public class Monster {
String name = null;
String location = null;
int age = 0;
public Monster(String name, String loc, int age) {
this.name = name;
this.loc = location;
this.age = age;
}
public void printDetails() {
System.out.println(name + " is from " + location +
" and is " + age + " old.");
}
}
Here we have a Monster
object, but now in our Main.java
class we want to keep a record of all our Monster
's that we create, so let's add them to an ArrayList
public class Main {
ArrayList<Monster> myMonsters = new ArrayList<Monster>();
public Main() {
Monster yetti = new Monster("Yetti", "The Mountains", 77);
Monster lochness = new Monster("Lochness Monster", "Scotland", 20);
myMonsters.add(yetti); // <-- added Yetti to our list
myMonsters.add(lochness); // <--added Lochness to our list
for (Monster m : myMonsters) {
m.printDetails();
}
}
public static void main(String[] args) {
new Main();
}
}
(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)
I use this snipped to change the active class for all pills in the same ul (applied at document ready):
$('ul.nav.nav-pills li a').click(function() {
$(this).parent().addClass('active').siblings().removeClass('active');
});
On *nix, unlike Windows, the current directory is usually not in your $PATH
variable. So the current directory is not searched when executing commands. You don't need ./
for running applications because these applications are in your $PATH; most likely they are in /bin
or /usr/bin
.
The other methods described assume a binary mask. If you want to use a real-valued single-channel grayscale image as a mask (e.g. from an alpha channel), you can expand it to three channels and then use it for interpolation:
assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
assert len(foreground_rgb.shape) == 3
assert len(background_rgb.shape) == 3
alpha3 = np.stack([mask]*3, axis=2)
blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb
Note that mask
needs to be in range 0..1
for the operation to succeed. It is also assumed that 1.0
encodes keeping the foreground only, while 0.0
means keeping only the background.
If the mask may have the shape (h, w, 1)
, this helps:
alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))
Here np.atleast_3d(mask)
makes the mask (h, w, 1)
if it is (h, w)
and np.squeeze(...)
reshapes the result from (h, w, 3, 1)
to (h, w, 3)
.
Function overloading is done when you want to have the same function with different parameters
void Print(string s);//Print string
void Print(int i);//Print integer
Function overriding is done to give a different meaning to the function in the base class
class Stream//A stream of bytes
{
public virtual void Read();//read bytes
}
class FileStream:Stream//derived class
{
public override void Read();//read bytes from a file
}
class NetworkStream:Stream//derived class
{
public override void Read();//read bytes from a network
}
Alternate approach : without installation of Redistributable package.
Check out in some github for the relevant dll, some people upload the reference dll for their application dependency.
you can download and use them in your project , I have used and run them successfully.
example : https://github.com/Emotiv/community-sdk/find/master
You can use zip
:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
... print x, y
...
1 a
2 b
3 c
For INNER
joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT *
to SELECT a.*, b.*, c.*
.
For (LEFT
, RIGHT
or FULL
) OUTER
joins, yes, the order matters - and (updated) things are much more complicated.
First, outer joins are not commutative, so a LEFT JOIN b
is not the same as b LEFT JOIN a
Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
is equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
but:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
AND c.bc_id = b.bc_id
is not equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
AND b.bc_id = c.bc_id
Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c
:
a LEFT JOIN b
ON b.ab_id = a.ab_id -- AB condition
LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
This is equivalent to a LEFT JOIN (b LEFT JOIN c)
:
a LEFT JOIN
b LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
ON b.ab_id = a.ab_id -- AB condition
only because we have "nice" ON
conditions. Both ON b.ab_id = a.ab_id
and c.bc_id = b.bc_id
are equality checks and do not involve NULL
comparisons.
You can even have conditions with other operators or more complex ones like: ON a.x <= b.x
or ON a.x = 7
or ON a.x LIKE b.x
or ON (a.x, a.y) = (b.x, b.y)
and the two queries would still be equivalent.
If however, any of these involved IS NULL
or a function that is related to nulls like COALESCE()
, for example if the condition was b.ab_id IS NULL
, then the two queries would not be equivalent.
Unzip the updated Android SDK in your current SDK folder. This solved my problem.
Adding a solution here for a different problem, but one that manifests with the same error... Take care when constructing json on the fly (as api responses or whatever) to escape literal double quotes in your string members. You may be consuming your own malformed json.
Yes. The querystring is also encrypted with SSL. Nevertheless, as this article shows, it isn't a good idea to put sensitive information in the URL. For example:
URLs are stored in web server logs - typically the whole URL of each request is stored in a server log. This means that any sensitive data in the URL (e.g. a password) is being saved in clear text on the server
If you are using ggplot2
to generate a figure, then a ggsave(file="name.eps")
will also work.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("test.csv");
If you use context ClassLoader to find a resource then definitely it will cost application performance.
Java7 update 45 64 bit direct download link is:
http://javadl.sun.com/webapps/download/AutoDL?BundleId=81821
Well there's no difference between the first two - they're just using different names for the type parameter (E
or T
).
The third isn't a valid declaration - ?
is used as a wildcard which is used when providing a type argument, e.g. List<?> foo = ...
means that foo
refers to a list of some type, but we don't know what.
All of this is generics, which is a pretty huge topic. You may wish to learn about it through the following resources, although there are more available of course:
Answered here: Convert an image to grayscale in HTML/CSS
You don't even need to use two images which sounds like a pain or an image manipulation library, you can do it with cross browser support (current versions) and just use CSS. This is a progressive enhancement approach which just falls back to color versions on older browsers:
img {
filter: url(filters.svg#grayscale);
/* Firefox 3.5+ */
filter: gray;
/* IE6-9 */
-webkit-filter: grayscale(1);
/* Google Chrome & Safari 6+ */
}
img:hover {
filter: none;
-webkit-filter: none;
}
and filters.svg file like this:
<svg xmlns="http://www.w3.org/2000/svg">
<filter id="grayscale">
<feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0" />
</filter>
</svg>
Yep, and if you have tried all the above solutions (what's more likely to happen) and none work for you, it may happen that Guzzle is not installed.
Laravel ships mailing tools, by which is required the Guzzle framework, but it won't be installed, and AS OF the documentation, will have to install it manually: https://laravel.com/docs/master/mail#driver-prerequisites
composer require guzzlehttp/guzzle
You don't, see below
I find this 'feature' rather annoying since I'm not trying to launch rockets to the moon, just push my damn branch. You probably do too or else you wouldn't be here!
Here is the fix: if you want it to implicitly push for the current branch regardless of if that branch exists on origin just issue this command once and you will never have to again anywhere:
git config --global push.default current
So if you make branches like this:
git checkout -b my-new-branch
and then make some commits and then do a
git push -u
to get them out to origin (being on that branch) and it will create said branch for you if it doesn't exist.
Note the -u bit makes sure they are linked if you were to pull later on from said branch. If you have no plans to pull the branch later (or are okay with another one liner if you do) -u is not necessary.
This could be due to Android Studio version conflict of v3 and v4 especially when you import a project in android stdio v4 which was previously built in v3.
Here are the few things you need to do:
Parentheses do not create a tuple. aka one = (two) is not a tuple. The only way around is either one = (two,) or one = tuple(two). So a solution is:
tuple(i for i in myothertupleorlistordict)
I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.
Give this a try:
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.
This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.
The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
I have found it best to add viewBox
and preserveAspectRatio
attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h
:
<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>
No.
A developer is responsible for keeping track of time-zone information associated with a DateTime value via some external mechanism.
A quote from an excellent article here. A must read for every .Net developer.
So my advice is to write a little wrapper class that suits your needs.
another way, this will scan the table only once instead of twice if you use a subquery
only sql server 2005 and up
select Date, User, Status, Notes
from (
select m.*, row_number() over (partition by user order by Date desc) as rn
from [SOMETABLE] m
) m2
where m2.rn = 1;
I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/
Instead of
this.$axios.get('items')
use
this.$axios({ url: 'items', baseURL: 'http://new-url.com' })
If you don't pass method: 'XXX'
then by default, it will send via get
method.
Request Config: https://github.com/axios/axios#request-config
It works good for me in Chrome 20.0.11
var startPos = this[0].selectionStart;
var endPos = this[0].selectionEnd;
var scrollTop = this.scrollTop;
this[0].value = this[0].value.substring(0, startPos) + myVal + this[0].value.substring(endPos, this[0].value.length);
this.focus();
this.selectionStart = startPos + myVal.length;
this.selectionEnd = startPos + myVal.length;
this.scrollTop = scrollTop;
A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).
My preference is using Sublime Text 3.
Microsoft Web Matrix and Dreamweaver are great.
Visual Studio and Expression Web are also great but may be overkill for you.
For just plain text editors, Sublime Text 2 is really cool
Python 3.6+ using f-string:
mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"
gives
'1362511338_314'
By Using data.table
we can specify data types for each column.
library(data.table)
data=data.table(a=numeric(), b=numeric(), c=numeric())
You should use dp just as you would pixels. That's all they are; display independent pixels. Use the same numbers you would on a medium density screen, and the size will be magically correct on a high density screen.
However, it sounds like what you need is the fill_parent option in your layout design. Use fill_parent when you want your view or control to expand to all the remaining size in the parent container.
You might want to have a look at this specification for CSV. Bear in mind that there is no official recognized specification.
If you do not now the delimiter it will not be possible to do this so you have to find out somehow. If you can do a manual inspection of the file you should quickly be able to see what it is and hard code it in your program. If the delimiter can vary your only hope is to be able to deduce if from the formatting of the known data. When Excel imports CSV files it lets the user choose the delimiter and this is a solution you could use as well.
Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.
You might be using a ConsoleHandler
(I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO
. You will have to configure this handler, to publish log records of level Level.FINER
and higher, for the desired outcome.
I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.
Editing the handler level
1. Using the Configuration file
The java.util.logging properties file (by default, this is the logging.properties
file in JRE_HOME/lib
) can be modified to change the default level of the ConsoleHandler:
java.util.logging.ConsoleHandler.level = FINER
2. Creating handlers at runtime
This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.
Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);
In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
mask = np.zeros(edges.shape)
to
mask = np.zeros(edges.shape,dtype='uint8')
For arbitrary levels of nestedness:
In [2]: def nested_dict():
...: return collections.defaultdict(nested_dict)
...:
In [3]: a = nested_dict()
In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})
In [5]: a['a']['b']['c'] = 1
In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
{'a': defaultdict(<function __main__.nested_dict>,
{'b': defaultdict(<function __main__.nested_dict>,
{'c': 1})})})
In my version of Git [1], every Git submodule has a name
and a path
. They don't necessarily have to be the same [2]. Getting both in a reliable way, without checking out the submodules first (git update --init
), is a tricky bit of shell wizardry.
names
I didn't find a way how to achieve this using git config
or any other git
command. Therefore we are back to regex on .gitmodules
(super ugly). But it seems to be somewhat safe since git
limits the possible code space allowed for submodule names
. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL
-bytes (\0
).
$ sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0"
And in your script:
#!/usr/bin/env bash
while IFS= read -rd '' submodule_name; do
echo submodule name: "${submodule_name}"
done < <(
sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0"
)
Note: read -rd ''
requires bash
and won't work with sh
.
paths
In my approach I try not to process the output from git config --get-regexp
with awk
, tr
, sed
, ... but instead pass it a zero byte separated back to git config --get
. This is to avoid problems with newlines, spaces and other special characters (e.g. Unicode) in the submodule paths
. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL
-bytes (\0
).
$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get
For example, in a Bash script you could then:
#!/usr/bin/env bash
while IFS= read -rd '' submodule_path; do
echo submodule path: "${submodule_path}"
done < <(
git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get
)
Note: read -rd ''
requires bash
and won't work with sh
.
$ git --version
git version 2.22.0
name
and path
Set up test repository:
$ git init test-name-path
$ cd test-name-path/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$ git submodule add ./ submodule-name
Cloning into '/tmp/test-name-path/submodule-name'...
done.
$ ls
submodule-name
$ cat .gitmodules
[submodule "submodule-name"]
path = submodule-name
url = ./
Move submodule to make name
and path
diverge:
$ git mv submodule-name/ submodule-path
$ ls
submodule-path
$ cat .gitmodules
[submodule "submodule-name"]
path = submodule-path
url = ./
$ git config --file .gitmodules --get-regexp '\.path$'
submodule.submodule-name.path submodule-path
Set up test repository:
$ git init test
$ cd test/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$
$ git submodule add ./ simplename
Cloning into '/tmp/test/simplename'...
done.
$
$ git submodule add ./ 'name with spaces'
Cloning into '/tmp/test/name with spaces'...
done.
$
$ git submodule add ./ 'future-name-with-newlines'
Cloning into '/tmp/test/future-name-with-newlines'...
done.
$ git mv future-name-with-newlines/ 'name
> with
> newlines'
$
$ git submodule add ./ 'name-with-unicode-'
Cloning into '/tmp/test/name-with-unicode-'...
done.
$
$ git submodule add ./ sub/folder/submodule
Cloning into '/tmp/test/sub/folder/submodule'...
done.
$
$ git submodule add ./ name.with.dots
Cloning into '/tmp/test/name.with.dots'...
done.
$
$ git submodule add ./ 'name"with"double"quotes'
Cloning into '/tmp/test/name"with"double"quotes'...
done.
$
$ git submodule add ./ "name'with'single'quotes"
Cloning into '/tmp/test/name'with'single'quotes''...
done.
$ git submodule add ./ 'name]with[brackets'
Cloning into '/tmp/test/name]with[brackets'...
done.
$ git submodule add ./ 'name-with-.path'
Cloning into '/tmp/test/name-with-.path'...
done.
.gitmodules
:
[submodule "simplename"]
path = simplename
url = ./
[submodule "name with spaces"]
path = name with spaces
url = ./
[submodule "future-name-with-newlines"]
path = name\nwith\nnewlines
url = ./
[submodule "name-with-unicode-"]
path = name-with-unicode-
url = ./
[submodule "sub/folder/submodule"]
path = sub/folder/submodule
url = ./
[submodule "name.with.dots"]
path = name.with.dots
url = ./
[submodule "name\"with\"double\"quotes"]
path = name\"with\"double\"quotes
url = ./
[submodule "name'with'single'quotes"]
path = name'with'single'quotes
url = ./
[submodule "name]with[brackets"]
path = name]with[brackets
url = ./
[submodule "name-with-.path"]
path = name-with-.path
url = ./
names
$ sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0" \
| xargs -0 -n1 echo submodule name:
submodule name: simplename
submodule name: name with spaces
submodule name: future-name-with-newlines
submodule name: name-with-unicode-
submodule name: sub/folder/submodule
submodule name: name.with.dots
submodule name: name"with"double"quotes
submodule name: name'with'single'quotes
submodule name: name]with[brackets
submodule name: name-with-.path
paths
$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get \
| xargs -0 -n1 echo submodule path:
submodule path: simplename
submodule path: name with spaces
submodule path: name
with
newlines
submodule path: name-with-unicode-
submodule path: sub/folder/submodule
submodule path: name.with.dots
submodule path: name"with"double"quotes
submodule path: name'with'single'quotes
submodule path: name]with[brackets
submodule path: name-with-.path
You can do two different container one with mobile order and hide on desktop screen, another with desktop order and hide on mobile screen
The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1
perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'
is equivalent to:
cut -d, -f2-4,6-10,12-20
If the commas are not needed in the output:
perl -F, -lane 'print "@F[1..3,5..9,11..19]"'
window.onload = codeAddress;
should work - here's a demo, and the full code:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Test</title>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<script type="text/javascript">_x000D_
function codeAddress() {_x000D_
alert('ok');_x000D_
}_x000D_
window.onload = codeAddress;_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Test</title>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<script type="text/javascript">_x000D_
function codeAddress() {_x000D_
alert('ok');_x000D_
}_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
<body onload="codeAddress();">_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
This works for me:
$.get("data.php", function(data){
var expected = ['justIn', 'recent', 'old'];
var outString = '';
$.each(expected, function(i, val){
var contentArray = data[val];
outString += '<ul><li><b>' + val + '</b>: ';
$.each(contentArray, function(i1, val2){
var textID = val2.textId;
var text = val2.text;
var textType = val2.textType;
outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
});
outString += '</li></ul>';
});
$('#contentHere').append(outString);
}, 'json');
This produces this output:
<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>
And looks like this:
Also, remember to set the contentType
as 'json'
If by version you mean a tag or a release, then github provides download links for those. For example, if I want to install fetch version 0.3.2 (it is not available on npm), then I add to my package.json
under dependencies
:
"fetch": "https://github.com/github/fetch/archive/v0.3.2.tar.gz",
The only disadvantage when compared with the commit hash approach is that a hash is guaranteed not to represent changed code, whereas a tag could be replaced. Thankfully this rarely happens.
Update:
These days the approach I use is the compact notation for a GitHub served dependency:
"dependencies": {
"package": "github:username/package#commit"
}
Where commit can be anything commitish, like a tag. In the case of GitHub you can even drop the initial github:
since it's the default.
I recently used ez_setup.py
as well and I did a tutorial on how to install it. The tutorial has snapshots and simple to follow. You can find it below:
Installing easy_install Using ez_setup.py
I hope you find this helpful.
Here's yet another, slightly different answer with a few enhancements.
This code takes the .jar right out of the .aar. Personally, that gives me a bit more confidence that the bits being shipped via .jar are the same as the ones shipped via .aar. This also means that if you're using ProGuard, the output jar will be obfuscated as desired.
I also added a super "makeJar" task, that makes jars for all build variants.
task(makeJar) << {
// Empty. We'll add dependencies for this task below
}
// Generate jar creation tasks for all build variants
android.libraryVariants.all { variant ->
String taskName = "makeJar${variant.name.capitalize()}"
// Create a jar by extracting it from the assembled .aar
// This ensures that products distributed via .aar and .jar exactly the same bits
task (taskName, type: Copy) {
String archiveName = "${project.name}-${variant.name}"
String outputDir = "${buildDir.getPath()}/outputs"
dependsOn "assemble${variant.name.capitalize()}"
from(zipTree("${outputDir}/aar/${archiveName}.aar"))
into("${outputDir}/jar/")
include('classes.jar')
rename ('classes.jar', "${archiveName}-${variant.mergedFlavor.versionName}.jar")
}
makeJar.dependsOn tasks[taskName]
}
For the curious reader, I struggled to determine the correct variables and parameters that the com.android.library plugin uses to name .aar files. I finally found them in the Android Open Source Project here.
Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY();
rule.
If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height {
-webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
}
In this instance, it is important to remember that translateY(100%)
will move the element in question downwards by a total of it's own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($){ //wait for the document to load
$('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
$(this).css({
'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
});
});
});
I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.
Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.
Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.
In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.
I would suggest using Document Wrapped as the web service type of choice due to its advantages.
SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.
If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.
A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services
...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?
If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:
Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.
Along with Environment.NewLine
and the literal \r\n
or just \n
you may also use a verbatim string in C#. These begin with @
and can have embedded newlines. The only thing to keep in mind is that "
needs to be escaped as ""
. An example:
string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."
I've faced this issue several times on MacOS. Git is case sensitive but Mac is only case preserving.
Someone commit a file: Foobar.java
and after a few days decides to rename it to FooBar.java
. When you pull the latest code it fails with The following untracked working tree files would be overwritten by checkout...
The only reliable way that I've seen that fixes this is:
git rm Foobar.java
git commit -m 'TEMP COMMIT!!'
git rebase --continue
git rebase -i HEAD~2
and drop
the TEMP COMMIT!!
FooBar.java
The file default.properties
is by default read only, changing that worked for me.
EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());
All you need is parent
part if you use pathlib
.
from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent)
Will output:
C:\Program Files\Internet Explorer
Case you need all parts (already covered in other answers) use parts
:
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts)
Then you will get a list:
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
Saves tone of time.
Swift 4 Answer who are using Constraint
label.text = "Hello World"
var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet
Swift 5 Answer who are using Constraint
label.text = "Hello World"
var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet
Another method is to place a png behind the UILabel. I have views with several labels that overlay a single background png that has all the artwork for the individual labels.
You can use the unicode of a non breaking space :
p:before { content: "\00a0 "; }
See JSfiddle demo
[style improved by @Jason Sperske]
String dateStart = "01/14/2015 08:29:58";
String dateStop = "01/15/2015 11:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
Another better way of doing it:
:LOOP
timeout /T 1 /NOBREAK
::pause or sleep x seconds also valid
call myLabel
if not ErrorLevel 1 goto :LOOP
This way you can take care of errors too
This error can occur if you project is compiling with JDK 1.6 and you have dependencies compiled with Java 7.
You probably will need to use POST or PATCH, because it is unlikely that a single request that updates and creates multiple resources will be idempotent.
Doing PATCH /docs
is definitely a valid option. You might find using the standard patch formats tricky for your particular scenario. Not sure about this.
You could use 200. You could also use 207 - Multi Status
This can be done in a RESTful way. The key, in my opinion, is to have some resource that is designed to accept a set of documents to update/create.
If you use the PATCH method I would think your operation should be atomic. i.e. I wouldn't use the 207 status code and then report successes and failures in the response body. If you use the POST operation then the 207 approach is viable. You will have to design your own response body for communicating which operations succeeded and which failed. I'm not aware of a standardized one.
[open git settings (TortoiseGit ? Settings ? Git)][1]
[In GIt: click to edit global .gitconfig][2]
Here is the solution I implemented after reading through jQuery UI ticket #4731, originally posted by slolife as a response to another answer. (The ticket was also created by him.)
First, in whatever method you use to apply autocompletes to the page, add the following line of code:
$.ui.dialog.prototype._focusTabbable = function(){};
That disables jQuery's "auto-focus" behavior. To ensure that your site continues to be broadly accessible, wrap your dialog creation methods so that additional code can be added, and add a call to focus the first input element:
function openDialog(context) {
// Open your dialog here
// Usability for screen readers. Focus on an element so that screen readers report it.
$("input:first", $(context)).focus();
}
To further address accessibility when autocomplete options are selected via keyboard, we override jQuery UI's "select" autocomplete callback and add some additional code to ensure the textElement does not lose focus in IE 8 after making a selection.
Here is the code we use to apply autocompletes to elements:
$.fn.applyAutocomplete = function () {
// Prevents jQuery dialog from auto-focusing on the first tabbable element.
// Make sure to wrap your dialog opens and focus on the first input element
// for screen readers.
$.ui.dialog.prototype._focusTabbable = function () { };
$(".autocomplete", this)
.each(function (index) {
var textElement = this;
var onSelect = $(this).autocomplete("option", "select");
$(this).autocomplete("option", {
select: function (event, ui) {
// Call the original functionality first
onSelect(event, ui);
// We replace a lot of content via AJAX in our project.
// This ensures proper copying of values if the original element which jQuery UI pointed to
// is replaced.
var $hiddenValueElement = $("#" + $(textElement).attr('data-jqui-acomp-hiddenvalue'));
if ($hiddenValueElement.attr("value") != ui.item.value) {
$hiddenValueElement.attr("value", ui.item.value);
}
// Replace text element value with that indicated by "display" if any
if (ui.item.display)
textElement.value = ui.item.display;
// For usability purposes. When using the keyboard to select from an autocomplete, this returns focus to the textElement.
$(textElement).focus();
if (ui.item.display)
return false;
}
});
})
// Set/clear data flag that can be checked, if necessary, to determine whether list is currently dropped down
.on("autocompleteopen", function (event, ui) {
$(event.target).data().autocompleteIsDroppedDown = true;
})
.on("autocompleteclose", function (event, ui) {
$(event.target).data().autocompleteIsDroppedDown = false;
});
return this;
}
If you want to end check whether your sentence ends with "." then you have to add [\.\]$ to the end of your pattern.
While trying to use the method with excutable configuration I noticed that it may work or may NOT work depending on where in the script is located the call:
call config.cmd
I know it doesn't make any sens, but for me it's a fact. When "call config.cmd" is located at the top of the script, it works, but if further in the script it doesn't.
By doesn't work, I mean the variable are not set un the calling script.
Very very strange !!!!
ngAttr
directive can totally be of help here, as introduced in the official documentation
https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes
For instance, to set the id
attribute value of a div
element, so that it contains an index, a view fragment might contain
<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>
which would get interpolated to
<div id="object-1"></div>
You can check like this
public void checktype() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
Toast.makeText(this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
}
}
}
I like to define custom structs locally. So:
// my handler func
func addImage(w http.ResponseWriter, r *http.Request) {
// define custom type
type Input struct {
Url string `json:"url"`
Name string `json:"name"`
Priority int8 `json:"priority"`
}
// define a var
var input Input
// decode input or return error
err := json.NewDecoder(r.Body).Decode(&input)
if err != nil {
w.WriteHeader(400)
fmt.Fprintf(w, "Decode error! please check your JSON formating.")
return
}
// print user inputs
fmt.Fprintf(w, "Inputed name: %s", input.Name)
}
You should also set this parameter to log every statement:
log_min_duration_statement = 0
Easy fix that worked for me (after trying some of these other suggestion). My logcat was sitting blank in a separate window (on my second screen). Just had to drag the Logcat tab back to it's original place in the debug panel next to the Debugger and Console tabs, and VOILA... it began immediately updating and showing all processes verbose. So (If your logcat is anywhere outside of the debugger panel (i.e. the logcat tab isn't sitting nested alongside the debugger and console tab) then it won't receive updates and will sit there blankly. Don't know if this is an issue with older versions of Android Studio. But again, easy to try and if it works... it works!!
For people finding this post and using PHP5.5+, this might help.
I was finding the approach suggested by netcoder wasn't working. i.e. this didn't work:
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
I would receive in the $_POST
var the 'uploaded_file'
field - and nothing in the $_FILES
var.
It turns out that for php5.5+ there is a new curl_file_create()
function you need to use. So the above would become:
$data = array(
'uploaded_file' => curl_file_create($tmpfile, $_FILES['image']['type'], $filename)
);
As the @
format is now deprecated.
If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.
As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).
edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p
In addition to previously provided answers, one option is to follow the 'localhost exception' approach to create the first user if your db is already started with access control (--auth
switch). In order to do that, you need to have localhost access to the server and then run:
mongo
use admin
db.createUser(
{
user: "user_name",
pwd: "user_pass",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" }
]
})
As stated in MongoDB documentation:
The localhost exception allows you to enable access control and then create the first user in the system. With the localhost exception, after you enable access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. Connections using the localhost exception only have access to create the first user on the admin database.
Here is the link to that section of the docs.
Remove 'javascript:' from your code and it should work.
Do you happen to use FireFox? I have learned from someone else that FireFox no longer accepts the 'javascript:' string. However, for the life of me, I cannot find the original source (though I believe it was somewhere in FF update notes).
A key is just a normal index. A way over simplification is to think of it like a card catalog at a library. It points MySQL in the right direction.
A unique key is also used for improved searching speed, but it has the constraint that there can be no duplicated items (there are no two x and y where x is not y and x == y).
The manual explains it as follows:
A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.
A primary key is a 'special' unique key. It basically is a unique key, except that it's used to identify something.
The manual explains how indexes are used in general: here.
In MSSQL, the concepts are similar. There are indexes, unique constraints and primary keys.
Untested, but I believe the MSSQL equivalent is:
CREATE TABLE tmp (
id int NOT NULL PRIMARY KEY IDENTITY,
uid varchar(255) NOT NULL CONSTRAINT uid_unique UNIQUE,
name varchar(255) NOT NULL,
tag int NOT NULL DEFAULT 0,
description varchar(255),
);
CREATE INDEX idx_name ON tmp (name);
CREATE INDEX idx_tag ON tmp (tag);
Edit: the code above is tested to be correct; however, I suspect that there's a much better syntax for doing it. Been a while since I've used SQL server, and apparently I've forgotten quite a bit :).
This issue can be resolved by trying multiple solutions like:
I've done this before with conditional formatting. It's a great way to visually inspect the cells in a workbook and spot the outliers in your data.
You can add a class to each of your .row
divs to add some space in between them like so:
.spacer {
margin-top: 40px; /* define margin as you see fit */
}
You can then use it like so:
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
You can only return one value, but it can be an object that has multiple fields - ie a "value object". Eg
public class MyResult {
int returnCode;
String errorMessage;
// etc
}
public MyResult someMethod() {
// impl here
}
My way of doing this involves adding a new column that is unique to one dataframe and using this to choose whether to keep an entry
df2[col3] = 1
df1 = pd.merge(df_1, df_2, on=['field_x', 'field_y'], how = 'outer')
df1['Empt'].fillna(0, inplace=True)
This makes it so every entry in df1 has a code - 0 if it is unique to df1, 1 if it is in both dataFrames. You then use this to restrict to what you want
answer = nonuni[nonuni['Empt'] == 0]
First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.
For an in-place sort, use
foo = [(list of tuples)]
foo.sort(key=lambda x:x[0]) #To sort by first element of the tuple
select * FROM doc_tab
PIVOT
(
Min(document_id)
FOR document_type IN ('Voters ID','Pan card','Drivers licence')
)
outputs as this
This seems to work for me.
var combindedString = new string(list.ToArray());
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
Let me seperate up everything and solve approach each problem in isolation:
Authentication
For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.
Auth server load
If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.
Transmission Security
If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.
url = username:[email protected]/api/call/nonce
If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:
nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call
It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).
Secure secret storage
It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.
If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.
(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.
Simple add below line into your MainActivity
and your App never turn lights off.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Since you tagged Java-ee as well - then YES it is possible.
and in core java as well it is possible using static blocks
and check this How can you run a Java program without main method?
Edit:
as already pointed out in other answers - it does not support from Java 7
You have to use HorizontalContentAlignment="Center" and! Width="Auto".
Pre React Native 0.29, run this in the console:
adb logcat *:S ReactNative:V ReactNativeJS:V
Post React Native 0.29, run:
react-native log-ios
or
react-native log-android
As Martin said in another answer.
This shows all console.log(), errors, notes, etc. and causes zero slow down.
Try putting this into the top of your file (before any other output):
<?php
header('Content-Type: text/html; charset=UTF-8');
?>
You can perform this task using window.location.reload();
. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation
JavaScript window.location
object can be used
window
: in JavaScript represents an open window in a browser.
location
: in JavaScript holds information about current URL.
The location
object is like a fragment of the window
object and is called up through the window.location
property.
location
object has three methods:
assign()
: used to load a new documentreload()
: used to reload current documentreplace()
: used to replace current document with a new oneSo here we need to use reload()
, because it can help us in reloading the same document.
So use it like window.location.reload();
.
To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true
parameter to location.reload()
. This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.
The whole thing should look like:
<form enctype='multipart/form-data' method='POST' action='submitFormTo.php'>
<input type='file' name='files[]' multiple />
<button type='submit'>Submit</button>
</form>
Make sure you have the enctype='multipart/form-data'
attribute in your <form>
tag, or you can't read the files on the server side after submission!
For MVC developers, to redirect a browser using javascript:
window.location.href = "@Url.Action("Action", "Controller")";
Disclaimer: This is intended for those supporting a continuous integration workflow that require an automated process. If you don't, please use Xcode as described in Javier's answer.
This worked for me to set ENABLE_BITCODE = NO
via the command line:
find . -name *project.pbxproj | xargs sed -i -e 's/\(GCC_VERSION = "";\)/\1\ ENABLE_BITCODE = NO;/g'
Note that this is likely to be unstable across Xcode versions. It was tested with Xcode 7.0.1 and as part of a Cordova 4.0 project.
No, one per customer prior to Java 7.
You can catch a superclass, like java.lang.Exception, as long as you take the same action in all cases.
try {
// some code
} catch(Exception e) { //All exceptions are caught here as all are inheriting java.lang.Exception
e.printStackTrace();
}
But that might not be the best practice. You should only catch an exception when you have a strategy for actually handling it - and logging and rethrowing is not "handling it". If you don't have a corrective action, better to add it to the method signature and let it bubble up to someone that can handle the situation.
In simple cases you can use next method which doesn`t require you to create a function or to copy code to several cells:
In any cell write next code
=Transpose(A1:A9)
Where A1:A9 are cells you would like to merge.
F9
After that, the cell will contain the string:
={A1,A2,A3,A4,A5,A6,A7,A8,A9}
Source: http://www.get-digital-help.com/2011/02/09/concatenate-a-cell-range-without-vba-in-excel/
Update: One part can be ambiguous. Without leaving the cell means having your cell in editor mode. Alternatevly you can press F9 while are in cell editor panel (normaly it can be found above the spreadsheet)
To upper case: Ctrl+K, Ctrl+U
and to lower case: Ctrl+K, Ctrl+L.
Mnemonics:
K like the Keyboard
U like the Upper case
L like the Lower case
just change the default folder for your R libraries in a directory with no Administrator rights, e.g.
.libPaths("C:/R/libs")
How about something like this.
next_prime:
for (var i = 2; i < 100; i++){
for (var e = 2; e < i; e++){
if (i % e === 0) continue next_prime;
}
console.log(i + '<br>');
}
Here is an interesting case I thought I should share.
Let's say that you have an array of objects and an array of selected filters.
let arr = [
{ id: 'x', tags: ['foo'] },
{ id: 'y', tags: ['foo', 'bar'] },
{ id: 'z', tags: ['baz'] }
];
const filters = ['foo'];
To apply the selected filters to this structure we can
if (filters.length > 0)
arr = arr.filter(obj =>
obj.tags.some(tag => filters.includes(tag))
);
// [
// { id: 'x', tags: ['foo'] },
// { id: 'y', tags: ['foo', 'bar'] }
// ]
Another, more humane way:
find /<directory> -newermt "-24 hours" -ls
or:
find /<directory> -newermt "1 day ago" -ls
or:
find /<directory> -newermt "yesterday" -ls
Use the optional font
argument to turtle.write()
, from the docs:
turtle.write(
arg, move=False, align="left", font=("Arial", 8, "normal"))
Parameters:
- arg – object to be written to the TurtleScreen
- move – True/False
- align – one of the strings “left”, “center” or right”
- font – a triple (fontname, fontsize, fonttype)
So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal"))
to change the font size to 16 (default is 8).
UPDATE for v1.1:
Rather than giving q="search_string"
give it q="hashtag"
in URL encoded form to return results with HASHTAG ONLY. So your query would become:
GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames
%23
is URL encoded form of #
. Try the link out in your browser and it should work.
You can optimize the query by adding since_id
and max_id
parameters detailed here. Hope this helps !
Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call
Updated
Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
Permanent Generation. Details are of course implementation specific.
Briefly, it contains the Java objects associated with classes and interned strings. In Sun's client implementation with sharing on, classes.jsa
is memory mapped to form the initial data, with about half read-only and half copy-on-write.
Java objects that are merely old are kept in the Tenured Generation.
Subversion 1.5 introduces sparse checkouts which may be something you might find useful. From the documentation:
... sparse directories (or shallow checkouts) ... allows you to easily check out a working copy—or a portion of a working copy—more shallowly than full recursion, with the freedom to bring in previously ignored files and subdirectories at a later time.
Check on yourCheckBox.Value
?
When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.
ASPX code:
<asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
someID.Attributes.Add("onClick", "return false;");
}
}
What renders as HTML is:
<a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a>
In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back.
I had this same issue when I was assessing 100+ servers, I had a script written in C# to browse the service names consist of SQL. When instances installed on the server, SQL Server adds a service for each instance with service name. It may vary for different versions like 2000 to 2008 but for sure there is a service with instance name.
I take the service name and obtain instance name from the service name. Here is the sample code used with WMI Query Result:
if (ServiceData.DisplayName == "MSSQLSERVER" || ServiceData.DisplayName == "SQL Server (MSSQLSERVER)")
{
InstanceData.Name = "DEFAULT";
InstanceData.ConnectionName = CurrentMachine.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
else
if (ServiceData.DisplayName.Contains("SQL Server (") == true)
{
InstanceData.Name = ServiceData.DisplayName.Substring(
ServiceData.DisplayName.IndexOf("(") + 1,
ServiceData.DisplayName.IndexOf(")") - ServiceData.DisplayName.IndexOf("(") - 1
);
InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
else
if (ServiceData.DisplayName.Contains("MSSQL$") == true)
{
InstanceData.Name = ServiceData.DisplayName.Substring(
ServiceData.DisplayName.IndexOf("$") + 1,
ServiceData.DisplayName.Length - ServiceData.DisplayName.IndexOf("$") - 1
);
InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:
EXEC TEST()
Share and enjoy.
Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS
view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:
CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
Y IN NUMBER DEFAULT 1)
AS
varX VARCHAR2(32767) := NVL(X, 'P');
varY NUMBER := NVL(Y, 1);
BEGIN
DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;
Another simple solution is list(np.where(df['b'].isnull())[0])
use grep [n]ame to remove that grep -v name this is first... Sec using xargs in the way how it is up there is wrong to rnu whatever it is piped you have to use -i ( interactive mode) otherwise you may have issues with the command.
ps axf | grep | grep -v grep | awk '{print "kill -9 " $1}' ? ps aux |grep [n]ame | awk '{print "kill -9 " $2}' ? isnt that better ?
If you are using Google Cloud Messaging, then this issue will not be solved by simply changing your icon. For example, this will not work:
Notification notification = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
.setAutoCancel(true)
.build();
Even if ic_notification is transparant and white. It must be also defined in the Manifest meta data, like so:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_notification" />
Meta-data goes under the application
tag, for reference.
A small change to Paul's code so that it doesn't return the error mentioned above.
dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
id.vars = "Species")
dat$x <- c(1:150, 1:150)
ggplot(aes(x = x, y = value, color = variable), data = dat) +
geom_point() + geom_line()
Using imgscalr – Java Image Scaling Library:
BufferedImage image =
Scalr.resize(originalImage, Scalr.Method.BALANCED, newWidth, newHeight);
This is fast enough for me.
1-make 1 shape for Button right click on drawable nd new drawable resource file . change Root element to shape and make your shape.
2-now make 1 copy from your shape and change name and change solid color. enter image description here
3-right click on drawable and new drawable resource file just set root element to selector.
go to file and set "state_pressed"
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"android:drawable="@drawable/YourShape1"/>
<item android:state_pressed="false" android:drawable="@drawable/YourShape2"/>
</selector>
4-the end go to xml layout and set your Button background "your selector"
(sorry for my english weak)
When we first moved over to Vista with Oracle 10g, we experienced this issue when we installed the Oracle client on our Vista boxes, even when we were running with admin privileges during install.
Oracle brought out a new version of the 10g client (10.2.0.3) that was Vista compatible.
I do believe that this was after 11g was released, so it is possible that there is a 'Vista compatible' version for 11g also.
Use encodeURIComponent()
in JS and in PHP you should receive the correct values.
Note: When you access $_GET
, $_POST
or $_REQUEST
in PHP, you are retrieving values that have already been decoded.
Example:
In your JS:
// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B
On your server:
echo $_GET['string']; // "+"
It is only the raw HTTP request that contains the url encoded data.
For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI']
or $_SERVER['QUERY_STRING']
. For a urlencoded POST, file_get_contents('php://stdin')
NB:
decode()
only works for single byte encoded characters. It will not work for the full UTF-8 range.
eg:
text = "\u0100"; // A
// incorrect
escape(text); // %u0100
// correct
encodeURIComponent(text); // "%C4%80"
Note: "%C4%80"
is equivalent to: escape('\xc4\x80')
Which is the byte sequence (\xc4\x80
) that represents A
in UTF-8. So if you use encodeURIComponent()
your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.
This was not working for me in Firefox.
We added a conditional based on whether the code places the overflow at the html level. See Animate scrollTop not working in firefox.
var $header = $("#header #menu-wrap-left"),
$clone = $header.before($header.clone().addClass("clone"));
$(window).on("scroll", function() {
var fromTop = Array();
fromTop["body"] = $("body").scrollTop();
fromTop["html"] = $("body,html").scrollTop();
if (fromTop["body"])
$('body').toggleClass("down", (fromTop["body"] > 650));
if (fromTop["html"])
$('body,html').toggleClass("down", (fromTop["html"] > 650));
});
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous
function. Otherwise you will have to make a callback
.
So I just added async:false,
to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)
Edit 2018-05-28 I have changed the example to use Java 8's Time API:
LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();
Layers refer to logical seperation of code. Logical layers help you organise your code better. For example an application can have the following layers.
1)Presentation Layer or UI Layer 2)Business Layer or Business Logic Layer 3)Data Access Layer or Data Layer
The aboove three layers reside in their own projects, may be 3 projects or even more. When we compile the projects we get the respective layer DLL. So we have 3 DLL's now.
Depending upon how we deploy our application, we may have 1 to 3 tiers. As we now have 3 DLL's, if we deploy all the DLL's on the same machine, then we have only 1 physical tier but 3 logical layers.
If we choose to deploy each DLL on a seperate machine, then we have 3 tiers and 3 layers.
So, Layers are a logical separation and Tiers are a physical separation. We can also say that, tiers are the physical deployment of layers.
if it's not working for you then replace android:background with android:src
android:src will play the major trick
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/bg_hc" />
it's working fine like a charm
With MySQL 5.x you can use:
ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name DATATYPE NULL DEFAULT NULL;
Try the following; it works for me.
I have an application which dumps data in my "C:\tmp" folder, and the following works the best for me. It doesn't even ask Yes or No to delete the data. I have made a schedule for it to run after every 5 minutes
cd "C:\tmp"
del *.* /Q
Just right click on your terminal icon, and select open a new window. Now you'll have two terminal windows open. In the new window, type, mongo and hit enter. Boom, that'll work like it's supposed to.
If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.
Regex is compiled so for speed create it once and reuse it.
The new takes longer than the IsMatch.
This only checks for all digits.
It does not check for range.
If you need to test range then TryParse is the way to go.
private static Regex regexInt = new Regex("^\\d+$");
static bool CheckReg(string value)
{
return regexInt.IsMatch(value);
}
You can also do this with hooks.
function MyComponent (props) {
const [isActive, setActive] = useState(false);
const toggleClass = () => {
setActive(!isActive);
};
return (
<div
className={isActive ? 'your_className': null}
onClick={toggleClass}
>
<p>{props.text}</p>
</div>
);
}
From the mpdf site: "mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF, with a number of enhancements."
mpdf is superior to FPDF for language handling and UTF-8 support. For CJK support it not only supports font embedding, but font subsetting (so your CJK PDFs are not oversized). TCPDF and FPDF have nothing on the UTF-8 and Font support of mpdf. It even comes with some open source fonts as of version 5.0.
mylist = [1,2,3]
def multiple_appends(listname, *element):
listname.extend(element)
multiple_appends(mylist, 4, 5, "string", False)
print(mylist)
OUTPUT:
[1, 2, 3, 4, 5, 'string', False]
The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.
If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".
see Bootstrap 3 docs: http://getbootstrap.com/css/#grid
For Java 1.8 and higher you must set -Djdk.http.auth.tunneling.disabledSchemes=
to make proxies with Basic Authorization working with https.
You can use the built in OnSelecting parameter of asp:SqlDataSource
Example: [.aspx file]
<asp:SqlDataSource ID="SqldsExample" runat="server"
SelectCommand="SELECT [SomeColumn], [AnotherColumn]
FROM [SomeTable]
WHERE [Dynamic_Variable_Column] = @DynamicVariable"
OnSelecting="SqldsExample_Selecting">
<SelectParameters>
<asp:Parameter Name="DynamicVariable" Type="String"/>
</SelectParameters>
Then in your code behind implement your OnSelecting method: [.aspx.cs]
protected void SqldsExample_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["@DynamicVariable"].Value = (whatever value you want);
}
You can also use this for the other types of DB operations just implement your own methods:
OnInserting="SqldsExample_Inserting"
OnUpdating="SqldsExample_Updating"
OnDeleting="SqldsExample_Deleting"
One script to rule them all: this combines truncate and delete commands with sp_MSforeachtable so that you can avoid dropping and recreating constraints - just specify the tables that need to be deleted rather than truncated and for my purposes I have included an extra schema filter for good measure (tested in 2008r2)
declare @schema nvarchar(max) = 'and Schema_Id=Schema_id(''Value'')'
declare @deletiontables nvarchar(max) = '(''TableA'',''TableB'')'
declare @truncateclause nvarchar(max) = @schema + ' and o.Name not in ' + + @deletiontables;
declare @deleteclause nvarchar(max) = @schema + ' and o.Name in ' + @deletiontables;
exec sp_MSforeachtable 'alter table ? nocheck constraint all', @whereand=@schema
exec sp_MSforeachtable 'truncate table ?', @whereand=@truncateclause
exec sp_MSforeachtable 'delete from ?', @whereand=@deleteclause
exec sp_MSforeachtable 'alter table ? with check check constraint all', @whereand=@schema
Just passing the file object to the putobject method worked for me. If you are getting a stream, try writing it to a temp file before passing it on to S3.
amazonS3.putObject(bucketName, id,fileObject);
I am using Aws SDK v1.11.414
The answer at https://stackoverflow.com/a/35904801/2373449 helped me
My system is a bit of a mess with bash/cygwin/git/msysgit/maybe-more...
chmod
had no effect on the key, or the config
file.
Then I decided to approach it from Windows, which worked.
Properties
.Security
tab.Advanced
near the bottom.Change
, next to Owner
near the top.Check Names
, then OK
.Permission entries:
, highlight each user that isn't "My-Awesome-Username", and select Remove
. Repeat this until "My-Awesome-Username" is the only one left.Edit
below.Type:
at the top is set to Allow
, and then tick the checkbox next to Full control
.Hit OK
, Apply
, OK
, OK
.
Give it another try now...
Seems the sometimes the mock-bash can't control the file ownership. It's especially weird, as it's generated from a mock-bash script. Go figure.
@IanDevlin is correct. MDN's rules say the following:
"The HTML Header Element "" defines a page header — typically containing the logo and name of the site and possibly a horizontal menu..."
The word "possibly" there is key. It goes on to say that the header doesn't necessarily need to be a site header. For instance you could include a "header" on a pop-up modal or on other modular parts of the document where there is a header and it would be helpful for a user on a screen reader to know about it.
It terms of the implicit use of NAV you can use it anywhere there is grouped site navigation, although it's usually omitted from the "footer" section for mini-navs / important site links.
Really it comes down to personal / team choice. Decide what you and your team feel is more semantic and more important and the try to be consistent. For me, if the nav is inline with the logo and the main site's "h1" then it makes sense to put it in the "header" but if you have a different design choice then decide on a case by case basis.
Most importantly check out the docs and be sure if you choose to omit or include you understand why you are making that particular decision.
git add
adds your modified files to the queue to be committed later. Files are not committed
git commit
commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a
git push
pushes your changes to the remote repository.
This figure from this git cheat sheet gives a good idea of the work flow
git add
isn't on the figure because the suggested way to commit is the combined git commit -a
, but you can mentally add a git add
to the change block to understand the flow.
Lastly, the reason why push
is a separate command is because of git
's philosophy. git
is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push
is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
More information: man ln
/home/jake/xxx
is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:
cd /home/jake/
ln -s /home/jake/doc/test/2000/something xxx
As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.
Here's how to do it using Xerces2. A tutorial for this, here (req. signup).
Original attribution: blatantly copied from here:
import org.apache.xerces.parsers.DOMParser;
import java.io.File;
import org.w3c.dom.Document;
public class SchemaTest {
public static void main (String args[]) {
File docFile = new File("memory.xml");
try {
DOMParser parser = new DOMParser();
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setProperty(
"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
"memory.xsd");
ErrorChecker errors = new ErrorChecker();
parser.setErrorHandler(errors);
parser.parse("memory.xml");
} catch (Exception e) {
System.out.print("Problem parsing the file.");
}
}
}
Here's a less flexible alternative using unset():
$array = array(
1 => 'one',
2 => 'two',
3 => 'three'
);
$disallowed = array(1,3);
foreach($disallowed as $key){
unset($array[$key]);
}
The result of print_r($array)
being:
Array
(
[2] => two
)
This is not applicable if you want to keep the filtered values for later use but tidier, if you're certain that you don't.
The concept is very well explained by the accepted answer, but I find that the more example one sees, the better it sinks in. Here's an incremental example:
1) Boss says "get me number of items we have in stock grouped by brand"
You say: "no problem"
SELECT
BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
Result:
+--------------+---------------+
| Brand | Count |
+--------------+---------------+
| H&M | 50 |
+--------------+---------------+
| Hugo Boss | 100 |
+--------------+---------------+
| No brand | 22 |
+--------------+---------------+
2) The boss says "Now get me a list of all items, with their brand AND number of items that the respective brand has"
You may try:
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
But you get:
ORA-00979: not a GROUP BY expression
This is where the OVER (PARTITION BY BRAND)
comes in:
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID) OVER (PARTITION BY BRAND)
FROM
ITEMS;
Whic means:
COUNT(ITEM_ID)
- get the number of itemsOVER
- Over the set of rows(PARTITION BY BRAND)
- that have the same brandAnd the result is:
+--------------+---------------+----------+
| Items | Brand | Count() |
+--------------+---------------+----------+
| Item 1 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 2 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 3 | No brand | 22 |
+--------------+---------------+----------+
| Item 4 | No brand | 22 |
+--------------+---------------+----------+
| Item 5 | H&M | 50 |
+--------------+---------------+----------+
etc...
Add Microsot.ReportViewer 2010 or 2012 in prerequisite of setup project then it first install Report Viewer if it's not present in "C:\Windows\assembly\GAC_MSIL..." and after installing, it installs set up project
There is one case when you do it, with while
-loops.
When reading files, you usualy do like this:
void readFile(String pathToFile) {
// Create a FileInputStream object
FileInputStream fileIn = null;
try {
// Create the FileInputStream
fileIn = new FileInputStream(pathToFile);
// Create a variable to store the current line's text in
String currentLine;
// While the file has lines left, read the next line,
// store it in the variable and do whatever is in the loop
while((currentLine = in.readLine()) != null) {
// Print out the current line in the console
// (you can do whatever you want with the line. this is just an example)
System.out.println(currentLine);
}
} catch(IOException e) {
// Handle exception
} finally {
try {
// Close the FileInputStream
fileIn.close();
} catch(IOException e) {
// Handle exception
}
}
}
Look at the while
-loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if
-statement, but I guess a while loop can be included in your question as well.
The reason to this is that when using a FileInputStream
, every time you call FileInputStream.readLine()
, it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != null
without assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null
, and then called it from inside of the loop too, you would only get every second line.
Hope you understand, and good luck!
binascii methodes are easier by the way
>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'
Hope it helps. :)
Here's an example.
In CSS (used to style HTML pages), if you want an image element to be 100 pixels high and 100 pixels wide, you simply "declare" that that's what you want as follows:
#myImageId {
height: 100px;
width: 100px;
}
You can consider CSS a declarative "style sheet" language.
The browser engine that reads and interprets this CSS is free to make the image appear this tall and this wide however it wants. Different browser engines (e.g., the engine for IE, the engine for Chrome) will implement this task differently.
Their unique implementations are, of course, NOT written in a declarative language but in a procedural one like Assembly, C, C++, Java, JavaScript, or Python. That code is a bunch of steps to be carried out step by step (and might include function calls). It might do things like interpolate pixel values, and render on the screen.
Try with regex \d
:
$words = preg_replace('/\d/', '', $words );
\d
is an equivalent for [0-9]
which is an equivalent for numbers range from 0
to 9
.
In case anybody else comes across this problem, as I just have, the answer is to wrap the content which you want to collapse inside a div
and collapse the wrapper div rather than the content itself.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="form-group">_x000D_
<a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne" class="btn btn-primary">+ addInfo</a>_x000D_
<div id="collapseOne" class="collapse">_x000D_
<textarea class="form-control" rows="4"></textarea>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<a for="collapseTwo" data-toggle="collapse" href="#collapseTwo" aria-expanded="true" aria-controls="collapseOne" class="btn btn-info">+ subtitle</a>_x000D_
<input type="text" class="form-control collapse" id="collapseTwo">_x000D_
</div>
_x000D_
Whatever Apple ships as the default gcc in xcode (4.2.1 on 10.6, 4.0.1 before) is well tested (and maintained) by the apple guys and the "standard" to build software with on OS X. Everything else is not, so think twice if you want to develop software, or be gcc/OS X beta tester.
You can try Guava's TreeMultiSet.
Multiset<Integer> ms=TreeMultiset.create(Arrays.asList(1,2,3,1,1,-1,2,4,5,100));
System.out.println(ms);
update TABLE_1 a set COLUMN_1 = (select COLUMN_2 from TABLE_1 b where a.ID = b.ID)
It is actually far easier to add an id to the label in the form itself, for example:
<label for="firstName" id="firstNameLabel">FirstName:</label>
<input type="text" id="firstName" name="firstName" class="input_Field"
pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
title="Alphabetic, Space, Dash Only, 2-25 Characters Long"
autocomplete="on" required
/>
Then, you can simply use something like this:
if (myvariableforpagelang == 'es') {
// set field label to spanish
document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
// set field tooltip (title to spanish
document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
}
The javascript does have to be in a body onload function to work.
Just a thought, works beautifully for me.
Let’s take a simple vector class:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?
def length(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
What should it look like when we were to define it as a global method/function?
def length_global(vector):
return math.sqrt(vector.x ** 2 + vector.y ** 2)
So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a length
method for our Vector
class, we could do this:
Vector.length_new = length_global
v = Vector(3, 4)
print(v.length_new()) # 5.0
This works because the first parameter of length_global
, can be re-used as the self
parameter in length_new
. This would not be possible without an explicit self
.
Another way of understanding the need for the explicit self
is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like
v_instance.length()
is internally transformed to
Vector.length(v_instance)
it is easy to see where the self
fits in. You don't actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.
If you want to consider null values equality too, try the following
select column1, column2,
case
when column1 is NULL and column2 is NULL then 'true'
when column1=column2 then 'true'
else 'false'
end
from table;
if you want to current script filename as your title tag
include the function in your project
function setTitle($requestUri)
{
$explodeRequestUri = explode("/", $requestUri);
$currentFileName = end($explodeRequestUri);
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $currentFileName);
$explodeCurrentFileName = explode("-", $withoutExt);
foreach ($explodeCurrentFileName as $curFileValue)
{
$fileArrayName[] = ucfirst($curFileValue);
}
echo implode(" ", $fileArrayName);
}
and in your html include the function script and replace your title tag with this
<title>Your Project Name -
<?php setTitle($_SERVER['REQUEST_URI']); ?>
</title>
it works on php7 and above but i dont have any idea about php 5.* Hope it helps
Temporarily show Menu Bar on ATOM:
Press ALT
Key to make the Menu bar appear but it is not permanent.
Always display the Menu Bar on ATOM:
To make the change permanent, press ALT + V
and then select Toggle Menu Bar
option from the "View" drop-down down.
[Tested on ATOM running on Ubuntu 16.04]
<html>
<head>
<style>
input[type=text] {
width: 50%;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 16px;
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
padding: 12px 20px 12px 40px;
}
</style>
</head>
<body>
<p>Input with icon:</p>
<form>
<input type="text" name="search" placeholder="Search..">
</form>
</body>
</html>
First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.
There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:
Using these mocks, you could test things like
What happens if username is not in the request?
What happens if username is in the request?
etc
You could then do stuff like:
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class MyServletTest {
private MyServlet servlet;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
public void setUp() {
servlet = new MyServlet();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
@Test
public void correctUsernameInRequest() throws ServletException, IOException {
request.addParameter("username", "scott");
request.addParameter("password", "tiger");
servlet.doPost(request, response);
assertEquals("text/html", response.getContentType());
// ... etc
}
}
You can define a getter on Array.prototype
:
if (!Array.prototype.hasOwnProperty("last")) {_x000D_
Object.defineProperty(Array.prototype, "last", {_x000D_
get() {_x000D_
return this[this.length - 1];_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
console.log([9, 8, 7, 6].last); // => 6
_x000D_
As you can see, access doesn't look like a function call; the getter function is called internally.
This seems like the simplest solution that I've found to retrieve the last value in an ever-expanding column:
=INDEX(A:A,COUNTA(A:A),1)
Try one of below options.
For 32 bit JVM:
jmap -dump:format=b,file=<heap_dump_filename> <pid>
For 64 bit JVM (explicitly quoting):
jmap -J-d64 -dump:format=b,file=<heap_dump_filename> <pid>
For 64 bit JVM with G1GC algorithm in VM parameters (Only live objects heap is generated with G1GC algorithm):
jmap -J-d64 -dump:live,format=b,file=<heap_dump_filename> <pid>
Related SE question: Java heap dump error with jmap command : Premature EOF
Have a look at various options of jmap
at this article
You can definetely build your code from Vim, that's what the :make
command does.
However, you need to go through the basics first : type vimtutor
in your terminal and follow the instructions to the end.
After you have completed it a few times, open an existing (non-important) text file and try out all the things you learned from vimtutor
: entering/leaving insert mode, undoing changes, quitting/saving, yanking/putting, moving and so on.
For a while you won't be productive at all with Vim and will probably be tempted to go back to your previous IDE/editor. Do that, but keep up with Vim a little bit every day. You'll probably be stopped by very weird and unexpected things but it will happen less and less.
In a few months you'll find yourself hitting o
, v
and i
all the time in every textfield everywhere.
Have fun!
Microsoft has a tool just for this purpose: Microsoft Expression Web. There's a free version with a bunch of FrontPage/Dreamweaver-like garbage that nobody wants. What's important is that it has a great browser testing feature. I'm running Windows 8.1 Pro (final release, not preview) with Internet Explorer 11. I get these local browsers:
Then I get a Remote Browsers (Beta) option. I'm supposed to sign up with a valid e-mail, but there's an error communicating with the server. Oh well.
Firefox used to be supported, but I don't see it now. Might be hiding.
I can compare side-by-side between browser versions. I can also compare with an image, or apparently, a PSD file (no idea how well that works). InDesign would be nice, but that's probably asking for too much.
I have the full version of Expression partially installed as well due to Visual Studio Ultimate being on the same computer, so I'd appreciate someone confirming in a comment that my free installation isn't automatically upgrading.
Update: Looks like the online service was discontinued, but local browsers are still supported. You can also download just SuperPreview, without the editor garbage. If you want the full IDE, the latest version is Microsoft Expression Web 4 (Free Version). Here's the official list of supported browsers. IE6 seems to give an error on Windows 8.1, but IE7 works.
Update 2014-12-09: Microsoft has pretty much given up on this. Don't expect it to work well.
pip install django-cors-headers
and then add it to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
'http://localhost:3030',
]
more details: https://github.com/ottoyiu/django-cors-headers/#configuration
read the official documentation can resolve almost all problem
Try this change border-color to anything which you want
.form-control:focus {
border-color: #666666;
-webkit-box-shadow: none;
box-shadow: none;
}
var Test = (from row in Dataset1.Tables[0].AsEnumerable()
select row.Field<string>("attribute1_name") + row.Field<int>("attribute2_name")).Distinct();
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
Yes, it's possible, the syntax is curl [protocol://]<host>[:port]
, for example:
curl example.com:1234
If you're using Bash, you can also use pseudo-device /dev
files to open a TCP connection, e.g.:
exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.
See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
I have improved the function of shog9`s to handle array values
function encodeQueryData(data) {
const ret = [];
for (let d in data) {
if (typeof data[d] === 'object' || typeof data[d] === 'array') {
for (let arrD in data[d]) {
ret.push(`${encodeURIComponent(d)}[]=${encodeURIComponent(data[d][arrD])}`)
}
} else if (typeof data[d] === 'null' || typeof data[d] === 'undefined') {
ret.push(encodeURIComponent(d))
} else {
ret.push(`${encodeURIComponent(d)}=${encodeURIComponent(data[d])}`)
}
}
return ret.join('&');
}
let data = {
user: 'Mark'
fruits: ['apple', 'banana']
}
encodeQueryData(data) // user=Mark&fruits[]=apple&fruits[]=banana