Having tried Cem Catikkas' solution using reflection for Java, I'd have to say his was a more elegant solution than I have described here. However, if you're looking for an alternative to using reflection, and have access to the source you're testing, this will still be an option.
There is possible merit in testing private methods of a class, particularly with test-driven development, where you would like to design small tests before you write any code.
Creating a test with access to private members and methods can test areas of code which are difficult to target specifically with access only to public methods. If a public method has several steps involved, it can consist of several private methods, which can then be tested individually.
Advantages:
Disadvantages:
However, if continuous testing requires this method, it may be a signal that the private methods should be extracted, which could be tested in the traditional, public way.
Here is a convoluted example of how this would work:
// Import statements and package declarations
public class ClassToTest
{
private int decrement(int toDecrement) {
toDecrement--;
return toDecrement;
}
// Constructor and the rest of the class
public static class StaticInnerTest extends TestCase
{
public StaticInnerTest(){
super();
}
public void testDecrement(){
int number = 10;
ClassToTest toTest= new ClassToTest();
int decremented = toTest.decrement(number);
assertEquals(9, decremented);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(StaticInnerTest.class);
}
}
}
The inner class would be compiled to ClassToTest$StaticInnerTest
.
See also: Java Tip 106: Static inner classes for fun and profit
Project -> Clean seemed to work for me on on JRE 8
You're going to want to add Python to your Path Environment Variable in this way. Go to:
PYTHONPATH
and Path
. Here is a paste of what my variables look like:PYTHONPATH
C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts
Path
C:\Program Files\MySQL\MySQL Utilities 1.3.5\;C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts
Your Path's might be different, so please adjust them, but this configuration works for me and you should be able to run MySQL after making these changes.
Try this:
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
For Windows you could use msvcrt
like this:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print(key) # just to show the result
I had a similar use case, except I wanted to checkout only the commit for a tag and prune the directories. Using --depth 1
makes it really sparse and can really speed things up.
mkdir myrepo
cd myrepo
git init
git config core.sparseCheckout true
git remote add origin <url> # Note: no -f option
echo "path/within_repo/to/subdir/" > .git/info/sparse-checkout
git fetch --depth 1 origin tag <tagname>
git checkout <tagname>
Try this, it will convert True into 1 and False into 0:
data.frame$column.name.num <- as.numeric(data.frame$column.name)
Then you can convert into factor if you want:
data.frame$column.name.num.factor <- as .factor(data.frame$column.name.num)
BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature
Text is used to store large string.
Use @JsonCreator annotation, create method getType(), is serialize with toString or object working
{"ATIVO"}
or
{"type": "ATIVO", "descricao": "Ativo"}
...
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SituacaoUsuario {
ATIVO("Ativo"),
PENDENTE_VALIDACAO("Pendente de Validação"),
INATIVO("Inativo"),
BLOQUEADO("Bloqueado"),
/**
* Usuarios cadastrados pelos clientes que não possuem acesso a aplicacao,
* caso venham a se cadastrar este status deve ser alterado
*/
NAO_REGISTRADO("Não Registrado");
private SituacaoUsuario(String descricao) {
this.descricao = descricao;
}
private String descricao;
public String getDescricao() {
return descricao;
}
// TODO - Adicionar metodos dinamicamente
public String getType() {
return this.toString();
}
public String getPropertieKey() {
StringBuilder sb = new StringBuilder("enum.");
sb.append(this.getClass().getName()).append(".");
sb.append(toString());
return sb.toString().toLowerCase();
}
@JsonCreator
public static SituacaoUsuario fromObject(JsonNode node) {
String type = null;
if (node.getNodeType().equals(JsonNodeType.STRING)) {
type = node.asText();
} else {
if (!node.has("type")) {
throw new IllegalArgumentException();
}
type = node.get("type").asText();
}
return valueOf(type);
}
}
This is what I did on windows.
openssl x509 -outform der -in yourPemFilename.pem -out certfileOutName.crt
openssl rsa -in yourPemFilename.pem -out keyfileOutName.key
<string.h>
is the old C header. C++ provides <string>
, and then it should be referred to as std::string
.
These values vary from person to person, especially for people who are colorblind.
You need to specify the schema/owner (dbo by default) as part of the reference. Also, it would be preferable to use the newer (ANSI-92) join style.
select foo.id
from databaseserver1.db1.dbo.table1 foo
inner join databaseserver2.db1.dbo.table1 bar
on foo.name = bar.name
I have tried the below method and it works for such JSON format reading with Jackson.
Use the already suggested solution of: annotating getter with @JsonProperty("wrapper")
Your wrapper class
public Class Wrapper{
private List<Student> students;
//getters & setters here
}
My Suggestion of wrapper class
public Class Wrapper{
private StudentHelper students;
//getters & setters here
// Annotate getter
@JsonProperty("wrapper")
StudentHelper getStudents() {
return students;
}
}
public class StudentHelper {
@JsonProperty("Student")
public List<Student> students;
//CTOR, getters and setters
//NOTE: If students is private annotate getter with the annotation @JsonProperty("Student")
}
This would however give you the output of the format:
{"wrapper":{"student":[{"id":13,"name":Fred}]}}
Also for more information refer to https://github.com/FasterXML/jackson-annotations
Hope this helps
You can't stretch a background image (until CSS 3).
You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.
table {_x000D_
width: 230px;_x000D_
}_x000D_
_x000D_
.style1 {_x000D_
text-align: center;_x000D_
height: 35px;_x000D_
}_x000D_
_x000D_
.bg {_x000D_
position: relative;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg img {_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg .linkcontainer {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
<tr>_x000D_
<td class="style1">_x000D_
<div class="bg">_x000D_
<img src="http://placekitten.com/20/20" alt="" />_x000D_
<div class="linkcontainer">_x000D_
<a class="link" href="#">_x000D_
<span>Answer</span>_x000D_
</a>_x000D_
</div>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Try perl -MCPAN -e "upgrade /(.\*)/"
. It works fine for me.
You can add and remove classes with jQuery like so:
$(".first").addClass("second")
// remove a class
$(".first").removeClass("second")
By the way you can set multiple classes in your markup right away separated with a whitespace
<div class="second first"></div>
From the reference docs of Comparable.compareTo(T):
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
In short:
this.compareTo(that)
returns
where the implementation of this method determines the actual semantics of <
>
and ==
(I don't mean ==
in the sense of java's object identity operator)
"abc".compareTo("def")
will yield something smaller than 0 as abc
is alphabetically before def
.
Integer.valueOf(2).compareTo(Integer.valueOf(1))
will yield something larger than 0 because 2 is larger than 1.
Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.
Note: you should read at least one of the following:
Warning: you should never rely on the return values of compareTo being -1
, 0
and 1
. You should always test for x < 0
, x == 0
, x > 0
, respectively.
Here is a complete script to implement a solution:
create Procedure [dev].DeleteTablesFromSchema
(
@schemaName varchar(500)
)
As
begin
declare @constraintSchemaName nvarchar(128), @constraintTableName nvarchar(128), @constraintName nvarchar(128)
declare @sql nvarchar(max)
-- delete FK first
declare cur1 cursor for
select distinct
CASE WHEN t2.[object_id] is NOT NULL THEN s2.name ELSE s.name END as SchemaName,
CASE WHEN t2.[object_id] is NOT NULL THEN t2.name ELSE t.name END as TableName,
CASE WHEN t2.[object_id] is NOT NULL THEN OBJECT_NAME(d2.constraint_object_id) ELSE OBJECT_NAME(d.constraint_object_id) END as ConstraintName
from sys.objects t
inner join sys.schemas s
on t.[schema_id] = s.[schema_id]
left join sys.foreign_key_columns d
on d.parent_object_id = t.[object_id]
left join sys.foreign_key_columns d2
on d2.referenced_object_id = t.[object_id]
inner join sys.objects t2
on d2.parent_object_id = t2.[object_id]
inner join sys.schemas s2
on t2.[schema_id] = s2.[schema_id]
WHERE t.[type]='U'
AND t2.[type]='U'
AND t.is_ms_shipped = 0
AND t2.is_ms_shipped = 0
AND s.Name=@schemaName
open cur1
fetch next from cur1 into @constraintSchemaName, @constraintTableName, @constraintName
while @@fetch_status = 0
BEGIN
set @sql ='ALTER TABLE ' + @constraintSchemaName + '.' + @constraintTableName+' DROP CONSTRAINT '+@constraintName+';'
exec(@sql)
fetch next from cur1 into @constraintSchemaName, @constraintTableName, @constraintName
END
close cur1
deallocate cur1
DECLARE @tableName nvarchar(128)
declare cur2 cursor for
select s.Name, p.Name
from sys.objects p
INNER JOIN sys.schemas s ON p.[schema_id] = s.[schema_id]
WHERE p.[type]='U' and is_ms_shipped = 0
AND s.Name=@schemaName
ORDER BY s.Name, p.Name
open cur2
fetch next from cur2 into @schemaName,@tableName
while @@fetch_status = 0
begin
set @sql ='DROP TABLE ' + @schemaName + '.' + @tableName
exec(@sql)
fetch next from cur2 into @schemaName,@tableName
end
close cur2
deallocate cur2
end
go
Yes.
I use uncompyle6 decompile (even support latest Python 3.8.0):
uncompyle6 utils.cpython-38.pyc > utils.py
and the origin python and decompiled python comparing look like this:
so you can see, ALMOST same, decompile effect is VERY GOOD.
In tensorflow you create graphs and pass values to that graph. Graph does all the hardwork and generate the output based on the configuration that you have made in the graph. Now When you pass values to the graph then first you need to create a tensorflow session.
tf.Session()
Once session is initialized then you are supposed to use that session because all the variables and settings are now part of the session. So, there are two ways to pass external values to the graph so that graph accepts them. One is to call the .run() while you are using the session being executed.
Other way which is basically a shortcut to this is to use .eval(). I said shortcut because the full form of .eval() is
tf.get_default_session().run(values)
You can check that yourself.
At the place of values.eval()
run tf.get_default_session().run(values)
. You must get the same behavior.
what eval is doing is using the default session and then executing run().
Arabic, Egypt (ar_EG)
Arabic, Israel (ar_IL)
Bulgarian, Bulgaria (bg_BG)
Catalan, Spain (ca_ES)
Czech, Czech Republic (cs_CZ)
Danish, Denmark(da_DK)
German, Austria (de_AT)
German, Switzerland (de_CH)
German, Germany (de_DE)
German, Liechtenstein (de_LI)
Greek, Greece (el_GR)
English, Australia (en_AU)
English, Canada (en_CA)
English, Britain (en_GB)
English, Ireland (en_IE)
English, India (en_IN)
English, New Zealand (en_NZ)
English, Singapore(en_SG)
English, US (en_US)
English, South Africa (en_ZA)
Spanish (es_ES)
Spanish, US (es_US)
Finnish, Finland (fi_FI)
French, Belgium (fr_BE)
French, Canada (fr_CA)
French, Switzerland (fr_CH)
French, France (fr_FR)
Hebrew, Israel (he_IL)
Hindi, India (hi_IN)
Croatian, Croatia (hr_HR)
Hungarian, Hungary (hu_HU)
Indonesian, Indonesia (id_ID)
Italian, Switzerland (it_CH)
Italian, Italy (it_IT)
Japanese (ja_JP)
Korean (ko_KR)
Lithuanian, Lithuania (lt_LT)
Latvian, Latvia (lv_LV)
Norwegian bokmål, Norway (nb_NO)
Dutch, Belgium (nl_BE)
Dutch, Netherlands (nl_NL)
Polish (pl_PL)
Portuguese, Brazil (pt_BR)
Portuguese, Portugal (pt_PT)
Romanian, Romania (ro_RO)
Russian (ru_RU)
Slovak, Slovakia (sk_SK)
Slovenian, Slovenia (sl_SI)
Serbian (sr_RS)
Swedish, Sweden (sv_SE)
Thai, Thailand (th_TH)
Tagalog, Philippines (tl_PH)
Turkish, Turkey (tr_TR)
Ukrainian, Ukraine (uk_UA)
Vietnamese, Vietnam (vi_VN)
Chinese, PRC (zh_CN)
Chinese, Taiwan (zh_TW)
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
ORACLE/PLSQL:
NVL FUNCTION
SELECT NVL(SUM(Price), 0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
This SQL statement would return 0
if the SUM(Price)
returned a null value. Otherwise, it would return the SUM(Price)
value.
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
With naming conventions, it's usually safe to say "just pick one and stick to it", which makes sense.
However, after having to explain REST to lots of people, representing endpoints as paths on a file system is the most expressive way of doing it.
It is stateless (files either exist or don't exist), hierarchical, simple, and familiar - you already knows how to access static files, whether locally or via http.
And within that context, linguistic rules can only get you as far as the following:
A directory can contain multiple files and/or sub-directories, and therefore its name should be in plural form.
And I like that.
Although, on the other hand - it's your directory, you can name it "a-resource-or-multiple-resources" if that's what you want. That's not really the important thing.
What's important is that if you put a file named "123" under a directory named "resourceS" (resulting in /resourceS/123
), you cannot then expect it to be accessible via /resource/123
.
Don't try to make it smarter than it has to be - changing from plural to singluar depending on the count of resources you're currently accessing may be aesthetically pleasing to some, but it's not effective and it doesn't make sense in a hierarchical system.
Note: Technically, you can make "symbolic links", so that /resources/123
can also be accessed via /resource/123
, but the former still has to exist!
URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".
RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).
In Java, the correct way to build a URL is with the URI
class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString()
method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI
object using the single-string constructor and then use the accessor methods (such as getPath()
) to retrieve the decoded components.
Don't use the URLEncoder
class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder
. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).
I had the same problem as one of my <div>'s had the margin set by the browser. It was quite annoying but then I figured out as most of the people said, it's a markup error.
I went back and checked my <head> section and my CSS link was like below:
<link rel="stylesheet" href="ex.css">
I included type
in it and made it like below:
<link rel="stylesheet" type="text/css" href="ex.css">
My problem was solved.
My favorite method uses cv2.copyMakeBorder with no border, like so.
copy = cv2.copyMakeBorder(original,0,0,0,0,cv2.BORDER_REPLICATE)
In your custom view pager adapter, override those methods in ViewPager
.
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
And to enable, just return each super
method:
super.onInterceptTouchEvent(event)
and super.onTouchEvent(event)
.
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
No, there is no type called "byte
" in C++. What you want instead is unsigned char
(or, if you need exactly 8 bits, uint8_t
from <cstdint>
, since C++11). Note that char
is not necessarily an accurate alternative, as it means signed char
on some compilers and unsigned char
on others.
The XMLHttpRequest.timeout
property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0
, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests
requests, used in a document environment or it will throw an InvalidAccessError
exception. You may not use a timeout for synchronous requests with an owning window.
IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.
More info can be found here.
I have used the above option to .hide entries from 2 drops down boxes (first you select the city, then you selected the area within that city). It works fine on screen but the hidden options are still selectable via keyboard inputs.
This code works for iOS 5 (it worked for me):
In the head tag:
<script type="text/javascript">
function OpenLink(theLink){
window.location.href = theLink.href;
}
</script>
In the link that you want to be opened in the same window:
<a href="(your website here)" onclick="OpenLink(this); return false"> Link </a>
I got this code from this comment: iphone web app meta tags
In Python 3.9, a new removeprefix
method is being added:
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
The Laravel way
Try this:
$foo = \File::extension($filename);
For all smartphones and large screens use this format of media query
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
yes, by the concept of pointer you can do it like this for an int variable:
int *a;
int b=0;
a=NULL; // or a=&b; for giving the value of b to a
if(a==NULL)
printf("NULL");
else
printf(*a);
it is very simple and straitforward. it worked for me in Arduino IDE.
I had the same issue on Windows 10 where I tried to SSH into a Vagrant box. This seems like a bug in the old OpenSSH version. What worked for me:
(Note the ".exe" if you are using Powershell)
You might see something like:
C:\Windows\System32\OpenSSH\ssh.exe
C:\Program Files\OpenSSH\bin\ssh.exe
C:\opscode\chefdk\embedded\git\usr\bin\ssh.exe
Note that in the above example the latest OpenSSH is second in the path so it won't execute.
To change the order:
As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.
The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.
In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments.
FirstFragment.java has a orange background layout, SecondFragment.java has a green background layout and ThirdFragment.java has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.
Also be aware that I am using the support-library's Fragment: android.support.v4.app.Fragment
MainActivity.java (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the android.support.v4
package.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
@Override
public int getCount() {
return 5;
}
}
}
activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
The Fragment classes, FirstFragment.java import android.support.v4.app.Fragment;
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
first_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_orange_dark" >
<TextView
android:id="@+id/tvFragFirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26dp"
android:text="TextView" />
</RelativeLayout>
SecondFragment.java
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
second_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_green_dark" >
<TextView
android:id="@+id/tvFragSecond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26dp"
android:text="TextView" />
</RelativeLayout>
ThirdFragment.java
public class ThirdFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragThird);
tv.setText(getArguments().getString("msg"));
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
third_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_light" >
<TextView
android:id="@+id/tvFragThird"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26dp"
android:text="TextView" />
</RelativeLayout>
The end result is the following:
The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.
Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.
Last but not least:
I would recommend that you use an empty constructor in each of your Fragment classes.
Instead of handing over potential parameters via constructor, use the newInstance(...)
method and the Bundle
for handing over parameters.
This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles
attached to Intents
.
You can use below statement to write the contents of dataframe in CSV format
df.write.csv("/data/home/csv")
If you need to write the whole dataframe into a single CSV file, then use
df.coalesce(1).write.csv("/data/home/sample.csv")
For spark 1.x, you can use spark-csv to write the results into CSV files
Below scala snippet would help
import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.write.format("com.databricks.spark.csv").save("/data/home/csv")
To write the contents into a single file
import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.coalesce(1).write.format("com.databricks.spark.csv").save("/data/home/sample.csv")
With the below code you have to set PermissionLevel=External on your project properties before you deploy, and change the database to trust external code (be sure to read elsewhere about security risks and alternatives [like certificates]) by running "ALTER DATABASE database_name SET TRUSTWORTHY ON".
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Server;
[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined,
MaxByteSize=8000,
IsInvariantToDuplicates=true,
IsInvariantToNulls=true,
IsInvariantToOrder=true,
IsNullIfEmpty=true)]
public struct CommaDelimit : IBinarySerialize
{
[Serializable]
private class StringList : List<string>
{ }
private StringList List;
public void Init()
{
this.List = new StringList();
}
public void Accumulate(SqlString value)
{
if (!value.IsNull)
this.Add(value.Value);
}
private void Add(string value)
{
if (!this.List.Contains(value))
this.List.Add(value);
}
public void Merge(CommaDelimit group)
{
foreach (string s in group.List)
{
this.Add(s);
}
}
void IBinarySerialize.Read(BinaryReader reader)
{
IFormatter formatter = new BinaryFormatter();
this.List = (StringList)formatter.Deserialize(reader.BaseStream);
}
public SqlString Terminate()
{
if (this.List.Count == 0)
return SqlString.Null;
const string Separator = ", ";
this.List.Sort();
return new SqlString(String.Join(Separator, this.List.ToArray()));
}
void IBinarySerialize.Write(BinaryWriter writer)
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(writer.BaseStream, this.List);
}
}
I've tested this using a query that looks like:
SELECT
dbo.CommaDelimit(X.value) [delimited]
FROM
(
SELECT 'D' [value]
UNION ALL SELECT 'B' [value]
UNION ALL SELECT 'B' [value] -- intentional duplicate
UNION ALL SELECT 'A' [value]
UNION ALL SELECT 'C' [value]
) X
And yields: A, B, C, D
Simple way to save multiple files
cshtml
@using (Html.BeginForm("Index","Home",FormMethod.Post,new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Files:</label>
<input type="file" multiple name="files" id="files" /><br><br>
<input type="submit" value="Upload Files" />
<br><br>
@ViewBag.Message
}
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
}
return View();
}
Display display = getActivity().getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Log.d("Tag", "Getting Width >> " + screenWidth);
Log.d("Tag", "Getting Height >> " + screenHeight);
This worked properly in my application
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
Use the network byte order (big endian), which is the same as Java uses anyway. See man htons for the different translators in C.
We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.
If you really want to check for all those special characters, it's easier to use a regular expression:
var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('Your search string contains illegal characters.');
}
The above will only allow strings consisting entirely of characters on the ranges a-z
, A-Z
, 0-9
, plus the hyphen an space characters. A string containing any other character will cause the alert
.
I had this problem while using QT 5.6, Anaconda 4.3.23, python 3.5.2 and pyinstaller 3.3. I had created a python program with an interface developed using QTcreator, but had to deploy it to other computers, therefore I needed to make an executable, using pyinstaller.
I've found that the problem was solved on my computer if I set the following environment variables:
QT_QPA_PLATFORM_PLUGIN_PATH: %QTDIR%\plugins\platforms\
QTDIR: C:\Miniconda3\pkgs\qt-5.6.2-vc14_3\Library
But this solution only worked on my PC that had conda and qt installed in those folders.
To solve this and make the executable work on any computer, I've had to edit the ".spec" (file first generated by pyinstaller) to include the following line:
datas=[( 'C:\Miniconda3\pkgs\qt-5.6.2-vc14_3\Library\plugins\platforms*.dll', 'platforms' ),]
This solution is based on the answers of Jim G. and CrippledTable
Commit hash
git show -s --format=%H
Abbreviated commit hash
git show -s --format=%h
Click here for more git show
examples.
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
Try this batch :
@echo off
Title List of connected external devices by Hackoo
Mode con cols=100 lines=20 & Color 9E
wmic LOGICALDISK where driveType=2 get deviceID > wmic.txt
for /f "skip=1" %%b IN ('type wmic.txt') DO (echo %%b & pause & Dir %%b)
Del wmic.txt
pause
Here are some utility functions that allow you to determine if two files (or two streams) contain identical data.
I have provided a "fast" version that is multi-threaded as it compares byte arrays (each buffer filled from what's been read in each file) in different threads using Tasks.
As expected, it's much faster (around 3x faster) but it consumes more CPU (because it's multi threaded) and more memory (because it needs two byte array buffers per comparison thread).
public static bool AreFilesIdenticalFast(string path1, string path2)
{
return AreFilesIdentical(path1, path2, AreStreamsIdenticalFast);
}
public static bool AreFilesIdentical(string path1, string path2)
{
return AreFilesIdentical(path1, path2, AreStreamsIdentical);
}
public static bool AreFilesIdentical(string path1, string path2, Func<Stream, Stream, bool> areStreamsIdentical)
{
if (path1 == null)
throw new ArgumentNullException(nameof(path1));
if (path2 == null)
throw new ArgumentNullException(nameof(path2));
if (areStreamsIdentical == null)
throw new ArgumentNullException(nameof(path2));
if (!File.Exists(path1) || !File.Exists(path2))
return false;
using (var thisFile = new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var valueFile = new FileStream(path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (valueFile.Length != thisFile.Length)
return false;
if (!areStreamsIdentical(thisFile, valueFile))
return false;
}
}
return true;
}
public static bool AreStreamsIdenticalFast(Stream stream1, Stream stream2)
{
if (stream1 == null)
throw new ArgumentNullException(nameof(stream1));
if (stream2 == null)
throw new ArgumentNullException(nameof(stream2));
const int bufsize = 80000; // 80000 is below LOH (85000)
var tasks = new List<Task<bool>>();
do
{
// consumes more memory (two buffers for each tasks)
var buffer1 = new byte[bufsize];
var buffer2 = new byte[bufsize];
int read1 = stream1.Read(buffer1, 0, buffer1.Length);
if (read1 == 0)
{
int read3 = stream2.Read(buffer2, 0, 1);
if (read3 != 0) // not eof
return false;
break;
}
// both stream read could return different counts
int read2 = 0;
do
{
int read3 = stream2.Read(buffer2, read2, read1 - read2);
if (read3 == 0)
return false;
read2 += read3;
}
while (read2 < read1);
// consumes more cpu
var task = Task.Run(() =>
{
return IsSame(buffer1, buffer2);
});
tasks.Add(task);
}
while (true);
Task.WaitAll(tasks.ToArray());
return !tasks.Any(t => !t.Result);
}
public static bool AreStreamsIdentical(Stream stream1, Stream stream2)
{
if (stream1 == null)
throw new ArgumentNullException(nameof(stream1));
if (stream2 == null)
throw new ArgumentNullException(nameof(stream2));
const int bufsize = 80000; // 80000 is below LOH (85000)
var buffer1 = new byte[bufsize];
var buffer2 = new byte[bufsize];
var tasks = new List<Task<bool>>();
do
{
int read1 = stream1.Read(buffer1, 0, buffer1.Length);
if (read1 == 0)
return stream2.Read(buffer2, 0, 1) == 0; // check not eof
// both stream read could return different counts
int read2 = 0;
do
{
int read3 = stream2.Read(buffer2, read2, read1 - read2);
if (read3 == 0)
return false;
read2 += read3;
}
while (read2 < read1);
if (!IsSame(buffer1, buffer2))
return false;
}
while (true);
}
public static bool IsSame(byte[] bytes1, byte[] bytes2)
{
if (bytes1 == null)
throw new ArgumentNullException(nameof(bytes1));
if (bytes2 == null)
throw new ArgumentNullException(nameof(bytes2));
if (bytes1.Length != bytes2.Length)
return false;
for (int i = 0; i < bytes1.Length; i++)
{
if (bytes1[i] != bytes2[i])
return false;
}
return true;
}
i had problem to run it and i make some changes to run it with mp3 source. here is BackfrounSoundService.java
file. consider that my mp3 file is in my sdcard in my phone .
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("service", "onCreate");
player = new MediaPlayer();
try {
player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/your file.mp3");
} catch (IOException e) {
e.printStackTrace();
}
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("service", "onStartCommand");
try {
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
I had the same problem, and it turned out I hadn't installed the library.
this link was super usefull.
I've managed to get it working using curl:
curl -u <username>:<password> https://myrepo.example/v1/repositories/<username>/<image_name>/tags
Note that image_name
should not contain user details etc. For example if you're pushing image named myrepo.example/username/x
then image_name
should be x
.
as noted here, this is what worked best for me:
sudo apt-get install python3 python3-pip python3-setuptools
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
same problem for me, original code from spring starter demo gives unknown error on line 1:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
...
Changing just the version of 2.1.6.RELEASE to 2.1.4.RELEASE fixes the problem.
In Swift, using xcode 7 (and later), you can add the following to your AppDelegate.swift file:
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
This is the what the complete method looks like:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// I added this line
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
return true
}
In the example above my item will be white. The "/255.0" is needed because it expects a value from 0 to 1. For white, I could have just used 1. But for other color you'll probably be using RGB values.
Now we can use:
sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)
In the related question you posted, we already have a way to achieve that in plain javascript, so we only need to get the js reference to the dom node we want to scroll.
The ref
attribute can be used to declare reference to html elements to make them available in vue's component methods.
Or, if the method in the component
is a handler for some UI event, and the target is related to the div you want to scroll in space, you can simply pass in the event object along with your wanted arguments, and do the scroll like scroll(event.target.nextSibling)
.
Try this
INSERT INTO dbo.DB1.TempTable
(COLUMNS)
SELECT COLUMNS_IN_SAME_ORDER FROM dbo.DB2.TempTable
This will only fail if an item in dbo.DB2.TempTable is in already in dbo.DB1.TempTable.
use from configurations must be very very easy like this :
var config = new MiniConfig("setting.conf");
config.AddOrUpdate("port", "1580");
if (config.TryGet("port", out int port)) // if config exist
{
Console.Write(port);
}
for more details see MiniConfig
Here are two methods, one sweet and simple(and conceptual), the other more formal and can be extended in a variety of situations, after having read a dataset.
Method 1: Conceptual
X2=[]
X1=[1,2,3]
X2.append(X1)
X3=[4,5,6]
X2.append(X3)
X2 thus has [[1,2,3],[4,5,6]] ie a list of lists.
Method 2 : Formal and extensible
Another elegant way to store a list as a list of lists of different numbers - which it reads from a file. (The file here has the dataset train) Train is a data-set with say 50 rows and 20 columns. ie. Train[0] gives me the 1st row of a csv file, train[1] gives me the 2nd row and so on. I am interested in separating the dataset with 50 rows as one list, except the column 0 , which is my explained variable here, so must be removed from the orignal train dataset, and then scaling up list after list- ie a list of a list. Here's the code that does that.
Note that I am reading from "1" in the inner loop since I am interested in explanatory variables only. And I re-initialize X1=[] in the other loop, else the X2.append([0:(len(train[0])-1)]) will rewrite X1 over and over again - besides it more memory efficient.
X2=[]
for j in range(0,len(train)):
X1=[]
for k in range(1,len(train[0])):
txt2=train[j][k]
X1.append(txt2)
X2.append(X1[0:(len(train[0])-1)])
You array is being allocated on the stack in this case attempt to allocate an array of the same size using alloc.
In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),
I tried running the following code
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]
fig, ax = plt.scatter(z, y)
for i, txt in enumerate(n):
ax.annotate(txt, (z[i], y[i]))
But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)
I eventually solved the error using the following code
plt.scatter(z, y)
for i, txt in enumerate(n):
plt.annotate(txt, (z[i], y[i]))
I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.
If the folder is already writable so thats not the problem.
You can also just navigate to /www/projet_etienne/app/cache/
and manualy remove the folders in there (dev, dev_new, dev_old).
Make sure to SAVE a copy of those folder somewhere to put back if this doesn't fix the problem
I know this is not the way it should be done but it worked for me a couple of times now.
Same happened to me, I had to go into Packages and re-enable Tabs and Tree-View (both part of core).
In MSVC there is a Microsoft specific keyword for that: __super
MSDN: Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.
// deriv_super.cpp
// compile with: /c
struct B1 {
void mf(int) {}
};
struct B2 {
void mf(short) {}
void mf(char) {}
};
struct D : B1, B2 {
void mf(short) {
__super::mf(1); // Calls B1::mf(int)
__super::mf('s'); // Calls B2::mf(char)
}
};
You're nesting mocking inside of mocking. You're calling getSomeList()
, which does some mocking, before you've finished the mocking for MyMainModel
. Mockito doesn't like it when you do this.
Replace
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}
with
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
List<SomeModel> someModelList = getSomeList();
Mockito.when(mainModel.getList()).thenReturn(someModelList);
}
To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.
Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when
method reads the last of these invocations off the list and records this invocation in the OngoingStubbing
object it returns.
The line
Mockito.when(mainModel.getList()).thenReturn(someModelList);
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,thenReturn
is called on the OngoingStubbing
object returned by the when
method.The thenReturn
method can then instruct the mock it received via the OngoingStubbing
method to handle any suitable call to the getList
method to return someModelList
.
In fact, as Mockito can't see your code, you can also write your mocking as follows:
mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);
This style is somewhat less clear to read, especially since in this case the null
has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.
However, the line
Mockito.when(mainModel.getList()).thenReturn(getSomeList());
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,mock
of SomeModel
is created (inside getSomeList()
),model.getName()
is called,At this point Mockito gets confused. It thought you were mocking mainModel.getList()
, but now you're telling it you want to mock the model.getName()
method. To Mockito, it looks like you're doing the following:
when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);
This looks silly to Mockito
as it can't be sure what you're doing with mainModel.getList()
.
Note that we did not get to the thenReturn
method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList()
method.
Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.
Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
You could use List inside the method and transform it to an array at the end. But i think if we talk about an max-value of 20, your code is faster.
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
List<InputProperty> ip = new List<InputProperty>();
for (int i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
update.Items = ip.ToArray();
return update;
}
A). I never have and never will trust any tool which purports to produce code without the user coding, which goes double where it's a graphical tool.
B). I've never had any problem with this with Facebook Connect. It's all still plain old JavaScript code running in a browser and undefined===undefined
wherever you are.
In short, you need to provide evidence that your object.x really really was undefined and not null or otherwise, because I believe it is impossible for what you're describing to actually be the case - no offence :) - I'd put money on the problem existing in the Tersus code.
String username = "[email protected]";
String password = "some-password";
String recipient = "[email protected]");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.from", "[email protected]");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
props.setProperty("mail.debug", "true");
Session session = Session.getInstance(props, null);
MimeMessage msg = new MimeMessage(session);
msg.setRecipients(Message.RecipientType.TO, recipient);
msg.setSubject("JavaMail hello world example");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport transport = session.getTransport("smtp");
transport.connect(username, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
document.getElementById('id1').bgColor = '#00FF00';
seems to work. I don't think .style.backgroundColor
does.
Add a Primary Key (code below)
Run the correct delete (code below)
Consider WHY you woudln't want to keep that primary key.
Assuming MSSQL or compatible:
ALTER TABLE Employee ADD EmployeeID int identity(1,1) PRIMARY KEY;
WHILE EXISTS (SELECT COUNT(*) FROM Employee GROUP BY EmpID, EmpSSN HAVING COUNT(*) > 1)
BEGIN
DELETE FROM Employee WHERE EmployeeID IN
(
SELECT MIN(EmployeeID) as [DeleteID]
FROM Employee
GROUP BY EmpID, EmpSSN
HAVING COUNT(*) > 1
)
END
<table cellpadding="pixels"cellspacing="pixels"></table>
<td align="position"valign="position"></td>
cellpadding
="length in pixels" ~ The cellpadding attribute, used in the <table>
tag, specifies how much blank space to display in between the content of each table cell and its respective border. The value is defined as a length in pixels. Hence, a cellpadding="10"
attribute-value pair will display 10 pixels of blank space on all four sides of the content of each cell in that table.
cellspacing
="length in pixels" ~ The cellspacing attribute, also used in the <table>
tag, defines how much blank space to display in between adjacent table cells and in between table cells and the table border. The value is defined as a length in pixels. Hence, a cellspacing="10"
attribute-value pair will horizontally and vertically separate all adjacent cells in the respective table by a length of 10 pixels. It will also offset all cells from the table's frame on all four sides by a length of 10 pixels.
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:
var qry = Foos.GroupJoin(
Bars.OrderByDescending(b => b.Id),
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });
Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).
Take it from someone who has tried it all three ways... just use a varchar(39)
The slightly less efficient storage far outweighs any benefit of having to convert it on insert/update and format it when showing it anywhere.
Ideally these would go in a class called "FileNaming" or maybe just rename Encode to "FileNameEncode". Note: these are not designed to handle Full Paths, just the folder and/or file names. Ideally you would Split("/") your full path first and then check the pieces. And obviously instead of a union, you could just add the "%" character to the list of chars not allowed in Windows, but I think it's more helpful/readable/factual this way. Decode() is exactly the same but switches the Replace(Uri.HexEscape(s[0]), s) "escaped" with the character.
public static List<string> urlEncodedCharacters = new List<string>
{
"/", "\\", "<", ">", ":", "\"", "|", "?", "%" //and others, but not *
};
//Since this is a superset of urlEncodedCharacters, we won't be able to only use UrlEncode() - instead we'll use HexEncode
public static List<string> specialCharactersNotAllowedInWindows = new List<string>
{
"/", "\\", "<", ">", ":", "\"", "|", "?", "*" //windows dissallowed character set
};
public static string Encode(string fileName)
{
//CheckForFullPath(fileName); // optional: make sure it's not a path?
List<string> charactersToChange = new List<string>(specialCharactersNotAllowedInWindows);
charactersToChange.AddRange(urlEncodedCharacters.
Where(x => !urlEncodedCharacters.Union(specialCharactersNotAllowedInWindows).Contains(x))); // add any non duplicates (%)
charactersToChange.ForEach(s => fileName = fileName.Replace(s, Uri.HexEscape(s[0]))); // "?" => "%3f"
return fileName;
}
Thanks @simon-tewsi for the very usefull table above!
As suggested in an earlier answer, we need to include two additional files - jquery.fileupload-process.js
and then jquery.fileupload-validate.js
However as I need to perform some additional ajax calls while adding a file, I am subscribing to the fileuploadadd
event to perform those calls. Regarding such a usage the author of this plugin suggested the following
Please have a look here: https://github.com/blueimp/jQuery-File-Upload/wiki/Options#wiki-callback-options
Adding additional event listeners via bind (or on method with jQuery 1.7+) method is the preferred option to preserve callback settings by the jQuery File Upload UI version.
Alternatively, you can also simply start the processing in your own callback, like this: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50
Using the combination of the two suggested options, the following code works perfectly for me
$fileInput.fileupload({
url: 'upload_url',
type: 'POST',
dataType: 'json',
autoUpload: false,
disableValidation: false,
maxFileSize: 1024 * 1024,
messages: {
maxFileSize: 'File exceeds maximum allowed size of 1MB',
}
});
$fileInput.on('fileuploadadd', function(evt, data) {
var $this = $(this);
var validation = data.process(function () {
return $this.fileupload('process', data);
});
validation.done(function() {
makeAjaxCall('some_other_url', { fileName: data.files[0].name, fileSizeInBytes: data.files[0].size })
.done(function(resp) {
data.formData = data.formData || {};
data.formData.someData = resp.SomeData;
data.submit();
});
});
validation.fail(function(data) {
console.log('Upload error: ' + data.files[0].error);
});
});
Probably the best cross browser solution for pdf display on web pages is to use the Mozilla PDF.js project code, it can be run as a node.js service and used as follows
<iframe style="width:100%;height:500px" src="http://www.mysite.co.uk/libs/pdfjs/web/viewer.html?file="http://www.mysite.co.uk/mypdf.pdf"></iframe>
A tutorial on how to use pdf.js can be found at this ejectamenta blog article
I think If you want some custom colors you can go to Assets.xcassets
folder, right click and select New Color Set
, once you created you color you set, give it a name to reuse it.
And you can use it just like this :
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UITextField.appearance().tintColor = UIColor(named: "YOUR-COLOR-NAME") #here
}
}
Tested on macOS 10.15 / iOS 13 / Swift 5
The __proto__
property of an object is a property that maps to the prototype
of the constructor function of the object. In other words:
instance.__proto__ === constructor.prototype // true
This is used to form the prototype
chain of an object. The prototype
chain is a lookup mechanism for properties on an object. If an object's property is accessed, JavaScript will first look on the object itself. If the property isn't found there, it will climb all the way up to protochain
until it is found (or not)
function Person (name, city) {_x000D_
this.name = name;_x000D_
}_x000D_
_x000D_
Person.prototype.age = 25;_x000D_
_x000D_
const willem = new Person('Willem');_x000D_
_x000D_
console.log(willem.__proto__ === Person.prototype); // the __proto__ property on the instance refers to the prototype of the constructor_x000D_
_x000D_
console.log(willem.age); // 25 doesn't find it at willem object but is present at prototype_x000D_
console.log(willem.__proto__.age); // now we are directly accessing the prototype of the Person function
_x000D_
Our first log results to true
, this is because as mentioned the __proto__
property of the instance created by the constructor refers to the prototype
property of the constructor. Remember, in JavaScript, functions are also Objects. Objects can have properties, and a default property of any function is one property named prototype.
Then, when this function is utilized as a constructor function, the object instantiated from it will receive a property called __proto__
. And this __proto__
property refers to the prototype
property of the constructor function (which by default every function has).
JavaScript has a mechanism when looking up properties on Objects
which is called 'prototypal inheritance', here is what it basically does:
__proto__
property. There, it checks if the property is available on the object referred to by __proto__
.__proto__
object, it will climb up the __proto__
chain, all the way up to Object
object.prototype
chain, it will return undefined
.For example:
function Person (name) {_x000D_
this.name = name;_x000D_
}_x000D_
_x000D_
let mySelf = new Person('Willem');_x000D_
_x000D_
console.log(mySelf.__proto__ === Person.prototype);_x000D_
_x000D_
console.log(mySelf.__proto__.__proto__ === Object.prototype);
_x000D_
import re
url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)
>>> print urls
['http://example.com', 'http://example2.com']
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
If your're looking to set the current datetime for a dateTime column (like i was when I googled), use this way
$table->dateTime('signed_when')->useCurrent();
Try jQuery animate()
method, ex.
$("#divid").animate({'width':perc+'%'});
You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)
<!-- Normal state. -->
<item>
<layer-list>
<item>
<shape>
<gradient
android:startColor="@color/grey_light"
android:endColor="@color/grey_dark"
android:type="linear"
android:angle="270"
android:centerColor="@color/grey_mediumtodark" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#00666666"
android:endColor="#77666666"
android:type="radial"
android:gradientRadius="200"
android:centerColor="#00666666"
android:centerX="0.5"
android:centerY="0" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
</layer-list>
</item>
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
I find this to be concise and self-documenting:
[true, false].include? foo
If using Rails or ActiveSupport, you can even do a direct query using in?
foo.in? [true, false]
Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!
Solution: Remove height: 100%
in .item-inner and add display: flex
in .item
You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.
const noGuest = 3;_x000D_
_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_
console.log(guest);_x000D_
});
_x000D_
Example:
renderPayments(noGuest) {
return Array(noGuest).fill(noGuest).map((guess, index) => {
return(
<View key={index}>
<View><TextInput /></View>
<View><TextInput /></View>
<View><TextInput /></View>
</View>
);
}
}
Then use it where you want it
render() {
return(
const { guest } = this.state;
...
{this.renderPayments(guest)}
);
}
Hope you got the idea.
If you want to understand this in simple Javascript check Array.prototype.fill()
Apply these changes in phpmyconfig/config.inc. Type in your username and password that you have set:
$cfg['Servers'][$i]['user'] = 'user';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
This works for me.
This is working for IE/Netscape/Chrome :
function ClearAuthentication(LogOffPage)
{
var IsInternetExplorer = false;
try
{
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
}
catch(e)
{
IsInternetExplorer = false;
};
if (IsInternetExplorer)
{
// Logoff Internet Explorer
document.execCommand("ClearAuthenticationCache");
window.location = LogOffPage;
}
else
{
// Logoff every other browsers
$.ajax({
username: 'unknown',
password: 'WrongPassword',
url: './cgi-bin/PrimoCgi',
type: 'GET',
beforeSend: function(xhr)
{
xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
},
error: function(err)
{
window.location = LogOffPage;
}
});
}
}
$(document).ready(function ()
{
$('#Btn1').click(function ()
{
// Call Clear Authentication
ClearAuthentication("force_logout.html");
});
});
Watch out for possible unintended literals in your argument
for example you can have a space within your argument, rendering it to a string / literal:
float(' 0.33')
After making sure the unintended space did not make it into the argument, I was left with:
float(0.33)
Like this it works like a charm.
Take away is: Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.
Another alternative (15. gets typed to [timespan] automatically):
ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose
I made a tuple implementation that works quite well. This solution allows for array destructuring, as well as basic type-cheking.
const Tuple = (function() {
function Tuple() {
// Tuple needs at least one element
if (arguments.length < 1) {
throw new Error('Tuple needs at least one element');
}
const args = { ...arguments };
// Define a length property (equal to the number of arguments provided)
Object.defineProperty(this, 'length', {
value: arguments.length,
writable: false
});
// Assign values to enumerable properties
for (let i in args) {
Object.defineProperty(this, i, {
enumerable: true,
get() {
return args[+i];
},
// Checking if the type of the provided value matches that of the existing value
set(value) {
if (typeof value !== typeof args[+i]) {
throw new Error('Cannot assign ' + typeof value + ' on ' + typeof args[+i]);
}
args[+i] = value;
}
});
}
// Implementing iteration with Symbol.iterator (allows for array destructuring as well for...of loops)
this[Symbol.iterator] = function() {
const tuple = this;
return {
current: 0,
last: tuple.length - 1,
next() {
if (this.current <= this.last) {
let val = { done: false, value: tuple[this.current] };
this.current++;
return val;
} else {
return { done: true };
}
}
};
};
// Sealing the object to make sure no more values can be added to tuple
Object.seal(this);
}
// check if provided object is a tuple
Tuple.isTuple = function(obj) {
return obj instanceof Tuple;
};
// Misc. for making the tuple more readable when printing to the console
Tuple.prototype.toString = function() {
const copyThis = { ...this };
const values = Object.values(copyThis);
return `(${values.join(', ')})`;
};
// conctat two instances of Tuple
Tuple.concat = function(obj1, obj2) {
if (!Tuple.isTuple(obj1) || !Tuple.isTuple(obj2)) {
throw new Error('Cannot concat Tuple with ' + typeof (obj1 || obj2));
}
const obj1Copy = { ...obj1 };
const obj2Copy = { ...obj2 };
const obj1Items = Object.values(obj1Copy);
const obj2Items = Object.values(obj2Copy);
return new Tuple(...obj1Items, ...obj2Items);
};
return Tuple;
})();
const SNAKE_COLOR = new Tuple(0, 220, 10);
const [red, green, blue] = SNAKE_COLOR;
console.log(green); // => 220
A merge conflict occurs when two branches you're trying to merge both changed the same part of the same file. You can generate a list of conflicts with git status
.
When the conflicted line is encountered, Git will edit the content of the affected files with visual indicators that mark both sides of the conflicting content.
<<<<<<< HEAD
conflicted text from HEAD
=======
conflicted text from merging_branch
>>>>>>> merging_branch
When you fix your conflicted files and you are ready to merge, all you have to do is run git add
and git commit
to generate the merge commit. Once the commit was made ,git push
the changes to the branch.
Reference article: Git merge.
https://docs.python.org/3/library/os.path.html
In python 3 pathlib "The pathlib module offers high-level path objects." so,
>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
\a\b\c
>>> print(p.stem)
c
If you have USB-Debugging/ADB enabled on your phone and your PC is authorized for debugging on your phone then you can try one of the follwing tools:
scrcpy connects over adb to your device and executes a temporary app to stream the contents of your screen to your PC and you're able to remote control your device. It works on GNU/Linux, Windows and macOS.
Vysor is a chrome web app that connects to your device via adb and installs a companion app to stream your screen content to the PC. You can then remote control your device with your mouse.
MonkeyRemote is a remote control tool written by myself before I found Vysor. It also connects through adb and lets you control your device by mouse but in contrast to Vysor, the streamed screen content updates very slow (~1 frame per second). The upside is that there is no need for a companion app to be installed.
You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.
It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1
E.g.:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM
Where mF_9.B5f-4.1JqM is your OAuth access token.
You can use print_r
to get human-readable output.
With the release of iOS 7 (September 18th, 2013) apple increased the over-the-air cellular download limit to 100MBs.
Maximum app size remains 2GBs.
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
I was having this issue as well and the problem was in the view controllers. I'm not sure how your application is structured, so I'll just explain what I found. I'm pretty new to xcode and coding, so bear with me.
I was trying to programmatically change the text on a UILabel. Using "self.mylabel.text" worked fine until I added another view controller under the same class that didn't also include that label. That is when I got the error that you're seeing. When I added the same UILabel and connected it into that additional view controller, the error went away.
In short, it seems that in Swift, all view controllers assigned to the same class have to reference the code you have in there, or else you get an error. If you have two different view controllers with different code, assign them to different classes. This worked for me and hopefully applies to what you're doing.
You have to add extra parameter -g, which generates source level debug information. It will look like:
gcc -g prog.c
After that you can use gdb in common way.
Because the question is for EditorFor not TextBoxFor WEFX's suggestion doesn't work.
For changing individual input boxes, you can process the output of the EditorFor method:
<%: new HtmlString(Html.EditorFor(m=>m.propertyname).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line my500pxWideClass\"")) %>
It is also possible to change ALL your EditorFors as it turns out MVC sets the class of EditorFor text boxes with .text-box, therefore you can just override this style, in your stylesheet or on the page.
.text-box {
width: 80em;
}
Additionally, you could set the style for
input[type="text"] {
width: 200px;
}
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
Shortcut (Ubuntu, Windows):
Ctrl + F5
Will sync the project with Gradle files.
This post describes it very nicely.
In short: utf8_unicode_ci
uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci
is a more simple sort order which results in "less accurate" sorting results.
This worked for me: :)
<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
alert('PlanId:' + planId + ' ParticipantId:' + participantId);
}
<div ng-hide="myvar == null"></div>
or
<div ng-show="myvar != null"></div>
To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.
A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.
I had this problem when I added Swift source code to an existing ObjC static framework (dynamic framework with Mach-O type "Static Library").
The fix was setting CLANG_ENABLE_MODULES
("Enable Modules" in build settings) to YES
let a = 0.0500
a.toFixed(2);
//output
0.05
you can use the like query for comparing the respective string with table vales.
select column name from table_name where column name like 'respective comparing value';
Hashtable
is similar to the HashMap
and has a similar interface. It is recommended that you use HashMap
, unless you require support for legacy applications or you need synchronisation, as the Hashtables
methods are synchronised. So in your case as you are not multi-threading, HashMaps
are your best bet.
EXPOSE
is a way of documenting--publish
(or -p
) is a way of mapping a host port to a running container portNotice below that:
EXPOSE
is related to Dockerfiles
( documenting )--publish
is related to docker run ...
( execution / run-time )Exposing and publishing ports
In Docker networking, there are two different mechanisms that directly involve network ports: exposing and publishing ports. This applies to the default bridge network and user-defined bridge networks.
You expose ports using the
EXPOSE
keyword in the Dockerfile or the--expose
flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.You publish ports using the
--publish
or--publish-all
flag todocker run
. This tells Docker which ports to open on the container’s network interface. When a port is published, it is mapped to an available high-order port (higher than30000
) on the host machine, unless you specify the port to map to on the host machine at runtime. You cannot specify the port to map to on the host machine when you build the image (in the Dockerfile), because there is no way to guarantee that the port will be available on the host machine where you run the image.from:
Docker container networkingUpdate October 2019: the above piece of text is no longer in the docs but an archived version is here: docs.docker.com/v17.09/engine/userguide/networking/#exposing-and-publishing-ports
Maybe the current documentation is the below:
Published ports
By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the
--publish
or-p
flag. This creates a firewall rule which maps a container port to a port on the Docker host.and can be found here: docs.docker.com/config/containers/container-networking/#published-ports
Also,
EXPOSE
...The
EXPOSE
instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.from: Dockerfile reference
EXPOSE
/ --publish
are not defined:At @Golo Roden's answer it is stated that::
"If you do not specify any of those, the service in the container will not be accessible from anywhere except from inside the container itself."
Maybe that was the case at the time the answer was being written, but now it seems that even if you do not use EXPOSE
or --publish
, the host
and other containers
of the same network will be able to access a service you may start inside that container.
I've used the following Dockerfile
. Basically, I start with ubuntu and install a tiny web-server:
FROM ubuntu
RUN apt-get update && apt-get install -y mini-httpd
I build
the image as "testexpose" and run
a new container with:
docker run --rm -it testexpose bash
Inside the container, I launch a few instances of mini-httpd
:
root@fb8f7dd1322d:/# mini_httpd -p 80
root@fb8f7dd1322d:/# mini_httpd -p 8080
root@fb8f7dd1322d:/# mini_httpd -p 8090
I am then able to use curl
from the host or other containers to fetch the home page of mini-httpd
.
Very detailed articles on the subject by Ivan Pepelnjak:
The one-to-many table relationship looks as follows:
In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key
column in the child which references the Primary Key
of the parent table row.
In the table diagram above, the post_id
column in the post_comment
table has a Foreign Key
relationship with the post
table id Primary Key
column:
ALTER TABLE
post_comment
ADD CONSTRAINT
fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post
The one-to-one table relationship looks as follows:
In a relational database system, a one-to-one table relationship links two tables based on a Primary Key
column in the child which is also a Foreign Key
referencing the Primary Key
of the parent table row.
Therefore, we can say that the child table shares the Primary Key
with the parent table.
In the table diagram above, the id
column in the post_details
table has also a Foreign Key
relationship with the post
table id
Primary Key
column:
ALTER TABLE
post_details
ADD CONSTRAINT
fk_post_details_id
FOREIGN KEY (id) REFERENCES post
The many-to-many table relationship looks as follows:
In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key
columns referencing the Primary Key
columns of the two parent tables.
In the table diagram above, the post_id
column in the post_tag
table has also a Foreign Key
relationship with the post
table id Primary Key
column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post
And, the tag_id
column in the post_tag
table has a Foreign Key
relationship with the tag
table id Primary Key
column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag
Update: 04/2018: Note that Vincenty distance is deprecated since GeoPy version 1.13 - you should use geopy.distance.distance() instead!
The answers above are based on the Haversine formula, which assumes the earth is a sphere, which results in errors of up to about 0.5% (according to help(geopy.distance)
). Vincenty distance uses more accurate ellipsoidal models such as WGS-84, and is implemented in geopy. For example,
import geopy.distance
coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
print geopy.distance.vincenty(coords_1, coords_2).km
will print the distance of 279.352901604
kilometers using the default ellipsoid WGS-84. (You can also choose .miles
or one of several other distance units).
Use this, 100% guaranteed:-
vr {
margin-left: 20px;
margin-right: 20px;
height: 50px;
border: 0;
border-left: 1px solid #cccccc;
display: inline-block;
vertical-align: bottom;
}
data.table
has a really intuitive way of doing this as well:
library(data.table)
sample_fxn = function(x,y,z){
return((x+y)*z)
}
df = data.table(A = 1:5,B=seq(2,10,2),C = 6:10)
> df
A B C
1: 1 2 6
2: 2 4 7
3: 3 6 8
4: 4 8 9
5: 5 10 10
The :=
operator can be called within brackets to add a new column using a function
df[,new_column := sample_fxn(A,B,C)]
> df
A B C new_column
1: 1 2 6 18
2: 2 4 7 42
3: 3 6 8 72
4: 4 8 9 108
5: 5 10 10 150
It's also easy to accept constants as arguments as well using this method:
df[,new_column2 := sample_fxn(A,B,2)]
> df
A B C new_column new_column2
1: 1 2 6 18 6
2: 2 4 7 42 12
3: 3 6 8 72 18
4: 4 8 9 108 24
5: 5 10 10 150 30
Most answers here are lacking a useful information:
Yes, you can programmatically click the input element using jQuery/JavaScript, but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER!
So, for example, nothing will happen if you, the script, programmatically click the button in an ajax callback, but if you put the same line of code in an event handler that was raised by the user, it will work.
P.S. The debugger;
keyword disrupts the browse window if it is before the programmatical click ...at least in chrome 33...
To find diff use this command:
diff -qr dir1/ dir2/
-r will diff all subdirectories too -q tells diff to report only when files differ.
diff --brief dir1/ dir2/
--brief will show the files that dosent exist in directory.
Or else
we can use Meld which will show in graphical window its easy to find the difference.
meld dir1/ dir2/
This works pretty fine
> a<-c(1,1,2,2,3,3,4,4,5)
> names(table(a))[table(a)==max(table(a))]
If relative paths are what you want you can just use the -Name
flag.
Get-ChildItem "C:\windows\System32" -Recurse -Filter *.txt -Name
@echo off
cd C:\Program Files (x86)\MySQL\MySQL Workbench 6.0 CE
for %%a in (D:\abc\*.sql) do (
echo %%a
mysql --host=ip --port=3306 --user=uid--password=ped < %%a
)
Step1: above lines copy into note pad save it as bat.
step2: In d drive abc folder in all Sql files in queries executed in sql server.
step3: Give your ip, user id and password.
Facebook's new "Page Plugin" width ranges from 180px
to 500px
as per the documentation.
180px
it would enforce a minimum width of 180px
500px
it would enforce a maximum width of 500px
With Adaptive Width checked, ex:
Unlike like-box, this plugin enforces its limits by sticking to the boundary values if mis-configured.
For small screens / Responsive behaviors
When rendering on smaller screens, enforce desiered width
on the plugin container and plugin would try to fit in.
The plugin renders at a smaller width (to fit in smaller screens) automatically, if the container is of slimmer than the configured width
.
You can scale down the container on mobile and the plugin will fit in as long as it gets the minimum of 180px
to fit in.
Without Adaptive Width
An ES6 update... though both filter and map might need customization.
Object.entries(theObj)
returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.
Saves a ton of work on iterating over parts of an object Object.keys(theObj)
, or Object.values()
separately.
const buttons = {_x000D_
button1: {_x000D_
text: 'Close',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
},_x000D_
button2: {_x000D_
text: 'OK',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
},_x000D_
button3: {_x000D_
text: 'Cancel',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
list = Object.entries(buttons)_x000D_
.filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
.map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_
_x000D_
console.log(list)
_x000D_
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
Try destroy datatable first then setup it again, example
var table;
$(document).ready(function() {
table = $("#my-datatable").datatable()
$("#my-button").click(function() {
table.fnDestroy();
table = $("#my-datatable").dataTable();
});
});
With python 2.X, you can do the following:
numbers = [0, 1, 2, 3, 127, 200, 255]
print "".join(chr(i).encode('hex') for i in numbers)
'000102037fc8ff'
Convert Date to String using this function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
System.out.println(ex);
}
return dateStr;
}
From Convert Date to String in Java . And convert string to date again
public Date convertStringToDate(String dateStr, String format) {
Date date = null;
DateFormat df = new SimpleDateFormat(format);
try {
date = df.parse(dateStr);
} catch (Exception ex) {
System.out.println(ex);
}
return date;
}
One of the dummies ways to determine if .NET Core
is installed on Windows is:
cmd
dotnet --version
If the .NET Core
is installed, we should not get any error in the above steps.
The ?
is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.
Example without using the apply
method:
function a(...args){_x000D_
b(...args);_x000D_
b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
Note This snippet returns a syntax error if your browser still uses ES5.
Editor's note: Since the snippet uses console.log()
, you must open your browser's JS console to see the result - there will be no in-page result.
It will display this result:
In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters
The first one should work:
> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]
Non programmatically, you can just open the archive using the 7zip UI to add/remove or extract/replace files without the structure changing. I didn't know it was a problem using other things until now :)
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
Found this one:
[x for (i,x) in enumerate(my_list) if my_list[i] == "two"]
Will print:
["two"]
CleanProject - Cleans Visual Studio Solutions
How many times have you wanted to send a project to a friend or upload it to a web site like MSDN Code Gallery only to find that your zip file has lots of stuff that you don't need to send in it making the file larger than it needs to be.
bin folder obj folder TestResults folder Resharper folders And then if you forget about removing Source Control bindings whoever gets your project will be prompted about that. As someone who does this process a great deal I decided to share with you my code for cleaning a project.
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
What I would do is run the loop until the ans is Q
ans=(R)
while not ans=='Q':
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
postgresql.conf
is located in PostgreSQL's data directory. The data directory is configured during the setup and the setting is saved as PGDATA
entry in c:\Program Files\PostgreSQL\<version>\pg_env.bat
, for example
@ECHO OFF
REM The script sets environment variables helpful for PostgreSQL
@SET PATH="C:\Program Files\PostgreSQL\<version>\bin";%PATH%
@SET PGDATA=D:\PostgreSQL\<version>\data
@SET PGDATABASE=postgres
@SET PGUSER=postgres
@SET PGPORT=5432
@SET PGLOCALEDIR=C:\Program Files\PostgreSQL\<version>\share\locale
Alternatively you can query your database with SHOW config_file;
if you are a superuser.
In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO TableName ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
Another way
INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
You can do it with anchor tags using css3 :target
pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example
Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.
ADO.NET 2.0 Provider for SQLite has over 200 downloads every day, so I think you are safe using that one.
You just need parentheses around your select:
SET @times = (SELECT COUNT(DidWin) FROM ...)
Or you can do it like this:
SELECT @times = COUNT(DidWin) FROM ...
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:
Add an 'Application Server' role:
Then, add a 'Web Server' role:
The order line contentions are isolated by space. On the off chance that you need furnish a contention with a space in it, you should cite it. So use git commit - m "Initial commit".
must follow this syntax.
If you want to give your user all read permissions, you could use:
EXEC sp_addrolemember N'db_datareader', N'your-user-name'
That adds the default db_datareader
role (read permission on all tables) to that user.
There's also a db_datawriter
role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:
EXEC sp_addrolemember N'db_datawriter', N'your-user-name'
If you need to be more granular, you can use the GRANT
command:
GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName
and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.
This is all very well documented in the MSDN Books Online for SQL Server.
And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users
, right-click on that user you want to give permissions to, then Properties
adn at the bottom you see "Database role memberships" where you can add the user to db roles.
public class GetUsers extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect()
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost htopost = new HttpPost("URL");
htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));
try {
JSONObject param = new JSONObject();
param.put("PageSize",100);
param.put("Userid",userId);
param.put("CurrentPage",1);
htopost.setEntity(new StringEntity(param.toString()));
// Execute the request
HttpResponse response;
response = httpclient.execute(htopost);
// Examine the response status
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
json = new JSONArray(result);
// Closing the input stream will trigger connection release
instream.close();
return ""+response.getStatusLine().getStatusCode();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected String doInBackground(String... urls) {
return connect();
}
@Override
protected void onPostExecute(String status){
try {
if(status.equals("200"))
{
Global.defaultMoemntLsit.clear();
for (int i = 0; i < json.length(); i++) {
JSONObject ojb = json.getJSONObject(i);
UserMomentModel u = new UserMomentModel();
u.setId(ojb.getString("Name"));
u.setUserId(ojb.getString("ID"));
Global.defaultMoemntLsit.add(u);
}
userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);
recycleView.setAdapter(userMomentAdapter);
recycleView.setLayoutManager(mLayoutManager);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Try this code to use:
/* For Mozile Firefox Browser */
::-moz-selection { background-color: #4CAF50; }
/* For Other Browser*/
::selection { background-color: #4CAF50; }
The most common issue is misconfiguration of your JAVA_HOME
variable which should point to the right Java Development Kit library, if you've multiple installed.
To find where SDK Java folder is located, run the following commands:
jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));'
To check which java (openjdk) you've installed, check via:
dpkg -l "openjdk*" | grep ^i
or:
update-java-alternatives -l
To change it, use:
update-alternatives --config java
Prefix with sudo
if required.
to select the alternative java version.
Or check which are available for install:
apt-cache search ^openjdk
Prefix with sudo
if required.
Then you can install, for example:
apt-get install openjdk-7-jre
Prefix with sudo
if required.
Install/upgrade appropriate package via:
yum install java-1.7.0-openjdk java-1.7.0-openjdk-devel
The
java-1.7.0-openjdk
package contains just the Java Runtime Environment. If you want to develop Java programs then install thejava-1.7.0-openjdk-devel
package.
There is an OpenJDK 7 package in the FreeBSD Ports collection called openjdk7 which probably needs to be reconfigured.
See: OpenJDK wiki page.
Just install appropriate Java SE Development Kit library from the Oracle site or install
If you're experiencing this issue with Jenkins, see:
However selecting the right version of Java (newer) with update-alternatives
should work.
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.
It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way
=((E9-E8)/E8)
became
=((R[-1]C-R[-2]C)/R[-2]C)
and
(EXP((LN(E9/E8)/14.32))-1)
became
=(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)
In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!
PHP scripting is not like other desktop application developing language. In desktop application languages we can set daemon threads to run a background process but in PHP a process is occuring when user request for a page. However It is possible to set a background job using server's cron job functionality which php script runs.
I solved by adding a port forwarding in Virtualbox settings under network. Host IP set 127.0.0.1 port : 8080 Guest ip : Give any IP for the website ( say 10.0.2.5) port : 8080 Now from guest machine access http://10.0.2.5:8080 using IE
super()
returns a parent-like object in new-style classes:
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super(B, self).__init__()
B()
Just adding a hack-ish solution to make it responsive.
Wrap the recaptcha in an extra div:
<div class="recaptcha-wrap">
<div id="g-recaptcha"></div>
</div>
Add styles. This assumes the dark theme.
// Recaptcha
.recaptcha-wrap {
position: relative;
height: 76px;
padding:1px 0 0 1px;
background:#222;
> div {
position: absolute;
bottom: 2px;
right:2px;
font-size:10px;
color:#ccc;
}
}
// Hides top border
.recaptcha-wrap:after {
content:'';
display: block;
background-color: #222;
height: 2px;
width: 100%;
top: -1px;
left: 0px;
position: absolute;
}
// Hides left border
.recaptcha-wrap:before {
content:'';
display: block;
background-color: #222;
height: 100%;
width: 2px;
top: 0;
left: -1px;
position: absolute;
z-index: 1;
}
// Makes it responsive & hides cut-off elements
#g-recaptcha {
overflow: hidden;
height: 76px;
border-right: 60px solid #222222;
border-top: 1px solid #222222;
border-bottom: 1px solid #222;
position: relative;
box-sizing: border-box;
max-width: 294px;
}
This yields the following:
It will now resize horizontally, and doesn't have a border. The recaptcha logo would get cut off on the right, so I am hiding it with a border-right. It's also hiding the privacy and terms links, so you may want to add those back in.
I attempted to set a height on the wrapper element, and then vertically center the recaptcha to reduce the height. Unfortunately, any combo of overflow:hidden and a smaller height seems to kill the iframe.
All that the call to urlopen()
does (according to the docs) is return a file-like object. Once you have that, you need to call its read()
method to actually pull the JSON data across the network.
Something like:
jsonurl = urlopen(url)
text = json.loads(jsonurl.read())
print text
Get document size without jQuery
document.documentElement.clientWidth
document.documentElement.clientHeight
And use this if you need Screen size
screen.width
screen.height
How about get_the_category?
You can then do
$category = get_the_category();
$firstCategory = $category[0]->cat_name;
Addition to the @Günter Zöchbauer's answer above, I tried as follows and it seems to be working but I'm not sure whether it is a efficient way.
I use valueChanges
observable to listen for change events in the reactive form by subscribing to it. For special handling of backspace, I get the data
from subscribe and check it with userForm.value.phone(from [formGroup]="userForm")
. Because, at that moment, the data changes to the new value but the latter refers to the previous value because of not setting yet. If the data is less than previous value then the user should remove character from input. In this case, change pattern as follows:
from : newVal = newVal.replace(/^(\d{0,3})/, '($1)');
to : newVal = newVal.replace(/^(\d{0,3})/, '($1');
Otherwise, as Günter Zöchbauer mentioned above, deleting of non-numeric characters is not recognized because when we remove parentheses from input, digits still remain the same and added again parentheses from pattern match.
Controller:
import { Component,OnInit } from '@angular/core';
import { FormGroup,FormBuilder,AbstractControl,Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
constructor(private fb:FormBuilder) {
this.createForm();
}
createForm(){
this.userForm = this.fb.group({
phone:['',[Validators.pattern(/^\(\d{3}\)\s\d{3}-\d{4}$/),Validators.required]],
});
}
ngOnInit() {
this.phoneValidate();
}
phoneValidate(){
const phoneControl:AbstractControl = this.userForm.controls['phone'];
phoneControl.valueChanges.subscribe(data => {
/**the most of code from @Günter Zöchbauer's answer.*/
/**we remove from input but:
@preInputValue still keep the previous value because of not setting.
*/
let preInputValue:string = this.userForm.value.phone;
let lastChar:string = preInputValue.substr(preInputValue.length - 1);
var newVal = data.replace(/\D/g, '');
//when removed value from input
if (data.length < preInputValue.length) {
/**while removing if we encounter ) character,
then remove the last digit too.*/
if(lastChar == ')'){
newVal = newVal.substr(0,newVal.length-1);
}
if (newVal.length == 0) {
newVal = '';
}
else if (newVal.length <= 3) {
/**when removing, we change pattern match.
"otherwise deleting of non-numeric characters is not recognized"*/
newVal = newVal.replace(/^(\d{0,3})/, '($1');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
} else {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
}
//when typed value in input
} else{
if (newVal.length == 0) {
newVal = '';
}
else if (newVal.length <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, '($1)');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
} else {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
}
}
this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});
});
}
}
Template:
<form [formGroup]="userForm" novalidate>
<div class="form-group">
<label for="tel">Tel:</label>
<input id="tel" formControlName="phone" maxlength="14">
</div>
<button [disabled]="userForm.status == 'INVALID'" type="submit">Send</button>
</form>
UPDATE
Is there a way to preserve cursor position while backspacing in the middle of the string? Currently, it jumps back to the end.
Define an id <input id="tel" formControlName="phone" #phoneRef>
and renderer2#selectRootElement to get the native element in the component.
So we can get the cursor position using:
let start = this.renderer.selectRootElement('#tel').selectionStart;
let end = this.renderer.selectRootElement('#tel').selectionEnd;
and then we can apply it after the input is updated to new value:
this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});
//keep cursor the appropriate position after setting the input above.
this.renderer.selectRootElement('#tel').setSelectionRange(start,end);
UPDATE 2
It's probably better to put this sort of logic inside a directive rather than in the component
I also put the logic into a directive. This makes it easier to apply it to other elements.
Note: It is specific to (123) 123-4567
pattern.
Here is one trick:
public static int getItself(int itself, int dummy)
{
return itself;
}
public static void main(String[] args)
{
int a = 10;
int b = 20;
a = getItself(b, b = a);
}
Take a look at the JavaDoc for RestTemplate.
There is the corresponding getForObject
methods that are the HTTP GET equivalents of postForObject
, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.
Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange
methods allow you to provide an HttpEntity
object representing the details of the request (including headers). The execute
methods allow you to specify a RequestCallback
from which you can add the headers upon its invocation.
Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.
However, this is how you can vertically align YOUR 3 divs:
.wrap{
width: 500px;
overflow:hidden;
background: pink;
}
.left {
width: 150px;
margin-right: 10px;
background: yellow;
display:inline-block;
vertical-align: middle;
}
.left2 {
width: 150px;
margin-right: 10px;
background: aqua;
display:inline-block;
vertical-align: middle;
}
.right{
width: 150px;
background: orange;
display:inline-block;
vertical-align: middle;
}
Not sure why you needed both fixed width, display: inline-block and floating.
if(characterCode == 13)
{
return false; // returning false will prevent the event from bubbling up.
}
else
{
return true;
}
Ok, so imagine you have the following textbox in a form:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.
function runScript(e) {
//See notes about 'which' and 'key'
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.
It's been pointed out that keyCode
is now deprecated. The next best alternative which
has also been deprecated.
Unfortunately the favored standard key
, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.
Furthermore, while the deprecated warning is quite ominous about keyCode
and which
, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.
Near the top of the code with the Public Workshop(), I am assumeing this bit,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);
should maybe be,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);
Basically I use Fiddler or Postman for testing API's.
In fiddler, in request header you need to specify instead of xml, html you need to change it to json.
Eg: Accept: application/json
. That should do the job.
Assuming the file exists and you just need to update the timestamp.
type test.c > test.c.bkp && type test.c.bkp > test.c && del test.c.bkp
Probably very trivial, but I solved it by just converting the input to numpy array.
For the neural network architecture,
model = Sequential()
model.add(Conv2D(32, (5, 5), activation="relu", input_shape=(32, 32, 3)))
When the input was,
n_train = len(train_y_raw)
train_X = [train_X_raw[:,:,:,i] for i in range(n_train)]
train_y = [train_y_raw[i][0] for i in range(n_train)]
But when I changed it to,
n_train = len(train_y_raw)
train_X = np.asarray([train_X_raw[:,:,:,i] for i in range(n_train)])
train_y = np.asarray([train_y_raw[i][0] for i in range(n_train)])
It fixed the issue.
The issue here that the Python version used to build your Lambda function dependencies (on your own machine) is different than the selected Python version for your Lambda function. This case is common especially if the Numpy library part of your dependencies.
Example: Your machine's python version: 3.6 ---> Lambda python version 3.6
This line:
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:
setContentView(new GraphTemperature(getApplicationContext()));
And i'm guessing that new "graphTemperature" does not set anything with that id.
It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).
The nullpointer will be thrown because the layout you're looking for isn't found, so
layout.addView(buyButton);
Throws that exception.
addition: Now if you want to get that view from an XML, you should use an inflater:
layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);
assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"
u should add a theme
to ur all activities (u should add theme
for all application in ur <application>
in ur manifest)
but if u have set different theme to ur activity u can use :
android:theme="@style/Theme.AppCompat"
or each kind of AppCompat
theme!
It basically means that the object implements the __getitem__()
method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.
If you're using Chimp / Webdriver.io, they support a lot more CSS selectors than the CSS spec.
This, for example, will click on the first anchor that contains the words "Bad bear":
browser.click("a*=Bad Bear");
If possible you can change the div to an textarea and use .change().
Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.
You can also use http://www.jacklmoore.com/autosize/ to make the text area act more like a div.
<style>
.hidden{
display:none
}
</style>
<textarea class="hidden" rows="4" cols="50">
</textarea>
$("#hiddentextarea").change(function() {
alert('Textarea changed');
})
Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?
I'm not sure why you'd want to validate an optional email address, but I'd suggest you use
^$|^[^@\s]+@[^@\s]+$
meaning
^$ empty string
| or
^ beginning of string
[^@\s]+ any character but @ or whitespace
@
[^@\s]+
$ end of string
You won't stop fake emails anyway, and this way you won't stop valid addresses.
Sometimes (too often!) I have to untangle someone else's C++ code. And we all know that someone else's C++ code is a complete mess almost by definition :) So the first thing I do to decipher local data flow is put const in every variable definition until compiler starts barking. This means const-qualifying value arguments as well, because they are just fancy local variables initialized by caller.
Ah, I wish variables were const by default and mutable was required for non-const variables :)
Yes, Reflection would be the way to go. First, you would get the Type
that represents the type (at runtime) of the instance in the list. You can do this by calling the GetType
method on Object
. Because it is on the Object
class, it's callable by every object in .NET, as all types derive from Object
(well, technically, not everything, but that's not important here).
Once you have the Type
instance, you can call the GetProperties
method to get the PropertyInfo
instances which represent the run-time informationa about the properties on the Type
.
Note, you can use the overloads of GetProperties
to help classify which properties you retrieve.
From there, you would just write the information out to a file.
Your code above, translated, would be:
// The instance, it can be of any type.
object o = <some object>;
// Get the type.
Type type = o.GetType();
// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
// Do something with the property info.
DoSomething(info);
}
Note that if you want method information or field information, you would have to call the one of the overloads of the GetMethods
or GetFields
methods respectively.
Also note, it's one thing to list out the members to a file, but you shouldn't use this information to drive logic based on property sets.
Assuming you have control over the implementations of the types, you should derive from a common base class or implement a common interface and make the calls on those (you can use the as
or is
operator to help determine which base class/interface you are working with at runtime).
However, if you don't control these type definitions and have to drive logic based on pattern matching, then that's fine.
Windows INI API support for:
;
The authoritative source is the Windows API function that reads values out of INI files
GetPrivateProfileString
Retrieves a string from the specified section in an initialization file.
The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini
file contents:
[Application]
UseLiveData=1
;coke=zero
pepsi=diet ;gag
#stackoverflow=splotchy
Reading the values:
UseLiveData
: 1
coke
: not present;coke
: not presentpepsi
: diet ;gag
stackoverflow
: not present#stackoverflow
: splotchy
Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow
is because the name stackoverflow
no longer exists. And it turns out that semi-colon (;
) is a line-comment.
But there is no support for trailing comments.
One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).
Will take you to the master branch.
git checkout master
To switch to other branches do (ignore the square brackets, it's just for emphasis purposes)
git checkout [the name of the branch you want to switch to]
To create a new branch use the -b like this (ignore the square brackets, it's just for emphasis purposes)
git checkout -b [the name of the branch you want to create]
why not something like this:
Dim ar As New ArrayList
Dim numToGet As Integer = 5
'hard code just to test
ar.Add("12")
ar.Add("11")
ar.Add("10")
ar.Add("15")
ar.Add("16")
ar.Add("17")
Dim randomListOfProductIds As New ArrayList
Dim toAdd As String = ""
For i = 0 To numToGet - 1
toAdd = ar(CInt((ar.Count - 1) * Rnd()))
randomListOfProductIds.Add(toAdd)
'remove from id list
ar.Remove(toAdd)
Next
'sorry i'm lazy and have to write vb at work :( and didn't feel like converting to c#
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
Use angular-ui-bootstrap's typehead.
It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.
(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)
In RC2 (and most likely in the final release) you can switch language from inside Visual Studio and you can modify your setup to include other language packs.
You can now add and remove multiple user interface languages at any time using the Visual Studio installer on the Language Pack tab. You can select the current user interface language among those installed using Tools > Options > International Settings. Source : https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#vside
You don't need to learn JPA. You can use my easy-criteria for JPA2 (https://sourceforge.net/projects/easy-criteria/files/). Here is the example
CriteriaComposer<Pet> petCriteria CriteriaComposer.from(Pet.class).
where(Pet_.type, EQUAL, "Cat").join(Pet_.owner).where(Ower_.name,EQUAL, "foo");
List<Pet> result = CriteriaProcessor.findAllEntiry(petCriteria);
OR
List<Tuple> result = CriteriaProcessor.findAllTuple(petCriteria);
Quit vim before "git commit".
to make vim
use other folders for backup files, (/tmp
for example):
set bdir-=.
set bdir+=/tmp
to make vim stop using current folder for .swp files:
set dir-=.
set dir+=/tmp
Use -=, +=
would be generally good, because vim has other defaults for bdir, dir, we don't want to clear all. Check vim help for more about bdir, dir:
:h bdir
:h dir
In Debug > Website Properties.
change port number in Project Url to any nearest value and save
How about:
import pandas as pd
#List with all words
words=[]
#Code for adding words
words.append('test')
#When Input equals blank:
pd.Series(words).nunique()
It returns how many unique values are in a list
Try this:
git clone --recurse-submodules
It automatically pulls in the submodule data assuming you have already added the submodules to the parent project.
Also you can use DownloadFileAsync
method in WebClient
class. It downloads to a local file the resource with the specified URI
. Also this method does not block the calling thread.
Sample:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
For more information:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
using bootstrap you can have a responsive and mobile first embeded file.
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="address of your file" allowfullscreen></iframe>
</div>
Aspect ratios can be customized with modifier classes.
<!-- 21:9 aspect ratio -->
<div class="embed-responsive embed-responsive-21by9">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
<!-- 1:1 aspect ratio -->
<div class="embed-responsive embed-responsive-1by1">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>