Since 2011, if you can change function1
, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
Notice also that I fixed your broken object definition (aClass a();
declares a function).
I'm betting the problem is that Cygwin is writing Unix line endings (LF) to the file, and you're opening it with a program that expects Windows line-endings (CRLF). To determine if this is the case — and for a bit of a hackish workaround — try:
echo "`date` User `whoami` started the script."$'\r' >> output.log
(where the $'\r'
at the end is an extra carriage-return; it, plus the Unix line ending, will result in a Windows line ending).
Meanwhile this can be solved through a decorator in combination with Object.freeze
or Object.defineProperty
, I'm using this, it's a little bit prettier than using tons of getters. You can copy/paste this directly TS Playground to see it in action. - There are two options
The following decorator converts both, annotated static and non-static fields to "getter-only-properties".
Note: If an instance-variable with no initial value is annotated @final
, then the first assigned value (no matter when) will be the final one.
// example
class MyClass {
@final
public finalProp: string = "You shall not change me!";
@final
public static FINAL_FIELD: number = 75;
public static NON_FINAL: string = "I am not final."
}
var myInstance: MyClass = new MyClass();
myInstance.finalProp = "Was I changed?";
MyClass.FINAL_FIELD = 123;
MyClass.NON_FINAL = "I was changed.";
console.log(myInstance.finalProp); // => You shall not change me!
console.log(MyClass.FINAL_FIELD); // => 75
console.log(MyClass.NON_FINAL); // => I was changed.
The Decorator: Make sure you include this in your code!
/**
* Turns static and non-static fields into getter-only, and therefor renders them "final".
* To use simply annotate the static or non-static field with: @final
*/
function final(target: any, propertyKey: string) {
const value: any = target[propertyKey];
// if it currently has no value, then wait for the first setter-call
// usually the case with non-static fields
if (!value) {
Object.defineProperty(target, propertyKey, {
set: function (value: any) {
Object.defineProperty(this, propertyKey, {
get: function () {
return value;
},
enumerable: true,
configurable: false
});
},
enumerable: true,
configurable: true
});
} else { // else, set it immediatly
Object.defineProperty(target, propertyKey, {
get: function () {
return value;
},
enumerable: true
});
}
}
As an alternative to the decorator above, there would also be a strict version of this, which would even throw an Error when someone tried to assign some value to the field with "use strict";
being set. (This is only the static part though)
/**
* Turns static fields into getter-only, and therefor renders them "final".
* Also throws an error in strict mode if the value is tried to be touched.
* To use simply annotate the static field with: @strictFinal
*/
function strictFinal(target: any, propertyKey: string) {
Object.defineProperty(target, propertyKey, {
value: target[propertyKey],
writable: false,
enumerable: true
});
}
Possible Downside: This will only work for ALL statics of that class or for none, but cannot be applied to specific statics.
/**
* Freezes the annotated class, making every static 'final'.
* Usage:
* @StaticsFinal
* class MyClass {
* public static SOME_STATIC: string = "SOME_STATIC";
* //...
* }
*/
function StaticsFinal(target: any) {
Object.freeze(target);
}
// Usage here
@StaticsFinal
class FreezeMe {
public static FROZEN_STATIC: string = "I am frozen";
}
class EditMyStuff {
public static NON_FROZEN_STATIC: string = "I am frozen";
}
// Test here
FreezeMe.FROZEN_STATIC = "I am not frozen.";
EditMyStuff.NON_FROZEN_STATIC = "I am not frozen.";
console.log(FreezeMe.FROZEN_STATIC); // => "I am frozen."
console.log(EditMyStuff.NON_FROZEN_STATIC); // => "I am not frozen."
This is what worked for our particular situation.
Notes are from Wikipedia on Basic Auth from the Client Side. Thank you to @briantist's answer for the help!
Combine the username and password into a single string username:password
$user = "shaunluttin"
$pass = "super-strong-alpha-numeric-symbolic-long-password"
$pair = "${user}:${pass}"
Encode the string to the RFC2045-MIME variant of Base64, except not limited to 76 char/line.
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
Create the Auth value as the method, a space, and then the encoded pair Method Base64String
$basicAuthValue = "Basic $base64"
Create the header Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
$headers = @{ Authorization = $basicAuthValue }
Invoke the web-request
Invoke-WebRequest -uri "https://api.github.com/user" -Headers $headers
The PowerShell version of this is more verbose than the cURL version is. Why is that? @briantist pointed out that GitHub is breaking the RFC and PowerShell is sticking to it. Does that mean that cURL is also breaking with the standard?
heroku ps:restart [web|worker] --app app_name
works for all processes declared in your Procfile. So if you have multiple web processes or worker processes, each labeled with a number, you can selectively restart one of them:
heroku ps:restart web.2 --app app_name
heroku ps:restart worker.3 --app app_name
One of my favorite lib: Apache Commons.
The EnumUtils can do that easily.
Following an example to validate an Enum with that library:
public enum MyEnum {
DIV("div"), DEPT("dept"), CLASS("class");
private final String val;
MyEnum(String val) {
this.val = val;
}
public String getVal() {
return val;
}
}
MyEnum strTypeEnum = null;
// test if String str is compatible with the enum
// e.g. if you pass str = "div", it will return false. If you pass "DIV", it will return true.
if( EnumUtils.isValidEnum(MyEnum.class, str) ){
strTypeEnum = MyEnum.valueOf(str);
}
At any stage of maven build life cycle, all the previous goals are performed.
Ex: mvn install will invoke mvn validate, mvn compile, mvn test, mvn package etc.
An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.
There is good explanation of that here.
<div class="d-flex justify-content-center align-items-center container ">
<div class="row ">
<form action="">
<div class="form-group">
<label for="inputUserName" class="control-label">Enter UserName</label>
<input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
<small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
</div>
<div class="form-group">
<label for="inputPassword" class="control-label">Enter Password</label>
<input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">
</div>
</form>
</div>
</div>
No need to create a new key just clear site data on browser
If you change your site domain then add that domain to existing key (it's not necessary to a create new one) and save it.
https://www.google.com/recaptcha/admin#list
but google recapture has some data on browser. Clear them then it will work with your new domain
I was testing a function that had multiple UPDATE
statements within IF-ELSE
blocks.
I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE
statements each time before running the function again.
I noticed that the issue would happen just after those UPDATE
statements;
I added a COMMIT;
after the UPDATE
statement I used to reset the tables and that solved the problem.
So, caution, the problem was not the function itself...
Something along the lines of this?
<asp:TextBox id="txtUsername" runat="server" />
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Field not valid!"
ControlToValidate="txtUsername"
ValidationExpression="[0-9a-zA-Z]{6,}" />
The root of the answer is that the person asking the question needs to have a JavaScript interpreter to get what they are after. What I have found is I am able to get all of the information I wanted on a website in json before it was interpreted by JavaScript. This has saved me a ton of time in what would be parsing html hoping each webpage is in the same format.
So when you get a response from a website using requests really look at the html/text because you might find the javascripts JSON in the footer ready to be parsed.
This is where fnmatch comes very handy:
import fnmatch
print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))
More details: http://docs.python.org/2/library/fnmatch.html
Some things of top of my head.
Method 1.
Application.Union(Range("a1"), Range("b1"), Range("d1"), Range("e1"), Range("g1"), Range("h1")).EntireColumn.Select
Method 2.
Range("a1,b1,d1,e1,g1,h1").EntireColumn.Select
Method 3.
Application.Union(Columns("a"), Columns("b"), Columns("d"), Columns("e"), Columns("g"), Columns("h")).Select
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.
// Defensive database opening logic.
if (_databaseConnection.State == ConnectionState.Broken) {
_databaseConnection.Close();
}
if (_databaseConnection.State == ConnectionState.Closed) {
_databaseConnection.Open();
}
If you want get a float for $value = '0.4'
, but int for $value = '4'
, you can write:
$number = ($value == (int) $value) ? (int) $value : (float) $value;
It is little bit dirty, but it works.
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.
Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.
Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/
You can use these solutions :
CSS rules applies to all tags that have following two classes :
.left.ui-class-selector {
/*style here*/
}
CSS rules applies to all tags that have <li>
with following two classes :
li.left.ui-class-selector {
/*style here*/
}
jQuery solution :
$("li.left.ui-class-selector").css("color", "red");
Javascript solution :
document.querySelector("li.left.ui-class-selector").style.color = "red";
Because @Robert K and @mattcasey both have good code, I thought I'd contribute here with a CoffeeScript version, in case anyone in the future could use it:
String::unescape = (strict = false) ->
###
# Take escaped text, and return the unescaped version
#
# @param string str | String to be used
# @param bool strict | Stict mode will remove all HTML
#
# Test it here:
# https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
#
# Code: https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d
###
# Create a dummy element
element = document.createElement("div")
decodeHTMLEntities = (str) ->
if str? and typeof str is "string"
unless strict is true
# escape HTML tags
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
else
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
element.innerHTML = str
if element.innerText
# Do we support innerText?
str = element.innerText
element.innerText = ""
else
# Firefox
str = element.textContent
element.textContent = ""
unescape(str)
# Remove encoded or double-encoded tags
fixHtmlEncodings = (string) ->
string = string.replace(/\&#/mg, '&#') # The rest, for double-encodings
string = string.replace(/\"/mg, '"')
string = string.replace(/\"e;/mg, '"')
string = string.replace(/\_/mg, '_')
string = string.replace(/\'/mg, "'")
string = string.replace(/\"/mg, '"')
string = string.replace(/\>/mg, '>')
string = string.replace(/\</mg, '<')
string
# Run it
tmp = fixHtmlEncodings(this)
decodeHTMLEntities(tmp)
See https://jsfiddle.net/tigerhawkvok/t9pn1dn5/7/ or https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d (includes compiled JS, and is probably updated compared to this answer)
This worked for me in angular >= 6.x versions:
this.router.events
.subscribe((event) => {
if (event instanceof NavigationStart) {
window.localStorage.setItem('previousUrl', this.router.url);
}
});
Just for the fun of it, after the party has finished and the horse bolted.
The answer is: max()
!
Javascript can be executed against the current page just by putting it in the URL address, e.g.
javascript:;alert(window.document.body.innerHTML);
javascript:;alert(window.document.body.childNodes[0].innerHTML);
data=np.genfromtxt(csv_file, delimiter=',', dtype='unicode')
It works fine for me.
The file is a gzipped (compressed) SQL file, almost certainly a plain text file with .sql as its extension. The first thing you need to do is copy the file to your database server via scp.. I think PuTTY's is pscp.exe
# Copy it to the server via pscp
C:\> pscp.exe numbers.sql.gz user@serverhostname:/home/user
Then SSH into your server and uncompress the file with gunzip
user@serverhostname$ gunzip numbers.sql.gz
user@serverhostname$ ls
numbers.sql
Finally, import it into your MySQL database using the <
input redirection operator:
user@serverhostname$ mysql -u mysqluser -p < numbers.sql
If the numbers.sql file doesn't create a database but expects one to be present already, you will need to include the database in the command as well:
user@serverhostname$ mysql -u mysqluser -p databasename < numbers.sql
If you have the ability to connect directly to your MySQL server from outside, then you could use a local MySQL client instead of having to copy and SSH. In that case, you would just need a utility that can decompress .gz files on Windows. I believe 7zip does so, or you can obtain the gzip/gunzip binaries for Windows.
I had the same issue. I solved it, truncating the SQL Server LOG. Check doing that, and then tell us, if this solution helped you.
I also experienced that for example:
This code doesnt work and get the intended block error.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
However, when i press tab before typing return self.title statement, the code works.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
Hope, this will help others.
You can use the code below.
<script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
//alert("This function is working!");
//alert(place.name);
// alert(place.address_components[0].long_name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
and this part is inside your form:
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
I hope it helps.
You can use MERGE
Statement, This statement is used to insert data if not exist or update if does exist.
MERGE INTO Employee AS e
using EmployeeUpdate AS eu
ON e.EmployeeID = eu.EmployeeID`
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
Async Arrow function syntax with parameters
const myFunction = async (a, b, c) => {
// Code here
}
There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member
is correctly defined as
package pageNumber;
since, that's the only application package you're importing in your JSP.
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
Nobody seems to touch upon the fact that if you have many different 32-bit applications, the wow64 subsystem can map them anywhere in memory above 4G, so on a 64-bit windows with sufficient memory, you can run many more 32-bit applications than on a native 32-bit system.
I think you want to add android:configChanges="orientation|keyboardHidden"
to your activity? Otherwise the activity is restarted on config-change. The onConfigurationChanged
would not be called then, only the onCreate
The argument to split is a regular expression. "." matches anything so your delimiter to split on is anything.
The math.log
function is to the base e
, i.e. natural logarithm. If you want to the base 10 use math.log10
.
To use video extensions that are MKV. You should use video, not source
For example :
<!-- mkv -->
<video width="320" height="240" controls src="assets/animation.mkv"></video>
<!-- mp4 -->
<video width="320" height="240" controls>
<source src="assets/animation.mp4" type="video/mp4" />
</video>
_x000D_
This worked for me:
**/.idea/**
!**/.idea/copyright/
!.idea/copyright/profiles_settings.xml
!.idea/copyright/Copyright.xml
Use the moment.js library for time and date management.
import moment = require('moment');
const now = moment();
now.subtract(7, 'seconds'); // 7 seconds ago
now.subtract(7, 'days'); // 7 days and 7 seconds ago
now.subtract(7, 'months'); // 7 months, 7 days and 7 seconds ago
now.subtract(7, 'years'); // 7 years, 7 months, 7 days and 7 seconds ago
// because `now` has been mutated, it no longer represents the current time
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
HttpBasicAuth works for me with smaller changes
I use maven dependency
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<version>2.3.8</version>
</dependency>
Smaller change
String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes());
ApplicationId must be of type UniqueIdentifier
. Your code works fine if you do:
DECLARE @TTEST TABLE
(
TEST UNIQUEIDENTIFIER
)
DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();
INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);
SELECT * FROM @TTEST
Therefore I would say it is safe to assume that ApplicationId
is not the correct data type.
Nowadays, we could use some flexbox to align those divs.
.container {_x000D_
display: flex;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>_x000D_
<span>source list</span>_x000D_
<select size="10">_x000D_
<option />_x000D_
<option />_x000D_
<option />_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<span>destination list</span>_x000D_
<select size="10">_x000D_
<option />_x000D_
<option />_x000D_
<option />_x000D_
</select>_x000D_
</div>_x000D_
</div>
_x000D_
The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.
Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.
If you are on Java 10, you can use var
for that:
var ordinal = new Object() { int value; };
list.forEach(s -> {
s.setOrdinal(ordinal.value);
ordinal.value++;
});
This is working Oracle example but it should work in MySQL too.
You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.
SELECT empno, ename, job
FROM scott.emp
WHERE (CASE WHEN job = 'MANAGER' THEN '1'
WHEN job = 'CLERK' THEN '2'
ELSE '0' END) IN (1, 2)
For a use case like this, it may be useful to use a string constant so it can be marshaled into a JSON string. In the following example, []Base{A,C,G,T}
would get marshaled to ["adenine","cytosine","guanine","thymine"]
.
type Base string
const (
A Base = "adenine"
C = "cytosine"
G = "guanine"
T = "thymine"
)
When using iota
, the values get marshaled into integers. In the following example, []Base{A,C,G,T}
would get marshaled to [0,1,2,3]
.
type Base int
const (
A Base = iota
C
G
T
)
Here's an example comparing both approaches:
While working on my internship project I found a website for this https://thezipcodes.com/ Create a free account and get the API key from account Section.
https://thezipcodes.com/api/v1/search?zipCode={zipCode}&countryCode={2digitCountryCode}&apiKey={apiKey}
I found majority of data here.
Consume and cache the column value that you want to group by, then push the remaining data as a new subarray of the group you have created in the the result.
function array_group(array $data, $by_column)
{
$result = [];
foreach ($data as $item) {
$column = $item[$by_column];
unset($item[$by_column]);
$result[$column][] = $item;
}
return $result;
}
curl is a command in linux (and a library in php). Curl typically makes an HTTP request.
What you really want to do is make an HTTP (or XHR) request from javascript.
Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax
Essentially you will want to call $.ajax
with a few options for the header, etc.
$.ajax({
url: 'https://api.wit.ai/message?v=20140826&q=',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
}, success: function(data){
alert(data);
//process the JSON data etc
}
})
I am using the following
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}.${monthlyVersion}.${instanceVersion}</finalName>
</configuration>
</plugin>
....
This way you can define each value individually or pragmatically from Jenkins of some other system.
mvn package -DbaseVersion=1 -monthlyVersion=2 -instanceVersion=3
This will place a folder target\{group.id}\projectName-1.2.3.jar
A better way to save time might be
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
</configuration>
</plugin>
....
Like the same except I use on variable.
mvn package -DbaseVersion=0.3.4
This will place a folder target\{group.id}\projectName-1.2.3.jar
you can also use outputDirectory
inside of configuration
to specify a location you may want the package to be located.
Yes:
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);
First, the code creates a new layout params by specifying the height and width. The addRule
method adds the equivalent of the xml properly android:layout_below
. Then you just call View#setLayoutParams
on the view you want to have those params.
Step to enable SSL correctly.
sudo a2enmod ssl
sudo apt-get install openssl
Configure the path of SSL certificates in your SSL config file (default-ssl.conf) that might be located in /etc/apache2/sites-available. I have stored certificates under /etc/apache2/ssl/
SSLEngine On
SSLCertificateFile /etc/apache2/ssl/certificate.crt
SSLCertificateChainFile /etc/apache2/ssl/ca_bundle.crt
SSLCertificateKeyFile /etc/apache2/ssl/private.key
Enable SSL config file
sudo a2ensite default-ssl.conf
__stdcall
is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.
There are a number of other calling conventions, __cdecl
, __thiscall
, __fastcall
and the wonderfully named __declspec(naked)
. __stdcall
is the standard calling convention for Win32 system calls.
Wikipedia covers the details.
It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.
You can see the differences b/w these two
import sys
for i in range(1,10 ):
sys.stdout.write(str(i))
sys.stdout.flush()
for i in range(1,10 ):
print i
Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.
As a beginner in SQL I find that when using a BEGIN
and END
SSMS usually adds a squiggly line with incorrect syntax near 'END'
to END, simply because there's no content in between yet. If you're just setting up BEGIN
and END
to get started and add the actual query later, then simply add a bogus PRINT
statement so SSMS stops bothering you.
For example:
IF (1=1)
BEGIN
PRINT 'BOGUS'
END
The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:
IF (1=1)
BEGIN
END
Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
I find identically-specced AVDs run and load far better on my home machine (Phenom II x4 945/8GB RAM/Win7 HP 64bit) than they do on my work machine (Core2Duo/3GB RAM/Ubuntu 11.04 32bit).
As you're essentially running a virtual machine, I would personally go for nothing less than a dual core/4GB
, though highly recommend a quad/8GB if you can splash out for that.
Please try this:
with open('filename','r',buffering=100000) as f:
for line in f:
print line
The @Qualifier
annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.
The @Qualifier
annotation can be used on any class annotated with @Component
or on methods annotated with @Bean
. This annotation can also be applied on constructor arguments or method parameters.
Ex:-
public interface Vehicle {
public void start();
public void stop();
}
There are two beans, Car and Bike implements Vehicle interface
@Component(value="car")
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}
@Component(value="bike")
public class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike started");
}
@Override
public void stop() {
System.out.println("Bike stopped");
}
}
Injecting Bike bean in VehicleService using @Autowired
with @Qualifier
annotation. If you didn't use @Qualifier
, it will throw NoUniqueBeanDefinitionException.
@Component
public class VehicleService {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
public void service() {
vehicle.start();
vehicle.stop();
}
}
Reference:- @Qualifier annotation example
Try this
test2.removeAll(test1);
Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.
As Kevin Panko said, it's mostly because of library change. So in some cases a "clean" of the project (directory) followed by a build does the trick.
I'm using elasticsearch 7.5 and when I use
curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty' -d'
{
"query": {
"match_all": {}
}
}'
which will throw below error.
{
"error" : "Content-Type header [application/x-www-form-urlencoded] is not supported",
"status" : 406
}
I also need to add extra -H 'Content-Type: application/json'
header in the request to make it works.
curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty' -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}'
{
"took" : 465,
"timed_out" : false,
"total" : 2275,
"deleted" : 2275,
"batches" : 3,
"version_conflicts" : 0,
"noops" : 0,
"retries" : {
"bulk" : 0,
"search" : 0
},
"throttled_millis" : 0,
"requests_per_second" : -1.0,
"throttled_until_millis" : 0,
"failures" : [ ]
}
This is a further optimisation.
\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)
\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*(\d{1,2})$
(i) allows for valid international prefixes
(ii) followed by 9 or 10 digits, with any type or placing of delimeters (except between the last two digits)
This will match:
+1-234-567-8901
+61-234-567-89-01
+46-234 5678901
+1 (234) 56 89 901
+1 (234) 56-89 901
+46.234.567.8901
+1/234/567/8901
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
The first answer that uses eyed3 is outdated so here is an updated version of it.
Reading tags from an mp3 file:
import eyed3
audiofile = eyed3.load("some/file.mp3")
print(audiofile.tag.artist)
print(audiofile.tag.album)
print(audiofile.tag.album_artist)
print(audiofile.tag.title)
print(audiofile.tag.track_num)
An example from the website to modify tags:
import eyed3
audiofile = eyed3.load("some/file.mp3")
audiofile.tag.artist = u"Integrity"
audiofile.tag.album = u"Humanity Is The Devil"
audiofile.tag.album_artist = u"Integrity"
audiofile.tag.title = u"Hollow"
audiofile.tag.track_num = 2
An issue I encountered while trying to use eyed3 for the first time had to do with an import error of libmagic even though it was installed. To fix this install the magic-bin whl from here
There should also be <category android:name="android.intent.category.BROWSABLE"/>
added to the intent filter to make the activity recognized properly from the link.
i have changed my old path: jdbc:odbc:thin:@localhost:1521:orcl
to new : jdbc:oracle:thin:@//localhost:1521/orcl
and it worked for me.....hurrah!! image
In my case it was
Error starting userland proxy: listen tcp 0.0.0.0:9000: bind: address already in use
And all that I need is turn off debug listening in php storm
The best - and simplest - solution might be this:
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();
Documentation for finishAndRemoveTask()
:
Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.
Is that what you're looking for?
I needed a really light weight one, Its not 100%, but it gets close enough for some usecases.
float3 Hue(float h, float s, float l)
{
float r = max(cos(h * 2 * UNITY_PI) * 0.5 + 0.5, 0);
float g = max(cos((h + 0.666666) * 2 * UNITY_PI) * 0.5 + 0.5, 0);
float b = max(cos((h + 0.333333) * 2 * UNITY_PI) * 0.5 + 0.5, 0);
float gray = 0.2989 * r + 0.5870 * g + 0.1140 * b;
return lerp(gray, float3(r, g, b), s) * smoothstep(0, 0.5, l) + 1 * smoothstep(0.5, 1, l);
}
Doing
df.index = pd.to_datetime(df.index, errors='coerce')
the data type of the index has changed to
You won't need a plugin to see commit history with Visual Studio Code 1.42 or more.
Timeline view
In this milestone, we've made progress on the new Timeline view, and have an early preview to share.
This is a unified view for visualizing time-series events (e.g. commits, saves, test runs, etc.) for a resource (file, folder, etc.).
To enable the Timeline view, you must be using
the Insiders Edition(VSCode 1.44 March 2020) and then add the following setting:
"timeline.showView": true
Which version of IIS is your host running? One thing to try is to put a dummy default.aspx file in the root folder (this will not be used when MVC is working, but can get rid of this problem).
For Temporary change use following command
set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
For permanent change : go to config file /etc/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf and add following lines then restart mysql service
[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Describe Formatted/Extended will show the data definition of the table in hive
hive> describe Formatted dbname.tablename;
Type
git push
from the command line inside the repository directory
The solution you posted is not working for me...
This is what works for me:
Create the repository with the desired name.
When committing the image, name the image like the repository, including the username <dockerusername>/desired-name
. For example, radu/desired-name
.
@kajetons' answer is fully functional.
You can also pass multiple variables by passing them like: use($var1, $var2)
DB::table('users')->where(function ($query) use ($activated,$var2) {
$query->where('activated', '=', $activated);
$query->where('var2', '>', $var2);
})->get();
A symbolic link to the desired version, defined globally:
sudo ln -s /usr/bin/qmake-qt5 /usr/bin/qmake
... or per user:
sudo ln -s /usr/bin/qmake-qt5 /home/USERNAME/.local/bin/qmake
... to see if it works:
qmake --version
Go to Start and search for "Anaconda Prompt" - right click this and choose "Open File Location", which will open a folder of shortcuts. Right click the "Anaconda Prompt" shortcut, choose "Properties" and you can adjust the starting dir in the "Start in" box.
if you do the outer join (with the count), and then use this result as a sub-table, you can get 0 as expected (thanks to the nvl function)
Ex:
select P.person_id, nvl(A.nb_apptmts, 0) from
(SELECT person.person_id
FROM person) P
LEFT JOIN
(select person_id, count(*) as nb_apptmts
from appointment
group by person_id) A
ON P.person_id = A.person_id
There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all
and choosing the right alternatives for everything else besides java
and javac
.
convert_objects is deprecated.
For pandas >= 0.17.0, use pd.to_numeric
df["2nd"] = pd.to_numeric(df["2nd"])
Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use
$data = file_get_contents("php://input");
to just retrieve the http body and handle it yourself. See PHP input/output streams.
From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.
To allow a user to enter a Canadian Postal code with lower case letters as well, the regex would need to look like this:
/^([a-zA-Z][0-9][a-zA-Z])\s*([0-9][a-zA-Z][0-9])$/
Separate the increments with a comma too.
for(int a = 0, b = 1; a<cards.length-1; b=a+1, a++)
Let me show you another way that works 100%. I will also add some padding for the example.
<div class = "container">
<div class = "flex-pad-x">
<div class = "flex-pad-y">
<div class = "flex-pad-y">
<div class = "flex-grow-y">
Content Centered
</div>
</div>
</div>
</div>
</div>
.container {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
width: 100%;
height: 100%;
}
.flex-pad-x {
padding: 0px 20px;
height: 100%;
display: flex;
}
.flex-pad-y {
padding: 20px 0px;
width: 100%;
display: flex;
flex-direction: column;
}
.flex-grow-y {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.
1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.
Hope this helps
Daniel
Install firebug and use console.log
instead of alert
. Then you will see the exact element your accessing.
Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.
FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.
(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)
Perfect answer for AM/PM live time solution
<?php echo date('h:i A', time())?>
In TortoiseSVN you can access and modify some settings in the context menu "Settings/General" in explorer.
E.g. the "Global ignore pattern" can be edited directly in the dialog box. Such changings are the stored in the registry as bahrep pointed out in her answer.
(Win10/TortoiseSVN 1.13.1, Build 28686 - 64 Bit)
public abstract class Refl {
/** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
public static<T> T get(Object obj, String fieldPath) {
return (T) getValue(obj, fieldPath);
}
public static Object getValue(Object obj, String fieldPath) {
String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
String success = "";
Object res = obj;
for (String fieldName : fieldNames) {
if (fieldName.isEmpty()) continue;
int index = toIndex(fieldName);
if (index >= 0) {
try {
res = ((Object[])res)[index];
} catch (ClassCastException cce) {
throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
} catch (IndexOutOfBoundsException iobe) {
throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
}
} else {
Field field = getField(res.getClass(), fieldName);
field.setAccessible(true);
try {
res = field.get(res);
} catch (Exception ee) {
throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
}
}
success += fieldName + ".";
}
return res;
}
public static Field getField(Class<?> clazz, String fieldName) {
Class<?> tmpClass = clazz;
do {
try {
Field f = tmpClass.getDeclaredField(fieldName);
return f;
} catch (NoSuchFieldException e) {
tmpClass = tmpClass.getSuperclass();
}
} while (tmpClass != null);
throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
}
private static int toIndex(String s) {
int res = -1;
if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
try {
res = Integer.parseInt(s);
if (res < 0) {
res = -1;
}
} catch (Throwable t) {
res = -1;
}
}
return res;
}
}
It supports fetching fields and array items, e.g.:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));
there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
You can use Explicit wait or Fluent Wait
Example of Explicit Wait -
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));
Example of Fluent Wait -
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("about_me"));
}
});
Check this TUTORIAL for more details.
A simple way is to write it:
Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
msgbox "There is no records"
End if
SELECT DATEDIFF(NOW(),pickup_date) AS noofday
FROM cir_order
WHERE DATEDIFF(NOW(),pickup_date)>2;
or
SELECT *
FROM cir_order
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )
For those using the shade plugin, following on david_p's advice, you can merge the services in the shaded jar by adding the ServicesResourceTransformer to the plugin config:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
This will merge all the org.apache.hadoop.fs.FileSystem services in one file
app.js add
app.set('view engine','ejs')
add your partial file(ejs) in views/partials
in index.ejs
<%- include('partials/header.ejs') %>
Here is the simplest explanation
Alan Turing created a machine that can take a program, run that program, and show some result. But then he had to create different machines for different programs. So he created "Universal Turing Machine" that can take ANY program and run it.
Programming languages are similar to those machines (although virtual). They take programs and run them. Now, a programing language is called "Turing complete", if it can run any program (irrespective of the language) that a Turing machine can run given enough time and memory.
For example: Let's say there is a program that takes 10 numbers and adds them. A Turing machine can easily run this program. But now imagine that for some reason your programming language can't perform the same addition. This would make it "Turing incomplete" (so to speak). On the other hand, if it can run any program that the universal Turing machine can run, then it's Turing complete.
Most modern programming languages (e.g. Java, JavaScript, Perl, etc.) are all Turing complete because they each implement all the features required to run programs like addition, multiplication, if-else condition, return statements, ways to store/retrieve/erase data and so on.
Update: You can learn more on my blog post: "JavaScript Is Turing Complete" — Explained
For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
1-liner, takes a XML string text
and YourType
as the expected object type. not very different from other answers, just compressed to 1 line:
var result = (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));
Have a look at config.sample.inc.php: you will find examples of the configuration directives that you should copy to your config.inc.php (copy the missing ones). Then, have a look at examples/create_tables.sql which will help you create the missing tables.
The complete documentation for this is available at http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.
You can use OLD
and NEW
in the trigger to access those values which had changed in that trigger. Mysql Ref
Here's a more generic version of the solution above from @herbertD :
private void resizeView(View view, int newWidth, int newHeight) {
try {
Constructor<? extends LayoutParams> ctor = view.getLayoutParams().getClass().getDeclaredConstructor(int.class, int.class);
view.setLayoutParams(ctor.newInstance(newWidth, newHeight));
} catch (Exception e) {
e.printStackTrace();
}
}
Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME
which describes the branch.
In my script..
stage('Build') {
node {
echo 'Pulling...' + env.BRANCH_NAME
checkout scm
}
}
Yields...
Pulling...master
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
Ctrl+Shift+F to invoke the Auto Formatter
Ctrl+I to indent the selected part (or all) of you code.
Android Device Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To start the standalone Device Monitor application in Android Studio 3.1 and lower you can run android-sdk/tools/monitor.bat
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}
In date '?'
, the '?'
is a literal string with value ?
, not a parameter placeholder, so your query does not have any parameters. The date
is a shorthand cast from (literal) string to date. You need to replace date '?'
with ?
to actually have a parameter.
Also if you know it is a date, then use setDate(..)
and not setString(..)
to set the parameter.
If you still see permission denied
after verifying the permissions of the parent folders, it may be SELinux restricting access.
To check if SELinux is running:
# getenforce
To disable SELinux until next reboot:
# setenforce Permissive
Restart Nginx and see if the problem persists. To allow nginx to serve your www directory (make sure you turn SELinux back on before testing this. i.e, setenforce Enforcing
)
# chcon -Rt httpd_sys_content_t /path/to/www
See my answer here for more details
How do I declare an ES6 Map type in typescript?
You need to target --module es6
. This is misfortunate and you can raise your concern here : https://github.com/Microsoft/TypeScript/issues/2953#issuecomment-98514111
Your declaration is int ttTreeInsert(int value);
However, your definition/implementation is
ttTree::ttTreeInsert(int value)
{
}
Notice that the return type int
is missing in the implementation. Instead it should be
int ttTree::ttTreeInsert(int value)
{
return 1; // or some valid int
}
You can use the padding-left
attribute on the list items (not on the list itself!).
This is because of the proxy settings.
I also had the same problem, under which I could not use any of the modules which were fetching data from the internet.
There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done.
try to run the programme again, it must work
it worked for me at least
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
should works
I used some of the code recommended above and after many hours of waisting my time, I eventually came to a css bag free solution.
You can run it over here - http://jsfiddle.net/WqGph/
but then found a better solution - http://jsfiddle.net/XMMc4/5/
<input type = "button" value = "Choose image #2"
onclick ="javascript:document.getElementById('imagefile').click();">
<input id = "imagefile" type="file" style='display:none;' name="img" value="none"/>see jsfiddle code for examples<br/>
Another solution using scale_y_log10
with trans_breaks
, trans_format
and annotation_logticks()
library(ggplot2)
m <- ggplot(diamonds, aes(y = price, x = color))
m + geom_boxplot() +
scale_y_log10(
breaks = scales::trans_breaks("log10", function(x) 10^x),
labels = scales::trans_format("log10", scales::math_format(10^.x))
) +
theme_bw() +
annotation_logticks(sides = 'lr') +
theme(panel.grid.minor = element_blank())
You should look for a hosting company that provides such feature, but standard simple static+PHP+MySQL hosting won't let you use node.js.
You need either find a hosting designed for node.js or buy a Virtual Private Server and install it yourself.
There are way too many ways to possibly discuss that you probably don't care about. You can hack of course - strace bash, or do all sorts of black magic running Bash in gdb.
You actually have two completely different examples there. <<<'string'
is already writing a string to a file. If anything is acceptable other than printf
, echo
, and cat
, you can use many other commands to behave like cat (sed, awk, tee, etc).
$ cp /dev/stdin ./tmpfooblah <<<'hello world'; cat tmpfooblah
hello world
Or hell, depending on how you've compiled Bash.
$ enable -f /usr/lib/bash/print print; print 'hello world' >tmpfile
If you want to use only bash strings and redirection, in pure bash, with no hacking, and no loadables, it is not possible. In ksh93 however, it is possible.
$ rm tmpfooblah; <<<'hello world' >tmpfooblah <##@(&!()); cat tmpfooblah
hello world
You'll do it the same way you would apply a css selector. For instanse you can do
$("#mydiv > .myclass")
or
$("#mydiv .myclass")
The last one will match every myclass inside myDiv, including myclass inside myclass.
You have to bind your methods with 'this' (default object). So whatever your function may be just bind that in the constructor.
constructor(props) {
super(props);
this.state = { checked:false };
this.handleChecked = this.handleChecked.bind(this);
}
handleChecked(){
this.setState({
checked: !(this.state.checked)
})
}
render(){
var msg;
if(this.state.checked){
msg = 'checked'
}
else{
msg = 'not checked'
}
return (
<div>
<input type='checkbox' defaultChecked = {this.state.checked} onChange = {this.handleChecked} />
<h3>This is {msg}</h3>
</div>
);
I posted too soon however the ways to configure are given in below link
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
and way to get access keys are given in below link
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html#cli-signup
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$pass = $_POST["password"];
$check_email = mysqli_query($conn, "SELECT Email FROM crud where Email = '$email' ");
if(mysqli_num_rows($check_email) > 0){
echo('Email Already exists');
}
else{
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$result = mysqli_query($conn, "INSERT INTO crud (Firstname, Lastname, Email, Password) VALUES ('$firstname', '$lastname', '$email', '$pass')");
}
echo('Record Entered Successfully');
}
I know this is an old question but I came across this today since I needed to test for this in my site. It seems the answers above are needlessly complicated. To establish the site protocol, all you have to do is test $_SERVER['HTTPS']
If the protocol is using HTTPS, then $_SERVER['HTTPS']
will return 'on'. If not, the variable will remain empty.
For example:
// test if HTTPS is being used. If it is, the echo will return '$SSL_test: on'. If not HTTPS, '$SSL_test' will remain empty.
$SSL_test = $_SERVER['HTTPS'];
echo '<p>$SSL_test: '.$SSL_test.'</p>';
if($SSL_test == true) {
echo 'You\'re using SSL';
} else {
echo 'You\'re not using SSL';
}
You can use the above to easily and cleanly test for HTTPS and implement accordingly. :)
my solution (supports leading 0s):
String pattern="^[0-9](\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25?[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?$";
The other answer didn't work for me (on Windows 7). But this worked:
telnet localhost 5554
kill
colleagues.
I have faced with this trouble during a development of automation tests for our REST API. JDK 7_80 was installed at my machine only. Before I installed JDK 8, everything worked just fine and I had a possibility to obtain OAuth 2.0 tokens with a JMeter
. After I installed JDK 8, the nightmare with Certificates does not conform to algorithm constraints
began.
Both JMeter and Serenity did not have a possibility to obtain a token. JMeter uses the JDK library to make the request. The library just raises an exception when the library call is made to connect to endpoints that use it, ignoring the request.
The next thing was to comment all the lines dedicated to disabledAlgorithms in ALL java.security files.
C:\Java\jre7\lib\security\java.security
C:\Java\jre8\lib\security\java.security
C:\Java\jdk8\jre\lib\security\java.security
C:\Java\jdk7\jre\lib\security\java.security
Then it started to work at last. I know, that's a brute force approach, but it was the most simple way to fix it.
# jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
# jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
@Zugwait's answer is correct. req.param()
is deprecated. You should use req.params
, req.query
or req.body
.
But just to make it clearer:
req.params
will be populated with only the route values. That is, if you have a route like /users/:id
, you can access the id
either in req.params.id
or req.params['id']
.
req.query
and req.body
will be populated with all params, regardless of whether or not they are in the route. Of course, parameters in the query string will be available in req.query
and parameters in a post body will be available in req.body
.
So, answering your questions, as color
is not in the route, you should be able to get it using req.query.color
or req.query['color']
.
$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];
Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.
There is a lot of confusion around this, I will try to make it as simple as possible.
The primary key is a general concept to indicate one or more columns used to retrieve data from a Table.
The primary key may be SIMPLE and even declared inline:
create table stackoverflow_simple (
key text PRIMARY KEY,
data text
);
That means that it is made by a single column.
But the primary key can also be COMPOSITE (aka COMPOUND), generated from more columns.
create table stackoverflow_composite (
key_part_one text,
key_part_two int,
data text,
PRIMARY KEY(key_part_one, key_part_two)
);
In a situation of COMPOSITE primary key, the "first part" of the key is called PARTITION KEY (in this example key_part_one is the partition key) and the second part of the key is the CLUSTERING KEY (in this example key_part_two)
Please note that the both partition and clustering key can be made by more columns, here's how:
create table stackoverflow_multiple (
k_part_one text,
k_part_two int,
k_clust_one text,
k_clust_two int,
k_clust_three uuid,
data text,
PRIMARY KEY((k_part_one, k_part_two), k_clust_one, k_clust_two, k_clust_three)
);
Behind these names ...
Further usage information: DATASTAX DOCUMENTATION
insert into stackoverflow_simple (key, data) VALUES ('han', 'solo');
select * from stackoverflow_simple where key='han';
table content
key | data
----+------
han | solo
COMPOSITE/COMPOUND KEY can retrieve "wide rows" (i.e. you can query by just the partition key, even if you have clustering keys defined)
insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 9, 'football player');
insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 10, 'ex-football player');
select * from stackoverflow_composite where key_part_one = 'ronaldo';
table content
key_part_one | key_part_two | data
--------------+--------------+--------------------
ronaldo | 9 | football player
ronaldo | 10 | ex-football player
But you can query with all key (both partition and clustering) ...
select * from stackoverflow_composite
where key_part_one = 'ronaldo' and key_part_two = 10;
query output
key_part_one | key_part_two | data
--------------+--------------+--------------------
ronaldo | 10 | ex-football player
Important note: the partition key is the minimum-specifier needed to perform a query using a where clause
.
If you have a composite partition key, like the following
eg: PRIMARY KEY((col1, col2), col10, col4))
You can perform query only by passing at least both col1 and col2, these are the 2 columns that define the partition key. The "general" rule to make query is you have to pass at least all partition key columns, then you can add optionally each clustering key in the order they're set.
so the valid queries are (excluding secondary indexes)
Invalid:
Hope this helps.
Just had the same problem after creating a new user profile on my development machine.
The problem was that I wasn't running the console (command prompt\powershell ISE) as admin.
Running as admin solved this problem for me.
Running the command prompt or Powershell ISE as an administrator fixed this for me.
If you have more than one network adapter and more than one adapter is active (f.e WLAN + VPN) you need a bit more complex check. You can use this one-liner:
[System.Net.DNS]::GetHostByAddress(([System.Net.DNS]::GetHostAddresses([System.Environment]::MachineName) | Where-Object { $_.AddressFamily -eq "InterNetwork" } | Select-Object IPAddressToString)[0].IPAddressToString).HostName.ToLower()
If you aren't getting the this.props
... you were expecting based on the other answers, you may need to use withRouter
(docs v4):
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>You are now at {location.pathname}</div>
)
}
}
// Create a new component that is "connected" (to borrow redux terminology) to the router.
const TwitterSsoButton = withRouter(ShowTheLocation)
// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))
// This does not
connect(...)(withRouter(MyComponent))
ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
I always have to use the brackets when I use the ALTER SCHEMA
query in SQL, or I get an error message.
To replace na values in pandas
df['column_name'].fillna(value_to_be_replaced,inplace=True)
if inplace = False
, instead of updating the df (dataframe) it will return the modified values.
From the documentation for FileSystemWatcher
:
The
OnCreated
event is raised as soon as a file is created. If a file is being copied or transferred into a watched directory, theOnCreated
event will be raised immediately, followed by one or moreOnChanged
events.
So, if the copy fails, (catch the exception), add it to a list of files that still need to be moved, and attempt the copy during the OnChanged
event. Eventually, it should work.
Something like (incomplete; catch specific exceptions, initialize variables, etc):
public static void listener_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine
(
"File Created:\n"
+ "ChangeType: " + e.ChangeType
+ "\nName: " + e.Name
+ "\nFullPath: " + e.FullPath
);
try {
File.Copy(e.FullPath, @"D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name);
}
catch {
_waitingForClose.Add(e.FullPath);
}
Console.Read();
}
public static void listener_Changed(object sender, FileSystemEventArgs e)
{
if (_waitingForClose.Contains(e.FullPath))
{
try {
File.Copy(...);
_waitingForClose.Remove(e.FullPath);
}
catch {}
}
}
Problem source is datetime format.
Wrong samples: "MM-dd-yyyy H:mm","MM-dd-yyyy"
Correct sample: "MM-dd-yyyy HH:mm"
For anyone reading this post in the future, you don't need to cd to the directory where the jar is present. Here is what you need to do -
Go to your project folder from where you can run maven commands (When you do an ls -ltr in this folder, you should see pom.xml)
Do this -
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=<Path where the jar is, example downloads>/ojdbc6.jar -DgeneratePom=true
Once this is done, you can add the dependency in your pom.xml, something like this -
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
if($("#id").length) /*exists*/
if(!$("#id").length) /*doesn't exist*/
Using new Array methods and =>
function syntax from ES6 standard (only Firefox at the time of writing).
By filling holes with undefined
:
Array(N).fill().map((_, i) => i + 1);
Array.from
turns "holes" into undefined
so Array.map
works as expected:
Array.from(Array(5)).map((_, i) => i + 1)
Put the varible in an array and Use a for Loop to assign the same value to multiple variables.
myArray[moveUP, moveDown, moveLeft];
for(var i = 0; i < myArray.length; i++){
myArray[i] = true;
}
Actually, you do not need to do a first guess. Simply doing
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])
n = len(x) #the number of data
mean = sum(x*y)/n #note this correction
sigma = sum(y*(x-mean)**2)/n #note this correction
def gaus(x,a,x0,sigma):
return a*exp(-(x-x0)**2/(2*sigma**2))
popt,pcov = curve_fit(gaus,x,y)
#popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()
works fine. This is simpler because making a guess is not trivial. I had more complex data and did not manage to do a proper first guess, but simply removing the first guess worked fine :)
P.S.: use numpy.exp() better, says a warning of scipy
Global variables are fine in small programs, but horrible if used the same way in large ones.
This means that you can easily get in the habit of using them while learning. This is what your professor is trying to protect you from.
When you are more experienced it will be easier to learn when they are okay.
pip
is a command line tool, not Python syntax.
In other words, run the command in your console, not in the Python interpreter:
pip install beautifulsoup4
You may have to use the full path:
C:\Python27\Scripts\pip install beautifulsoup4
or even
C:\Python27\Scripts\pip.exe install beautifulsoup4
Windows will then execute the pip
program and that will use Python to install the package.
Another option is to use the Python -m
command-line switch to run the pip
module, which then operates exactly like the pip
command:
python -m pip install beautifulsoup4
or
python.exe -m pip install beautifulsoup4
Is there a way to set the session timeout programatically
There are basically three ways to set the session timeout value:
session-timeout
in the standard web.xml
file ~or~session-timeout
value (and thus configuring it at the server level) ~or~HttpSession. setMaxInactiveInterval(int seconds)
method in your Servlet or JSP. But note that the later option sets the timeout value for the current session, this is not a global setting.
Refer to the jQuery API documentation: not() selector and not equal selector.
$elapsed = '2592000';
// Time in the past
$time_past = '2014-07-16 11:35:33';
$time_past = strtotime($time_past);
// Add a month to that time
$time_past = $time_past + $elapsed;
// Time NOW
$time_now = time();
// Check if its been a month since time past
if($time_past > $time_now){
echo 'Hasnt been a month';
}else{
echo 'Been longer than a month';
}
If the shell scripts start with #!/bin/bash
, they will always run with bash
from /bin
. If they however start with #!/usr/bin/env bash
, they will search for bash
in $PATH
and then start with the first one they can find.
Why would this be useful? Assume you want to run bash
scripts, that require bash 4.x or newer, yet your system only has bash
3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.
Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin
for example. And you can also modify your $PATH
variable in your .bash_profile
file to include ~/bin
as the first entry (PATH=$HOME/bin:$PATH
as ~
will not expand in $PATH
). If you now call bash
, the shell will first look for it in $PATH
in order, so it starts with ~/bin
, where it will find your bash
. Same thing happens if scripts search for bash
using #!/usr/bin/env bash
, so these scripts would now be working on your system using your custom bash
build.
One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.
The biggest downside with env
is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>
, as the systems will see <interpreter> <arg>
as one argument (they will treat it as if the expression was quoted) and thus env
will search for an interpreter named <interpreter> <arg>
. Note that this is not a problem of the env
command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env
. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.
It can even have security implications, e.g. if sudo
was not configured to clean environment or $PATH
was excluded from clean up. Let me demonstrate this:
Usually /bin
is a well protected place, only root
is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash
into some hidden directory, modify your .bash_profile
to include that directory in your $PATH
, so all scripts using #!/usr/bin/env bash
will end up running with that fake bash
. If sudo
keeps $PATH
, you are in big trouble.
E.g. consider a tool creates a file ~/.evil/bash
with the following content:
#!/bin/bash
if [ $EUID -eq 0 ]; then
echo "All your base are belong to us..."
# We are root - do whatever you want to do
fi
/bin/bash "$@"
Let's make a simple script sample.sh
:
#!/usr/bin/env bash
echo "Hello World"
Proof of concept (on a system where sudo
keeps $PATH
):
$ ./sample.sh
Hello World
$ sudo ./sample.sh
Hello World
$ export PATH="$HOME/.evil:$PATH"
$ ./sample.sh
Hello World
$ sudo ./sample.sh
All your base are belong to us...
Hello World
Usually the classic shells should all be located in /bin
and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin
that points to their real locations (or maybe /bin
itself is a symlink), so I would always go with #!/bin/sh
and #!/bin/bash
. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh
, it would probably still understand #!/bin/sh
and know what to do with it and may it only be for compatibility with existing code.
But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin
but they may as well be in /usr/local/bin
or in a completely different hierarchy branch (/opt/...
, /Applications/...
, etc.). That's why these often use the #!/usr/bin/env xxx
shebang syntax.
Check out yowsup
https://github.com/tgalal/yowsup
Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.
A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.
Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.
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']
Installing the aab directly from the device, I couldn't find a way for that.
But there is a way to install it through your command line using the following documentation You can install apk to a device through BundleTool
According to "@Albert Vila Calvo" comment he noted that to install bundletools using HomeBrew use brew install bundletool
You can now install extract apks from aab file and install it to a device
Extracting apk files from through the next command
java -jar bundletool-all-0.3.3.jar build-apks --bundle=bundle.aab --output=app.apks --ks=my-release-key.keystore --ks-key-alias=alias --ks-pass=pass:password
Arguments:
Then you will have a file with extension .apks So now you need to install it to a device
java -jar bundletool-all-0.6.0.jar install-apks --adb=/android-sdk/platform-tools/adb --apks=app.apks
Arguments:
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:
For eg. consider a slight modification of your case:
@JsonProperty("fileName")
private String fileName;
@JsonProperty("fileName")
public String getFileName()
{
return fileName;
}
@JsonProperty("fileName1")
public void setFileName(String fileName)
{
this.fileName = fileName;
}
Both fileName
field, and method getFileName
, have the correct property name of fileName
and setFileName
has a different one fileName1
, in this case Jackson will look for a fileName1
attribute in json at the point of deserialization and will create a attribute called fileName1
at the point of serialization.
Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName
, it would just pick one of them as the attribute(FILENAME
), and had any on of the three differed, it would have thrown an exception:
java.lang.IllegalStateException: Conflicting property name definitions
\t
will match tabs, rather than spaces and should also be referred to with a double slash: \\t
. You could call s.split( " " )
but that wouldn't count consecutive spaces. By that I mean...
String bar = " ba jfjf jjj j ";
String[] split = bar.split( " " );
System.out.println( split.length ); // Returns 5
So, despite the fact there are seven space characters, there are only five blocks of space. It depends which you're trying to count, I guess.
Commons Lang is your friend for this one.
int count = StringUtils.countMatches( inputString, " " );
Broadcast receiver code to check internet connectivity change:
public class BroadCastDetecter extends BroadcastReceiver {
public static boolean internet_status = false;
public static void checkInternetConenction(Context context) {
internet_status = false;
ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null) {
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
{
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
internet_status = true;
}
}
if(internet_status)
{
//do what you want to if internet connection is available
}
}
}
@Override
public void onReceive(Context context, Intent intent)
{
try {
checkInternetConenction(context);
}catch(Exception e){
}
}
}
add this in manifest file:
<receiver android:name=".BroadCastDetecter">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
user.no_of_logins += 1
session.commit()
You have to use the jquery attribute selector. You can read more here:
http://api.jquery.com/attribute-equals-selector/
In your case it should be:
$('input[name="btnName"]')
You can also use prompter.
Shamelessly taken from the README:
#pip install prompter
from prompter import yesno
>>> yesno('Really?')
Really? [Y/n]
True
>>> yesno('Really?')
Really? [Y/n] no
False
>>> yesno('Really?', default='no')
Really? [y/N]
True
While templates are probably best for the case you describe, if you have or want your data and/or arguments in iterable/array form, you can use String.raw
.
String.raw({
raw: ["I'm ", " years old!"]
}, 3);
With the data as an array, one can use the spread operator:
const args = [3, 'yesterday'];
String.raw({
raw: ["I'm ", " years old as of ", ""]
}, ...args);
You can have a look at Jansson
The website states the following: Jansson is a C library for encoding, decoding and manipulating JSON data. It features:
The simplest way is to map over the DataFrame's RDD and use mkString:
df.rdd.map(x=>x.mkString(","))
As of Spark 1.5 (or even before that)
df.map(r=>r.mkString(","))
would do the same
if you want CSV escaping you can use apache commons lang for that. e.g. here's the code we're using
def DfToTextFile(path: String,
df: DataFrame,
delimiter: String = ",",
csvEscape: Boolean = true,
partitions: Int = 1,
compress: Boolean = true,
header: Option[String] = None,
maxColumnLength: Option[Int] = None) = {
def trimColumnLength(c: String) = {
val col = maxColumnLength match {
case None => c
case Some(len: Int) => c.take(len)
}
if (csvEscape) StringEscapeUtils.escapeCsv(col) else col
}
def rowToString(r: Row) = {
val st = r.mkString("~-~").replaceAll("[\\p{C}|\\uFFFD]", "") //remove control characters
st.split("~-~").map(trimColumnLength).mkString(delimiter)
}
def addHeader(r: RDD[String]) = {
val rdd = for (h <- header;
if partitions == 1; //headers only supported for single partitions
tmpRdd = sc.parallelize(Array(h))) yield tmpRdd.union(r).coalesce(1)
rdd.getOrElse(r)
}
val rdd = df.map(rowToString).repartition(partitions)
val headerRdd = addHeader(rdd)
if (compress)
headerRdd.saveAsTextFile(path, classOf[GzipCodec])
else
headerRdd.saveAsTextFile(path)
}
The Python Tutorial simply calls it 'the *
-operator'. It performs unpacking of arbitrary argument lists.
I think the best solution is resize the images via script or locally and upload them again. Remember, you're forcing your viewers to download larger files than they need
Rather than dealing with a switch statement, I think it's neater to lookup the content type from a dictionary:
var contentTypesByExtension = {
'html': "text/html",
'js': "text/javascript"
};
...
var contentType = contentTypesByExtension[fileExtension] || 'text/plain';
This works for sure for Select Control:
$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
this.selected = true;
return;
} });
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
plt.gca().xaxis.grid(True)
proved to be the solution for me
If they are in the same directory as your script that contains:
./a.sh > /dev/null 2>&1 &
./b.sh > /dev/null 2>&1 &
The &
at the end is what makes your script run in the background.
The > /dev/null 2>&1
part is not necessary - it redirects the stdout and stderr streams so you don't have to see them on the terminal, which you may want to do for noisy scripts with lots of output.
If you're attempting to get an element you can use Vue.util.query
which is really just a wrapper around document.querySelector
but at 14 characters vs 22 characters (respectively) it is technically shorter. It also has some error handling in case the element you're searching for doesn't exist.
There isn't any official documentation on Vue.util
, but this is the entire source of the function:
function query(el) {
if (typeof el === 'string') {
var selector = el;
el = document.querySelector(el);
if (!el) {
({}).NODE_ENV !== 'production' && warn('Cannot find element: ' + selector);
}
}
return el;
}
Repo link: Vue.util.query
By default, for all collection and map objects the fetching rule is FetchType.LAZY
and for other instances it follows the FetchType.EAGER
policy.
In brief, @OneToMany
and @ManyToMany
relations does not fetch the related objects (collection and map) implicictly but the retrieval operation is cascaded through the field in @OneToOne
and @ManyToOne
ones.
The first thing I want to make clear is that branch names are just an alias to a specific commit. a commit is what git works off, when you pull, push merge and so forth. Each commit has a unique id.
When you do $ git merge , what is actually happening is git tries to fast forward your current branch to to the commit the referenced branch is on (in other words both branch names point to the same commit.) This scenario is the easiest for git to deal, since there's no new commit. Think of master jumping onto the lilipad your branch is chilling on. It's possible to set the --no-ff flag, in which case git will create a new commit regardless of whether there were any code conflicts.
In a situation where there are code conflicts between the two branches you are trying to merge (usually two branches whose commit history share a common commit in the past), the fast forward won't work. git may still be able to automatically merge the files, so long as the same line wasn't changed by both branches in a conflicting file. in this case, git will merge the conflicting files for you AND automatically commit them. You can preview how git did by doing $ git diff --cached. Or you can pass the --no-commit flag to the merge command, which will leave modified files in your index you'll need to add and commit. But you can $ git diff these files to review what the merge will change.
The third scenario is when there are conflicts git can't automatically resolve. In this case you'll need to manually merge them. In my opinion this is easiest to do with a merge took, like araxis merge or p4merge (free). Either way, you have to do each file one by one. If the merge ever seems to be stuck, use $ git merge --continue, to nudge it along. Git should tell you if it can't continue, and if so why not. If you feel you loused up the merge at some point, you can do $ git merge --abort, and any merging will undo and you can start over. When you're done, each file you merged will be a modified file that needs to be added and committed. You can verify where the files are with $ git status. If you haven't committed the merged files yet. You need to do that to complete the merge. You have to complete the merge or abort the merge before you can switch branches.
Perhaps you need to specify a top value in your css rule set, so that it will know what value to animate from.
You are missing an opening quote on the id= and you have a semi-colon after the function declaration. Also, the input tag does not need a closing tag.
This works:
<input onclick="change()" type="button" value="Open Curtain" id="myButton1">
<script type="text/javascript">
function change()
{
document.getElementById("myButton1").value="Close Curtain";
}
</script>
Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.
Sometimes using image = array(img).reshape(a,b,c,d)
will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is
np.expand_dims(img, axis=0)
It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.
You need to have installed Microsoft Visual Studio Tools for Office (VSTO).
VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.
After that create common .NET project and add the reference to Microsoft.Office.Interop.Excel
via 'Add Reference... > Assemblies' dialog.
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Missing.Value
is a special reflection struct for unnecessary parameters replacement
In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library
. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library
, or an older version, but it is the same process to include.
I had to add a message box to my existing program. Most of the answers are overly complicated in this instance. For Linux on Ubuntu 16.04 (Python 2.7.12) with future proofing for Ubuntu 20.04 here is my code:
from __future__ import print_function # Must be first import
try:
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as font
import tkinter.filedialog as filedialog
import tkinter.messagebox as messagebox
PYTHON_VER="3"
except ImportError: # Python 2
import Tkinter as tk
import ttk
import tkFont as font
import tkFileDialog as filedialog
import tkMessageBox as messagebox
PYTHON_VER="2"
Regardless of which Python version is being run, the code will always be messagebox.
for future proofing or backwards compatibility. I only needed to insert two lines into my existing code above.
''' At least one song must be selected '''
if self.play_song_count == 0:
messagebox.showinfo(title="No Songs Selected", \
message="You must select at least one song!", \
parent=self.toplevel)
return
I already had the code to return if song count was zero. So I only had to insert three lines in between existing code.
You can spare yourself complicated geometry code by using parent window reference instead:
parent=self.toplevel
Another advantage is if the parent window was moved after program startup your message box will still appear in the predictable place.
To use the least amount of space you should use a CHAR field constrained to 'Y' or 'N'. Oracle doesn't support BOOLEAN, BIT, or TINYINT data types, so CHAR's one byte is as small as you can get.
As stated here: UITextField text change event, it seems that as of iOS 6 (iOS 6.0 and 6.1 checked) it is not possible to fully detect changes in UITextField
objects just by observing the UITextFieldTextDidChangeNotification
.
It seems that only those changes made directly by the built-in iOS keyboard are tracked now. This means that if you change your UITextField
object just by invoking something like this: myUITextField.text = @"any_text"
, you won't be notified about any changes at all.
I don't know if this is a bug or it is intended. Seems like a bug since I haven't found any reasonable explanation in documentation. This is also stated here: UITextField text change event.
My "solution" to this is to actually post a notification by myself for every change I make to my UITextField
(if that change is done without using the built-in iOS keyboard). Something like this:
myUITextField.text = @"I'm_updating_my_UITextField_directly_in_code";
NSNotification *myTextFieldUpdateNotification =
[NSNotification notificationWithName:UITextFieldTextDidChangeNotification
object:myUITextField];
[NSNotificationCenter.defaultCenter
postNotification:myTextFieldUpdateNotification];
This way you are 100% confident that you'll receive the same notification when you change the .text
property of your UITextField
object, either when you update it "manually" in your code or through the built-in iOS keyboard.
It is important to consider that, since this is not a documented behavior, this approach may lead to 2 notifications received for the same change in your UITextField
object. Depending on your needs (what you actually do when your UITextField.text
changes) this could be an inconvenience for you.
A slightly different approach would be to post a custom notification (this is, with a custom name other than UITextFieldTextDidChangeNotification
) if you actually need to know whether the notification was yours or "iOS-made".
EDIT:
I've just found a different approach which I think could be better:
This involves the Key-Value Observing (KVO) feature of Objective-C (http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177-BCICJDHA).
Basically, you register yourself as an observer of a property and if this property changes you get notified about it. The "principle" is quite similar to how NSNotificationCenter
works, being the main advantage that this approach works automatically also as of iOS 6 (without any special tweak like having to manually post notifications).
For our UITextField
-scenario this works just fine if you add this code to, for example, your UIViewController
that contains the text field:
static void *myContext = &myContext;
- (void)viewDidLoad {
[super viewDidLoad];
//Observing changes to myUITextField.text:
[myUITextField addObserver:self forKeyPath:@"text"
options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
context:myContext];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
if(context == myContext) {
//Here you get notified every time myUITextField's "text" property is updated
NSLog(@"New value: %@ - Old value: %@",
[change objectForKey:NSKeyValueChangeNewKey],
[change objectForKey:NSKeyValueChangeOldKey]);
}
else
[super observeValueForKeyPath:keyPath ofObject:object
change:change context:context];
}
Credit to this answer regarding "context" management: https://stackoverflow.com/a/12097161/2078512
Note: Seems like while you are in the process of editing a UITextField
with the built-in iOS keyboard, the "text" property of the text field is not updated with every new letter typed/removed. Instead, the text field object gets updated "as a whole" after you resign the first responder status of the text field.
Android supports string formatting using HTML tags in the strings xml. So the following would work:
<string name="label_testinghtmltags"><u>This text has an underscore</u></string>
Then you just use it as you normally would. You can see more in the documentation here
Update:
To further expand on the answer, the documentation says:
... the
format(String, Object...)
andgetString(int, Object...)
methods strip all the style information from the string. . The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place
For example, the resulting string from the following code snippet will not show up as containing underscored elements:
<string name="html_bold_test">This <u>%1$s</u> has an underscore</string>
String result = getString(R.string.html_bold_test, "text")
However the result from the following snippet would contain underscores:
<string name="html_bold_test">This <u> %1$s </u> has an underscore</string>
String result = Html.fromHtml(getString(R.string.html_bold_test, "text"))
My task was kill everything matching regexp that is placed in specific directory (after selenium tests not everything got stop). This worked for me:
for i in `ps aux | egrep "firefox|chrome|selenium|opera"|grep "/home/dir1/dir2"|awk '{print $2}'|uniq`; do kill $i; done
The accepted answer here gave me unpredictable results, sometimes weirdly adding months and years.
The most reliable way I could find was found here Add days to Javascript Date object, and also increment month
var dayOffset = 20;
var millisecondOffset = dayOffset * 24 * 60 * 60 * 1000;
december.setTime(december.getTime() + millisecondOffset);
EDIT: Even though it has worked for some people, I don't think it is entirely correct. I would recommend going with a more popular answer or using something like http://momentjs.com/
It depends on the configuration of the application as well as on IIS as this gentleman in the below link has rightfully explained. Please see his article below
http://richhewlett.com/2011/02/15/getting-a-users-username-in-asp-net/
The reason your original code doesn't compile is that <? extends Serializable>
does not mean, "any class that extends Serializable," but "some unknown but specific class that extends Serializable."
For example, given the code as written, it is perfectly valid to assign new TreeMap<String, Long.class>()
to expected
. If the compiler allowed the code to compile, the assertThat()
would presumably break because it would expect Date
objects instead of the Long
objects it finds in the map.
You need to use the command echo $PATH
to display the PATH variable or you can just execute set
or env
to display all of your environment variables.
By typing $PATH
you tried to run your PATH variable contents as a command name.
Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:
/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin
To me this list appears to be complete.
Close the emulator if already opened. Right click on your project ->Run as -> run configurations -> Run. After the emulator launched: Right click on your project ->Run as ->android project.
In C# 7.1 and later, type can be inferred by using the default
literal instead of the default
operator so it can be written as below:
v2 = v1 ?? default;
I got it working using the following code.
var green= "Green";
var color : Color= <Color>Color[green];
The answers referring to simply calling array()
are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap
an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):
if (myByteBuffer.hasArray()) {
return new String(myByteBuffer.array(),
myByteBuffer.arrayOffset() + myByteBuffer.position(),
myByteBuffer.remaining());
} else {
final byte[] b = new byte[myByteBuffer.remaining()];
myByteBuffer.duplicate().get(b);
return new String(b);
}
For the concerns related to encoding, see Andy Thomas' answer.
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat
that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat
that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat
like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
Even simpler to remember than the sed
approach is to use awk
.
Here is an example, which you can run on your local machine:
kubectl describe pod `<podName>` | grep IP | awk '{print $2}'
The IP itself is on column 2 of the output, hence $2
.
Since the question mentioned finding the keys, I figured I'd mention that to show every key and value pair, you could do it like this (based on Kevin's answer):
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
console.log( localStorage.key( i ) + ": " + localStorage.getItem( localStorage.key( i ) ) );
}
This will log the data in the format "key: value"
(Kevin: feel free to just take this info into the your answer if you want!)