Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.
Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E
Note: my answers best fits for mobile devices.
From what I understand they are independent of one another. By keeping the session timeout less than or equal to the authentication timeout, you can make sure any user-specific session variables are not persisted after the authentication has timed out (if that is your concern, which I think is the normal one when asking this question). Of course, you'll have to manually handle the disposal of session variables upon log-out.
Here is a decent response that may answer your question or at least point you in the right direction:
print( "hello " +k+ " " +ln);
where k
and ln
are variables
A functor is a higher-order function that applies a function to the parametrized(ie templated) types. It is a generalization of the map higher-order function. For example, we could define a functor for std::vector
like this:
template<class F, class T, class U=decltype(std::declval<F>()(std::declval<T>()))>
std::vector<U> fmap(F f, const std::vector<T>& vec)
{
std::vector<U> result;
std::transform(vec.begin(), vec.end(), std::back_inserter(result), f);
return result;
}
This function takes a std::vector<T>
and returns std::vector<U>
when given a function F
that takes a T
and returns a U
. A functor doesn't have to be defined over container types, it can be defined for any templated type as well, including std::shared_ptr
:
template<class F, class T, class U=decltype(std::declval<F>()(std::declval<T>()))>
std::shared_ptr<U> fmap(F f, const std::shared_ptr<T>& p)
{
if (p == nullptr) return nullptr;
else return std::shared_ptr<U>(new U(f(*p)));
}
Heres a simple example that converts the type to a double
:
double to_double(int x)
{
return x;
}
std::shared_ptr<int> i(new int(3));
std::shared_ptr<double> d = fmap(to_double, i);
std::vector<int> is = { 1, 2, 3 };
std::vector<double> ds = fmap(to_double, is);
There are two laws that functors should follow. The first is the identity law, which states that if the functor is given an identity function, it should be the same as applying the identity function to the type, that is fmap(identity, x)
should be the same as identity(x)
:
struct identity_f
{
template<class T>
T operator()(T x) const
{
return x;
}
};
identity_f identity = {};
std::vector<int> is = { 1, 2, 3 };
// These two statements should be equivalent.
// is1 should equal is2
std::vector<int> is1 = fmap(identity, is);
std::vector<int> is2 = identity(is);
The next law is the composition law, which states that if the functor is given a composition of two functions, it should be the same as applying the functor for the first function and then again for the second function. So, fmap(std::bind(f, std::bind(g, _1)), x)
should be the same as fmap(f, fmap(g, x))
:
double to_double(int x)
{
return x;
}
struct foo
{
double x;
};
foo to_foo(double x)
{
foo r;
r.x = x;
return r;
}
std::vector<int> is = { 1, 2, 3 };
// These two statements should be equivalent.
// is1 should equal is2
std::vector<foo> is1 = fmap(std::bind(to_foo, std::bind(to_double, _1)), is);
std::vector<foo> is2 = fmap(to_foo, fmap(to_double, is));
No, but you can in Scala! (And then compile that and run it using any Java implementation!!!!)
Now, if you want to do it the easy way in java, use the Apache commons-lang package. Assuming you're using maven, add this dependency to your pom.xml:
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
And then use StringUtils.repeat as follows:
import org.apache.commons.lang.StringUtils
...
someNum = sumNum + StringUtils.repeat("0", 3);
sudo apt-get install php-mbstring
# if your are using php 7.1
sudo apt-get install php7.1-mbstring
# if your are using php 7.2
sudo apt-get install php7.2-mbstring
Please import Quartzcore framework
then you have to set setMaskToBounds
to TRUE
this the very important line.
Then: [[yourView layer] setCornerRadius:5.0f];
I have come to the conclusion that this is not possible without any plugins.
MySQL will also report "Column count doesn't match value count at row 1" if you try to insert multiple rows without delimiting the row sets in the VALUES section with parentheses, like so:
INSERT INTO `receiving_table`
(id,
first_name,
last_name)
VALUES
(1002,'Charles','Babbage'),
(1003,'George', 'Boole'),
(1001,'Donald','Chamberlin'),
(1004,'Alan','Turing'),
(1005,'My','Widenius');
This is quite likely the simplest way to achieve what you are looking for.
In order to use this map
function in this instance, we will have to pass a currentValue
(always-required) parameter, as well an index
(optional) parameter.
In the below example, station
is our currentValue
, and x
is our index
.
station
represents the current value of the object within the array as it is iterated over.
x
automatically increments; increasing by one each time a new object is mapped.
render () {
return (
<div>
{stations.map((station, x) => (
<div key={x}> {station} </div>
))}
</div>
);
}
What Thomas Valadez had answered, while it had provided the best/simplest method to render a component from an array of objects, it had failed to properly address the way in which you would assign a key during this process.
There is no right way, but you can initialize an array of literals:
char **values = (char *[]){"a", "b", "c"};
or you can allocate each and initialize it:
char **values = malloc(sizeof(char*) * s);
for(...)
{
values[i] = malloc(sizeof(char) * l);
//or
values[i] = "hello";
}
Also, this could make it works:
@{
Html.RenderPartial("your view", your_model, ViewData);
}
or
@{
Html.RenderPartial("your view", your_model);
}
For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread
Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:
import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()
It will show this:
In my experience, to use wmic
in a script, you need to get the nested quoting right:
wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive
quoting both the query and the name. But wmic will only uninstall things installed via windows installer.
After you determine that a number is composite (not prime), your work is done. You can exit the loop with break
.
while num > a :
if num%a==0 & a!=num:
print('not prime')
break # not going to update a, going to quit instead
else:
print('prime')
a=(num)+1
Also, you might try and become more familiar with some constructs in Python. Your loop can be shortened to a one-liner that still reads well in my opinion.
any(num % a == 0 for a in range(2, num))
My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.
Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo'
, then the selector will be 'td[id^="foo"]'
.
Note that the quotes are mandatory: [id^="...."]
.
Source: http://api.jquery.com/attribute-starts-with-selector/
Possibly close related code of Pascal
@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
public enum Right {
READ(100), WRITE(200), EDITOR(300);
private Integer value;
private Right(Integer value) {
this.value = value;
}
// Reverse lookup Right for getting a Key from it's values
private static final Map<Integer, Right> lookup = new HashMap<Integer, Right>();
static {
for (Right item : Right.values())
lookup.put(item.getValue(), item);
}
public Integer getValue() {
return value;
}
public static Right getKey(Integer value) {
return lookup.get(value);
}
};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
@Column(name = "RIGHT_ID")
private Integer rightId;
public Right getRight() {
return Right.getKey(this.rightId);
}
public void setRight(Right right) {
this.rightId = right.getValue();
}
}
You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.
Also, move the .on() outside of the .click() function, as you only need to set it once.
http://jsfiddle.net/samliew/3AJcj/2/
$(document).ready(function(){
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
Find the <SHA#>
for the commit you want to go. You can find it in github or by typing git log
or git reflog show
at the command line and then do
git reset --hard <SHA#>
Bring up the Package Manager Console in Visual Studio - it's in Tools / NuGet Package Manager / Package Manager Console. Then run the Install-Package command:
Install-Package Common.Logging -Version 1.2.0
See the command reference for details.
Edit:
In order to list versions of a package you can use the Get-Package command with the remote argument and a filter:
Get-Package -ListAvailable -Filter Common.Logging -AllVersions
By pressing tab after the version option in the Install-Package
command, you get a list of the latest available versions.
It is kind of standard/best practice. There are already answers listing scenarios, but for your second question:
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
Public constants and fields initialized at declaration should be "static final" rather than merely "final"
These are some of the reasons why it should be like this:
Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.
Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.
public void breadthFirstSearch(Node root, Consumer<String> c) {
List<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.remove(0);
c.accept(n.value);
if (n.left != null)
queue.add(n.left);
if (n.right != null)
queue.add(n.right);
}
}
And the Node:
public static class Node {
String value;
Node left;
Node right;
public Node(final String value, final Node left, final Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
First convert list to sets.
// create an empty set
Set<T> set = new HashSet<>();
// Add each element of list into the set
for (T t : list)
set.add(t);
You can use Sets.difference(Set1, Set2)
, which returns extra items present in Set1.
You can use Sets.difference(Set2, Set1)
, which returns extra items present in Set2.
You can use this and then you can add just a class
form from bootstrap.
(does not matter which version)
<div class="form-group">
<label >Begin voorverkoop periode</label>
<input type="date" name="bday" max="3000-12-31"
min="1000-01-01" class="form-control">
</div>
<div class="form-group">
<label >Einde voorverkoop periode</label>
<input type="date" name="bday" min="1000-01-01"
max="3000-12-31" class="form-control">
</div>
Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
Problem fixed, download https://curl.haxx.se/ca/cacert.pem and put it "somewhere", and add this line in php.ini
:
curl.cainfo = "C:/somewhere/cacert.pem"
PS: I got this error by trying to install module on drupal with xampp.
Using ruby 2.4 you can do the same thing using transform_values
, this feature extracted from rails to ruby.
h = {a: 1, b: 2, c: 3}
h.transform_values { |v| v * 10 }
#=> {a: 10, b: 20, c: 30}
We had an interesting issue come up at a company I previously worked at where we used friend to decent affect. I worked in our framework department we created a basic engine level system over our custom OS. Internally we had a class structure:
Game
/ \
TwoPlayer SinglePlayer
All of these classes were part of the framework and maintained by our team. The games produced by the company were built on top of this framework deriving from one of Games children. The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes. The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.
Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.
It is possible.
When you use Return inside a procedure, the control is transferred to the calling program which calls the procedure. It is like an exit in loops.
It won't return any value.
Another use case could be an event dispatcher bound at runtime:
MyClass = function () {
this.events = {};
// Fire up an event (most probably from inside an instance method)
this.OnFirstRun();
// Fire up other event (most probably from inside an instance method)
this.OnLastRun();
}
MyClass.prototype.dispatchEvents = function () {
var EventStack=this.events[GetFunctionName()], i=EventStack.length-1;
do EventStack[i]();
while (i--);
}
MyClass.prototype.setEvent = function (event, callback) {
this.events[event] = [];
this.events[event].push(callback);
this["On"+event] = this.dispatchEvents;
}
MyObject = new MyClass();
MyObject.setEvent ("FirstRun", somecallback);
MyObject.setEvent ("FirstRun", someothercallback);
MyObject.setEvent ("LastRun", yetanothercallback);
The advantage here is the dispatcher can be easily reused and doesn't have to receive the dispatch queue as an argument, instead it comes implicit with the invocation name...
In the end, the general case presented here would be "using the function name as an argument so you don't have to pass it explicitly", and that could be useful in many cases, such as the jquery animate() optional callback, or in timeouts/intervals callbacks, (ie you only pass a funcion NAME).
Taking from a few of these answers and some suggestions elsewhere, the following works great for hover menus (I'm using this with Bootstrap 3, specifically):
nav .dropdown-menu {
display: block;
overflow: hidden;
max-height: 0;
opacity: 0;
transition: max-height 500ms, opacity 300ms;
-webkit-transition: max-height 500ms, opacity 300ms;
}
nav .dropdown:hover .dropdown-menu {
max-height: 500px;
opacity: 1;
transition: max-height 0, opacity 300ms;
-webkit-transition: max-height 0, opacity 300ms;
}
You could also use height
in place of max-height
if you specify both values since height:auto
is not allowed with transition
s. The hover value of max-height
needs to be greater than the height
of the menu can possibly be.
The following works:
@NonCPS
def printParams() {
env.getEnvironment().each { name, value -> println "Name: $name -> Value $value" }
}
printParams()
Note that it will most probably fail on first execution and require you approve various groovy methods to run in jenkins sandbox. This is done in "manage jenkins/in-process script approval"
The list I got included:
Put the javascript part and the end right before the closing </body>
then it should work.
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
alert(a + b);
window.external.values(a.value, b.value, c.value, d.value, e.value);
}
</script>
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
EDIT 7/1/15:
I wrote this answer a pretty long time ago and haven't been keeping up a lot with angular for a while, but it seems as though this answer is still relatively popular, so I wanted to point out that a couple of the point @nicolas makes below are good. For one, injecting $rootScope and attaching the helpers there will keep you from having to add them for every controller. Also - I agree that if what you're adding should be thought of as Angular services OR filters, they should be adopted into the code in that manner.
Also, as of the current version 1.4.2, Angular exposes a "Provider" API, which is allowed to be injected into config blocks. See these resources for more:
https://docs.angularjs.org/guide/module#module-loading-dependencies
AngularJS dependency injection of value inside of module.config
I don't think I'm going to update the actual code blocks below, because I'm not really actively using Angular these days and I don't really want to hazard a new answer without feeling comfortable that it's actually conforming to new best practices. If someone else feels up to it, by all means go for it.
EDIT 2/3/14:
After thinking about this and reading some of the other answers, I actually think I prefer a variation of the method brought up by @Brent Washburne and @Amogh Talpallikar. Especially if you're looking for utilities like isNotString() or similar. One of the clear advantages here is that you can re-use them outside of your angular code and you can use them inside of your config function (which you can't do with services).
That being said, if you're looking for a generic way to re-use what should properly be services, the old answer I think is still a good one.
What I would do now is:
app.js:
var MyNamespace = MyNamespace || {};
MyNamespace.helpers = {
isNotString: function(str) {
return (typeof str !== "string");
}
};
angular.module('app', ['app.controllers', 'app.services']).
config(['$routeProvider', function($routeProvider) {
// Routing stuff here...
}]);
controller.js:
angular.module('app.controllers', []).
controller('firstCtrl', ['$scope', function($scope) {
$scope.helpers = MyNamespace.helpers;
});
Then in your partial you can use:
<button data-ng-click="console.log(helpers.isNotString('this is a string'))">Log String Test</button>
Old answer below:
It might be best to include them as a service. If you're going to re-use them across multiple controllers, including them as a service will keep you from having to repeat code.
If you'd like to use the service functions in your html partial, then you should add them to that controller's scope:
$scope.doSomething = ServiceName.functionName;
Then in your partial you can use:
<button data-ng-click="doSomething()">Do Something</button>
Here's a way you might keep this all organized and free from too much hassle:
Separate your controller, service and routing code/config into three files: controllers.js, services.js, and app.js. The top layer module is "app", which has app.controllers and app.services as dependencies. Then app.controllers and app.services can be declared as modules in their own files. This organizational structure is just taken from Angular Seed:
app.js:
angular.module('app', ['app.controllers', 'app.services']).
config(['$routeProvider', function($routeProvider) {
// Routing stuff here...
}]);
services.js:
/* Generic Services */
angular.module('app.services', [])
.factory("genericServices", function() {
return {
doSomething: function() {
//Do something here
},
doSomethingElse: function() {
//Do something else here
}
});
controller.js:
angular.module('app.controllers', []).
controller('firstCtrl', ['$scope', 'genericServices', function($scope, genericServices) {
$scope.genericServices = genericServices;
});
Then in your partial you can use:
<button data-ng-click="genericServices.doSomething()">Do Something</button>
<button data-ng-click="genericServices.doSomethingElse()">Do Something Else</button>
That way you only add one line of code to each controller and are able to access any of the services functions wherever that scope is accessible.
I think the problem is not in sub-query but in WHERE clause of outer query. When you use
WHERE account_code between 503100 and 503105
SQL server will try to convert every value in your Account_code field to integer to test it in provided condition. Obviously it will fail to do so if there will be non-integer characters in some rows.
Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.
I think you should refactor your packages in more convenient hierarchy, so they are out of the base package.
But if you can't do this, try:
<context:component-scan base-package="com.example">
...
<context:exclude-filter type="regex" expression="com\.example\.ignore.*"/>
</context:component-scan>
Here you could find more examples: Using filters to customize scanning
You guessed right, HTTP Headers are not part of the URL.
And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.
The most common scenario is that your server consumes a third party REST Api.
To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).
The code to forge the request, send it and finally get the response back depends on your server side language.
If you want to test a REST Api you may use curl
tool from the command line.
curl
makes a request and outputs the response to stdout (unless otherwise instructed).
In your case the test request would be issued like this:
$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'
The H
or --header
directive sets a header and its value.
Using foreach:
... endforeach;
does not only make things readable, it also makes least load for memory as introduced in PHP docs
So for big apps, receiving many users this would be the best solution
We're talking about C++ right? Why on earth are we still using macros!?
C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned.
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
Aside from that I have a few other gripes, particularly with the accepted answer :)
// this is used in C, not C++. if you want to use printf, instead include <cstdio>
//#include <stdio.h>
// instead you should use the iostream libs
#include <iostream>
// not only is this a C include, it's totally unnecessary!
//#include <stdarg.h>
// Macros - not type-safe, has side-effects. Use inline functions instead
//#define BOOL_STR(b) (b?"true":"false")
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
int main (int argc, char const *argv[]) {
bool alpha = true;
// printf? that's C, not C++
//printf( BOOL_STR(alpha) );
// use the iostream functionality
std::cout << BoolToString(alpha);
return 0;
}
Cheers :)
@DrPizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?
I'm using:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", DEFAULT_NAMESPACE);
using (var stream = new MemoryStream())
{
var someone = new Person
{
FirstName = "Donald",
LastName = "Duck"
};
serializer.Serialize(stream, someone, namespaces);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
To get the following XML:
<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
<FirstName>Donald</FirstName>
<LastName>Duck</LastName>
</Person>
If you don't want the namespace, just set DEFAULT_NAMESPACE to "".
$("input").click(function(){
var name = $(this).attr("name");
$('input[name="' + name + '"]').hide();
});
Also works with ID:
var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
when, (sometimes)
$('input#' + id).hide();
does not work, as it should.
You can even do both:
$('input[name="' + name + '"][id="' + id + '"]').hide();
$time = '10:09';
$timestamp = strtotime($time);
$timestamp_one_hour_later = $timestamp + 3600; // 3600 sec. = 1 hour
// Formats the timestamp to HH:MM => outputs 11:09.
echo strftime('%H:%M', $timestamp_one_hour_later);
// As crolpa suggested, you can also do
// echo date('H:i', $timestamp_one_hour_later);
Check PHP manual for strtotime(), strftime() and date() for details.
BTW, in your initial code, you need to add some quotes otherwise you will get PHP syntax errors:
$time = 10:09; // wrong syntax
$time = '10:09'; // syntax OK
$time = date(H:i, strtotime('+1 hour')); // wrong syntax
$time = date('H:i', strtotime('+1 hour')); // syntax OK
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function(){
//do something depressing
},
success: function(){
//do something cheerful :)
}
});
from: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06
Do you see any servers in server view in eclipse? Probably simply you have not created any server instances.
You should use the I/O Library where you can find all functions at the io
table and then use file:read
to get the file content.
local open = io.open
local function read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
end
local fileContent = read_file("foo.html");
print (fileContent);
I believe that most of these answers are for bootstrap 2. I ran into the same issue for bootstrap 3 and wanted to share my fix. Like my previous answer for bootstrap 2, this will still do an opacity fade, but will NOT do the slide transition.
You can either change the modals.less or the theme.css files, depending on your workflow. If you haven't spent any quality time with less, I'd highly recommend it.
for less, find the following code in MODALS.less
&.fade .modal-dialog {
.translate(0, -25%);
.transition-transform(~"0.3s ease-out");
}
&.in .modal-dialog { .translate(0, 0)}
then change the -25%
to 0%
Alternatively, if you're using just the css, find the following in theme.css
:
.modal.fade .modal-dialog {
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
transform: translate(0, -25%);
-webkit-transition: -webkit-transform 0.3s ease-out;
-moz-transition: -moz-transform 0.3s ease-out;
-o-transition: -o-transform 0.3s ease-out;
transition: transform 0.3s ease-out;
}
and then change the -25%
to 0%
.
Right below the RewriteEngine On
line, add:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R] # <- for test, for prod use [L,R=301]
to enforce a no-trailing-slash policy.
To enforce a trailing-slash policy:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R] # <- for test, for prod use [L,R=301]
EDIT: commented the R=301
parts because, as explained in a comment:
Be careful with that
R=301
! Having it there makes many browsers cache the .htaccess-file indefinitely: It somehow becomes irreversible if you can't clear the browser-cache on all machines that opened it. When testing, better go with simpleR
orR=302
After you've completed your tests, you can use R=301
.
I usually do this in the thread handling the json response:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.
I found it in http://www.baeldung.com/hikaricp and it works.
Your pom.xml
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.3</version>
</dependency>
Your data.xml
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"
/>
Your jdbc.properties
jdbc.driverClassName=org.postgresql.Driver
jdbc.dialect=org.hibernate.dialect.PostgreSQL94Dialect
jdbc.databaseurl=jdbc:postgresql://localhost:5432/dev_db
jdbc.username=dev
jdbc.password=dev
The precise wording of the question makes me think it's impossible.
return
to me means you have a function, which you have passed a string as a parameter.
You cannot change this parameter. Assigning to it will only change the value of the parameter within the function, not the passed in string. E.g.
>>> def removeAndReturnLastCharacter(a):
c = a[-1]
a = a[:-1]
return c
>>> b = "Hello, Gaukler!"
>>> removeAndReturnLastCharacter(b)
!
>>> b # b has not been changed
Hello, Gaukler!
Here's how to do it:
var myVideo = document.getElementById("my-video")
myVideo.controls = false;
Working example: https://jsfiddle.net/otnfccgu/2/
See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp
Aptana supports this and I use it for all of my web development now.
If you enabled html5mode as others have said, and create an .htaccess
file with the following contents (adjust for your needs):
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ./index.html [L]
Users will be directed to the your app when they enter a proper route, and your app will read the route and bring them to the correct "page" within it.
EDIT: Just make sure not to have any file or directory names conflict with your routes.
Since no one else has mentioned this…
It is not safe to compare the results of System.nanoTime()
calls between different threads. Even if the events of the threads happen in a predictable order, the difference in nanoseconds can be positive or negative.
System.currentTimeMillis()
is safe for use between threads.
Further to just simply turning off Source Maps in Chrome - I've done a little digging and found that using Web Essentials to create the source maps seems to be the issue.
For whatever reason, if I use an external compiler (Koala) I can successfully create working source maps in Chrome (no errors). Whereas if I use Web Essentials, the source maps fail to parse.
Hope this helps someone.
This is a common problem. You're almost certainly running into permissions issues. To solve it, make sure that the apache
user has read/write access to your entire repository. To do that, chown -R apache:apache *
, chmod -R 664 *
for everything under your svn repository.
Also, see here and here if you're still stuck.
The "664" string is an octal (base 8) representation of the permissions. There are three digits here, representing permissions for the owner, group, and everyone else (sometimes called "world"), respectively, for that file or directory.
Notice that each base 8 digit can be represented with 3 bits (000 for '0' through 111 for '7'). Each bit means something:
For example, 764 on a file would mean that:
Hope that clears things up!
Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like
template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64
Using name on a select option is not valid.
Other have suggested the data- attribute, an alternative is a lookup table
Here the "this" refers to the select so no need to "find" the option
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
$('#band_type_choices').on('change', function() {_x000D_
$('.checkboxlist').hide();_x000D_
var idx = this.selectedIndex;_x000D_
if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
});_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
<option vlaue="0"></option>_x000D_
<option value="100" name="acoustic">Acoustic</option>_x000D_
<option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
<option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
<option value="0" name="party">Party</option>_x000D_
<option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
<option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
<option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
<input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
<input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
<input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
<input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
<input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
<input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
<input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
<input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
<input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
<input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
<input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
You can also use shorthand for describe as desc
for table description.
desc [db_name.]table_name;
or
use db_name;
desc table_name;
You can also use explain
for table description.
explain [db_name.]table_name;
See official doc
Will give output like:
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| age | int(10) | YES | | NULL | |
| sex | varchar(10) | YES | | NULL | |
| sal | int(10) | YES | | NULL | |
| location | varchar(20) | YES | | Pune | |
+----------+-------------+------+-----+---------+-------+
I had the same error as described by title, but for me it was simply installing Microsoft access 12.0 oledb redistributable to use with LinqToExcel.
You can use this plugin, but for printing purpose i have added some code like
<button onclick="window.print();">Print</button>
and for saving image <button onclick="savePhoto();">Save Picture</button>
function savePhoto() {
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
window.location = img;}
checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app
Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>
I think I got this from not explicitly deleting some tables from the edmx before renaming and re-adding them. Instead, I just renamed the tables and then did an Update Model from Database, thinking it would see them gone, and delete them from model. I then did another Update Model from Database and added the renamed tables.
The site was working with the new tables, but I had the error. Eventually, I noticed the original tables were still in the model. I deleted them from the model (click them in edmx screen, delete key), and then the error went away.
http://en.wikipedia.org/wiki/Division_by_zero
http://en.wikipedia.org/wiki/Unix_signal#SIGFPE
This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0
IS division by zero and as such, will trigger a SIGFPE being thrown.
Here is a very simple way:
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True"
CommandArgument='<%# Container.DataItemIndex %>' />
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>
The span elements are inline an thus don't break the flow of the paragraph, only style in between the tags.
This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)
// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;
// Rotation information
double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);
A bit off on the "duck typing" definition -- dict.keys()
returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)
In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list()
.
Very similarly for zip()
-- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?
This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.
dict.keys()
should work with comprehensions, though -- check carefully for typos or something... it works fine for me:
>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]
Here is a better script:
$('#mainimage').click(function(e)
{
var offset_t = $(this).offset().top - $(window).scrollTop();
var offset_l = $(this).offset().left - $(window).scrollLeft();
var left = Math.round( (e.clientX - offset_l) );
var top = Math.round( (e.clientY - offset_t) );
alert("Left: " + left + " Top: " + top);
});
<select>
<option selected disabled>Choose one</option>
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
<option value="queenstown">Queenstown</option>
</select>
Using selected
and disabled
will make "Choose one" be the default selected value, but also make it impossible for the user to actually select the item, like so:
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
You have very little control over a browser's printing methods. At most you can SUGGEST, but if the browser's print settings have "don't print background images", there's nothing you can do without rewriting your page to turn the background images into floating "foreground" images that happen to be behind other content.
What I would do, looking at your specific need:
Say you have list a
with some values, and your keys are in the attribute x
of the objects stored in list b
keys = {i:j.x for i,j in zip(a, b)}
a.sort(key=keys.__get_item__)
With this method you get your list ordered without having to construct the intermediate permutation list you were asking for.
The simplest way for me to create and reuse a library project:
file > new > new module
(and answer the UI questions)include ':myLibrary'
check/or add if in the file build.gradle:
dependencies {
...
compile project(':myLibrary')
}
To reuse this library module in another project, copy it's folder in the project instead of step 1 and do the steps 2 and 3.
You can also create a new studio application project You can easily change an existing application module to a library module by changing the plugin assignment in the build.gradle file to com.android.library.
apply plugin: 'com.android.application'
android {...}
to
apply plugin: 'com.android.library'
android {...}
more here
I think we just need to enter the inputs to clean everything
$("#your_div").click(function() {
$(".error").html('');
$(".error").removeClass("error");
});
This is an older question, and there are many different ways to do this. The most complete answer, IMHO, is found here: https://gist.github.com/vielhuber/f2c6bdd1ed9024023fe4 . (Pasting and formatting the code here didn't work for me)
/* *Object: UserDefinedFunction [dbo].[Split] Script Date: 10/04/2013 18:18:38* */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Split]
(@List varchar(8000),@SplitOn Nvarchar(5))
RETURNS @RtnValue table
(Id int identity(1,1),Value nvarchar(100))
AS
BEGIN
Set @List = Replace(@List,'''','')
While (Charindex(@SplitOn,@List)>0)
Begin
Insert Into @RtnValue (value)
Select
Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))
Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
End
Insert Into @RtnValue (Value)
Select Value = ltrim(rtrim(@List))
Return
END
go
Select *
From [Clv].[Split] ('1,2,3,3,3,3,',',')
GO
If your SQL doesn't support NULLS FIRST
or NULLS LAST
, the simplest way to do this is to use the value IS NULL
expression:
ORDER BY Next_Contact_Date IS NULL, Next_Contact_Date
to put the nulls at the end (NULLS LAST
) or
ORDER BY Next_Contact_Date IS NOT NULL, Next_Contact_Date
to put the nulls at the front. This doesn't require knowing the type of the column and is easier to read than the CASE
expression.
EDIT: Alas, while this works in other SQL implementations like PostgreSQL and MySQL, it doesn't work in MS SQL Server. I didn't have a SQL Server to test against and relied on Microsoft's documentation and testing with other SQL implementations. According to Microsoft, value IS NULL
is an expression that should be usable just like any other expression. And ORDER BY
is supposed to take expressions just like any other statement that takes an expression. But it doesn't actually work.
The best solution for SQL Server therefore appears to be the CASE
expression.
public int read(byte[] a) throws IOException {
try {
return in.read(a);
} catch (final Throwable t) {
/* can do something here, like in=null; */
throw t;
}
}
This is a concrete example where the method throws an IOException
. The final
means t
can only hold an exception thrown from the try block. Additional reading material can be found here and here.
A few years later, but this uses Linq, returns -1 if not found, doesn't create extra objects, and should short-circuit when found [as opposed to iterating over the entire IEnumerable]:
public static int IndexOf<T>(this IEnumerable<T> list, T item)
{
return list.Select((x, index) => EqualityComparer<T>.Default.Equals(item, x)
? index
: -1)
.FirstOr(x => x != -1, -1);
}
Where 'FirstOr' is:
public static T FirstOr<T>(this IEnumerable<T> source, T alternate)
{
return source.DefaultIfEmpty(alternate)
.First();
}
public static T FirstOr<T>(this IEnumerable<T> source, Func<T, bool> predicate, T alternate)
{
return source.Where(predicate)
.FirstOr(alternate);
}
Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name
. You can also do it by assigning the variable to None
a = 10
print a
del a
print a ## throws an error here because it's been deleted already.
The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del
has no real effect, since those names would have been deleted as they went out of scope anyway.
Just FYI:
html should be table & width:100%. span should be margin: auto;
I don't think it's a good idea to process response received from the 3rd party server. This will only increase your proxy server's memory footprint. Further, it's the reason why your code is not working.
Instead try passing the response through to the client. Consider following snippet:
var http = require('http');
http.createServer(onRequest).listen(3000);
function onRequest(client_req, client_res) {
console.log('serve: ' + client_req.url);
var options = {
hostname: 'www.google.com',
port: 80,
path: client_req.url,
method: client_req.method,
headers: client_req.headers
};
var proxy = http.request(options, function (res) {
client_res.writeHead(res.statusCode, res.headers)
res.pipe(client_res, {
end: true
});
});
client_req.pipe(proxy, {
end: true
});
}
Depending on the type of input types you're using on your form, you should be able to grab them using standard jQuery expressions.
Example:
// change forms[0] to the form you're trying to collect elements from... or remove it, if you need all of them
var input_elements = $("input, textarea", document.forms[0]);
Check out the documentation for jQuery expressions on their site for more info: http://docs.jquery.com/Core/jQuery#expressioncontext
WAR stands for Web application ARchive
JAR stands for Java ARchive
The closed hand cursor is not 16x16. If you would need them in the same dimensions, here you have both of them in 16x16 px
Or if you need original cursors:
https://www.google.com/intl/en_ALL/mapfiles/openhand.cur https://www.google.com/intl/en_ALL/mapfiles/closedhand.cur
I added it for all fieldsets with
fieldset {
border: 1px solid lightgray;
}
I didnt work if I set it separately using for example
border-color : red
. Then a black line was drawn next to the red line.
Div is a block element and span is an inline element and its width depends upon the content of it self where div does not
You can't run two SQL statements into one like you are doing.
You can't "execute" a select query.
db is an object and you haven't set it to anything: (e.g. set db = currentdb)
In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.
You might want to be a bit more specific about the date you are inserting:
INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"
There are two main differences.
The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.
So, for a unidirectional @ManyToOne
association, it means you can only access the relationship from the child side where the foreign key resides.
If you have a unidirectional @OneToMany
association, it means you can only access the relationship from the parent side which manages the foreign key.
For the bidirectional @OneToMany
association, you can navigate the association in both ways, either from the parent or from the child side.
You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.
The second aspect is related to performance.
@OneToMany
, unidirectional associations don't perform as well as bidirectional ones.@OneToOne
, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.@ManyToMany
, the collection type makes quite a difference as Sets
perform better than Lists
.If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
For those situations where width of the items you do want to flex-end
is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start
with flex:1
This will cause the pseudo flex-start
item to fill the container, just format it to text-align:left
or whatever.
This Blog Post describes various styling aspects of EditText
and AutoCompleteTextView
wrapped by TextInputLayout
.
For EditText
and AppCompat lib 22.1.0+ you can set theme attribute with some theme related settings:
<style name="StyledTilEditTextTheme">
<item name="android:imeOptions">actionNext</item>
<item name="android:singleLine">true</item>
<item name="colorControlNormal">@color/greyLight</item>
<item name="colorControlActivated">@color/blue</item>
<item name="android:textColorPrimary">@color/blue</item>
<item name="android:textSize">@dimen/styledtil_edit_text_size</item>
</style>
<style name="StyledTilEditText">
<item name="android:theme">@style/StyledTilEditTextTheme</item>
<item name="android:paddingTop">4dp</item>
</style>
and apply them on EditText
:
<EditText
android:id="@+id/etEditText"
style="@style/StyledTilEditText"
For AutoCompleteTextView
things are more complicated because wrapping it in TextInputLayout
and applying this theme breaks floating label behaviour.
You need to fix this in code:
private void setStyleForTextForAutoComplete(int color) {
Drawable wrappedDrawable = DrawableCompat.wrap(autoCompleteTextView.getBackground());
DrawableCompat.setTint(wrappedDrawable, color);
autoCompleteTextView.setBackgroundDrawable(wrappedDrawable);
}
and in Activity.onCreate
:
setStyleForTextForAutoComplete(getResources().getColor(R.color.greyLight));
autoCompleteTextView.setOnFocusChangeListener((v, hasFocus) -> {
if(hasFocus) {
setStyleForTextForAutoComplete(getResources().getColor(R.color.blue));
} else {
if(autoCompleteTextView.getText().length() == 0) {
setStyleForTextForAutoComplete(getResources().getColor(R.color.greyLight));
}
}
});
I set the max width for my video to be 100%. On phones the video automatically fits the width of the screen. Since the embedded video is only 560px wide, I just added a 10% left-margin to the iframe, and put a "0" back in for the margin for the mobile CSS (to allow the full width view). I did't want to bother putting a div around every video...
Desktop CSS:
iframe {_x000D_
margin-left: 10%;_x000D_
}
_x000D_
Mobile CSS:
iframe {_x000D_
margin-left: 0;_x000D_
}
_x000D_
Worked perfect for my blog (Botanical Amy).
I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final")
.
When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.
Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.
libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)
This is for play 2.2.x
. In previous versions there were some differences in the build files.
In my case this was because a file named ociw32.dll had been placed in c:\windows\system32. This is however only allowed to exist in c:\oracle\11.2.0.3\bin.
Deleting the file from system32, which had been placed there by an installation of Crystal Reports, fixed this issue
while spring.jpa.open-in-view was true, I didn't have any problem with getOne but after setting it to false , i got LazyInitializationException. Then problem was solved by replacing with findById.
Although there is another solution without replacing the getOne method, and that is put @Transactional at method which is calling repository.getOne(id). In this way transaction will exists and session will not be closed in your method and while using entity there would not be any LazyInitializationException.
You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.
Type java -help for the options. In particular, see:
-version:<value>
require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
SQL
is a query language to operate on sets.
It is more or less standardized, and used by almost all relational database management systems: SQL Server, Oracle, MySQL, PostgreSQL, DB2, Informix, etc.
PL/SQL
is a proprietary procedural language used by Oracle
PL/pgSQL
is a procedural language used by PostgreSQL
TSQL
is a proprietary procedural language used by Microsoft in SQL Server.
Procedural languages are designed to extend SQL's abilities while being able to integrate well with SQL. Several features such as local variables and string/data processing are added. These features make the language Turing-complete.
They are also used to write stored procedures: pieces of code residing on the server to manage complex business rules that are hard or impossible to manage with pure set-based operations.
It seems you can just display both dfs using a comma in between in display. I noticed this on some notebooks on github. This code is from Jake VanderPlas's notebook.
class display(object):
"""Display HTML representation of multiple objects"""
template = """<div style="float: left; padding: 10px;">
<p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1}
</div>"""
def __init__(self, *args):
self.args = args
def _repr_html_(self):
return '\n'.join(self.template.format(a, eval(a)._repr_html_())
for a in self.args)
def __repr__(self):
return '\n\n'.join(a + '\n' + repr(eval(a))
for a in self.args)
display('df', "df2")
How about Embarcadero Rapid SQL Really good but kind of expensive.
Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta
for the simple stuff i.e.
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)
or you can start using relativedelta
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(years=+1)
for the last day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
Right now this will provide 29/02/2016
for the penultimate day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)
last Friday of the next month:
use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))
2nd Tuesday of next month:
new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))
As @mrroot5 points out dateutil's rrule
functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.
from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)
#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)
#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
print(ld)
#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
print(tuesday)
Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00
2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00
This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fieldsI have created another alternative to the one posted by Vishal Joshi where the requirement to change the build action to Content is removed and also implemented basic support for ClickOnce deployment. I say basic, because I didn't test it thoroughly but it should work in the typical ClickOnce deployment scenario.
The solution consists of a single MSBuild project that once imported to an existent windows application project (*.csproj) extends the build process to contemplate app.config transformation.
You can read a more detailed explanation at Visual Studio App.config XML Transformation and the MSBuild project file can be downloaded from GitHub.
Try [attr.style]="changeBackground()"
I think this actually answers your question.
It is so annoying working with date/time in javascript.
After a few gray hairs I figured out that is was actually pretty simple.
var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format
var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc = Date.UTC(str);
I wanted to share another solution working with the ui router 1.0.0.X
As you may know, stateChangeStart and stateChangeSuccess are now deprecated. https://github.com/angular-ui/ui-router/issues/2655
Instead you should use $transitions http://angular-ui.github.io/ui-router/1.0.0-alpha.1/interfaces/transition.ihookregistry.html
This is how I achieved it:
First I have and AuthService with some useful functions
angular.module('myApp')
.factory('AuthService',
['$http', '$cookies', '$rootScope',
function ($http, $cookies, $rootScope) {
var service = {};
// Authenticates throug a rest service
service.authenticate = function (username, password, callback) {
$http.post('api/login', {username: username, password: password})
.success(function (response) {
callback(response);
});
};
// Creates a cookie and set the Authorization header
service.setCredentials = function (response) {
$rootScope.globals = response.token;
$http.defaults.headers.common['Authorization'] = 'Bearer ' + response.token;
$cookies.put('globals', $rootScope.globals);
};
// Checks if it's authenticated
service.isAuthenticated = function() {
return !($cookies.get('globals') === undefined);
};
// Clear credentials when logout
service.clearCredentials = function () {
$rootScope.globals = undefined;
$cookies.remove('globals');
$http.defaults.headers.common.Authorization = 'Bearer ';
};
return service;
}]);
Then I have this configuration:
angular.module('myApp', [
'ui.router',
'ngCookies'
])
.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/resumen');
$stateProvider
.state("dashboard", {
url: "/dashboard",
templateUrl: "partials/dashboard.html",
controller: "dashCtrl",
data: {
authRequired: true
}
})
.state("login", {
url: "/login",
templateUrl: "partials/login.html",
controller: "loginController"
})
}])
.run(['$rootScope', '$transitions', '$state', '$cookies', '$http', 'AuthService',
function ($rootScope, $transitions, $state, $cookies, $http, AuthService) {
// keep user logged in after page refresh
$rootScope.globals = $cookies.get('globals') || {};
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals;
$transitions.onStart({
to: function (state) {
return state.data != null && state.data.authRequired === true;
}
}, function () {
if (!AuthService.isAuthenticated()) {
return $state.target("login");
}
});
}]);
You can see that I use
data: {
authRequired: true
}
to mark the state only accessible if is authenticated.
then, on the .run I use the transitions to check the autheticated state
$transitions.onStart({
to: function (state) {
return state.data != null && state.data.authRequired === true;
}
}, function () {
if (!AuthService.isAuthenticated()) {
return $state.target("login");
}
});
I build this example using some code found on the $transitions documentation. I'm pretty new with the ui router but it works.
Hope it can helps anyone.
To eliminate the need for the cmd variable, you can do this:
eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
Open Notepad
Type in the following:
javac *
java Main
SaveAs Main.bat or whatever name you wish to use for the batch file
Make sure that Main.java is in the same folder along with your batch file
Double Click on the batch file to run the Main.java file
Well I'am totally late to party :) I had the need for ansible play that creates multiple local users with randoms passwords. This what I came up with, used some of examples from top and put them together with some changes.
create-user-with-password.yml
---
# create_user playbook
- hosts: all
become: True
user: root
vars:
#Create following user
users:
- test24
- test25
#with group
group: wheel
roles:
- create-user-with-password
/roles/create-user-with-password/tasks/main.yml
- name: Generate password for new user
local_action: shell pwgen -s -N 1 20
register: user_password
with_items: "{{ users }}"
run_once: true
- name: Generate encrypted password
local_action: shell python -c 'import crypt; print(crypt.crypt( "{{ item.stdout }}", crypt.mksalt(crypt.METHOD_SHA512)))'
register: encrypted_user_password
with_items: "{{ user_password.results }}"
run_once: true
- name: Create new user with group
user:
name: "{{ item }}"
groups: "{{ group }}"
shell: /bin/bash
append: yes
createhome: yes
comment: 'Created with ansible'
with_items:
- "{{ users }}"
register: user_created
- name: Update user Passwords
user:
name: '{{ item.0 }}'
password: '{{ item.1.stdout }}'
with_together:
- "{{ users }}"
- "{{ encrypted_user_password.results }}"
when: user_created.changed
- name: Force user to change the password at first login
shell: chage -d 0 "{{ item }}"
with_items:
- "{{ users }}"
when: user_created.changed
- name: Save Passwords Locally
become: no
local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
with_items: "{{ user_password.results }}"
when: user_created.changed
it dows not work with the :input selector for select fields, use this:
jQuery(function() {
jQuery('form').bind('submit', function() {
jQuery(this).find(':disabled').removeAttr('disabled');
});
});
The above solutions work if you are compressing all white space in the XML document. Other quick options are JDOM (using Format.getCompactFormat()) and dom4j (using OutputFormat.createCompactFormat()) when outputting the XML document.
However, I had a unique requirement to preserve the white space contained within the element's text value and these solutions did not work as I needed. All I needed was to remove the 'pretty-print' formatting added to the XML document.
The solution that I came up with can be explained in the following 3-step/regex process ... for the sake of understanding the algorithm for the solution.
String regex, updatedXml;
// 1. remove all white space preceding a begin element tag:
regex = "[\\n\\s]+(\\<[^/])";
updatedXml = originalXmlStr.replaceAll( regex, "$1" );
// 2. remove all white space following an end element tag:
regex = "(\\</[a-zA-Z0-9-_\\.:]+\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
// 3. remove all white space following an empty element tag
// (<some-element xmlns:attr1="some-value".... />):
regex = "(/\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
NOTE: The pseudo-code is in Java ... the '$1' is the replacement string which is the 1st capture group.
This will simply remove the white space used when adding the 'pretty-print' format to an XML document, yet preserve all other white space when it is part of the element text value.
While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.
Here's my solution:
from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }
Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)
If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:
mkdir %windir%\Sun\Java\Deployment
Create a file deployment.config with the content:
deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE
Create a file deployment.properties
deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites
Create a file exception.sites
http://example1.com
http://example2.com/path/to/specific/directory/
Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in
Yes. You need to use the "Searched" form rather than the "Simple" form of the CASE
expression
SELECT CASE
WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
WHEN c.Number IN ( '234523', '2342423' ) THEN 2
END AS Test
FROM tblClient c
Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
code example below:
g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Welcome to the Java Applet", 20 , 20);
Create dictionaries for both arrays using _.keyBy()
, merge the dictionaries, and convert the result to an array with _.values()
. In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
.keyBy('member') // create a dictionary of the 1st array_x000D_
.merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
.values() // turn the combined dictionary to array_x000D_
.value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
Using ES6 Map
Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member
to a new object, and store in map. Convert the map to an array with Map#values and spread:
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime.
Also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts.
Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.
When writing C++ I'd pretty much always use the C++ ones over the the C style.
For simple animations you can use an animated gif. I'm using one in this README file for instance.
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
Example:
post('url', {name: 'Johnny Bravo'});
Try this using hover function with fadein fadeout animations
$('ul.nav li.dropdown').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});
I just changed the encryption from "Use explicit FTP over TLS if available" to "Only use plain FTP" (insecure) at site manager and it works!
The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.
For example,
with open('hst.txt') as fobj:
text = fobj.read()
name = 'Bob'
with open('hst.txt', 'a') as fobj:
if not text.endswith('\n'):
fobj.write('\n')
fobj.write(name)
You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.
I've put some of the above answers into a short bash script that you can put into a file called get.sh
and link to /usr/local/bin/get
(or whatever other name you prefer).
#!/bin/bash
if [ "${1}" == "" ]; then
echo "error: blank line number";
exit 1
fi
re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
echo "error: line number arg not a number";
exit 1
fi
if [ "${2}" == "" ]; then
echo "error: blank file name";
exit 1
fi
sed "${1}q;d" $2;
exit 0
Ensure it's executable with
$ chmod +x get
Link it to make it available on the PATH
with
$ ln -s get.sh /usr/local/bin/get
Enjoy responsibly!
P
Here's a short complete html example. See demo http://jsfiddle.net/CU585/
<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>
try this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""FileTreeMaker.py: ..."""
__author__ = "legendmohe"
import os
import argparse
import time
class FileTreeMaker(object):
def _recurse(self, parent_path, file_list, prefix, output_buf, level):
if len(file_list) == 0 \
or (self.max_level != -1 and self.max_level <= level):
return
else:
file_list.sort(key=lambda f: os.path.isfile(os.path.join(parent_path, f)))
for idx, sub_path in enumerate(file_list):
if any(exclude_name in sub_path for exclude_name in self.exn):
continue
full_path = os.path.join(parent_path, sub_path)
idc = "??"
if idx == len(file_list) - 1:
idc = "??"
if os.path.isdir(full_path) and sub_path not in self.exf:
output_buf.append("%s%s[%s]" % (prefix, idc, sub_path))
if len(file_list) > 1 and idx != len(file_list) - 1:
tmp_prefix = prefix + "? "
else:
tmp_prefix = prefix + " "
self._recurse(full_path, os.listdir(full_path), tmp_prefix, output_buf, level + 1)
elif os.path.isfile(full_path):
output_buf.append("%s%s%s" % (prefix, idc, sub_path))
def make(self, args):
self.root = args.root
self.exf = args.exclude_folder
self.exn = args.exclude_name
self.max_level = args.max_level
print("root:%s" % self.root)
buf = []
path_parts = self.root.rsplit(os.path.sep, 1)
buf.append("[%s]" % (path_parts[-1],))
self._recurse(self.root, os.listdir(self.root), "", buf, 0)
output_str = "\n".join(buf)
if len(args.output) != 0:
with open(args.output, 'w') as of:
of.write(output_str)
return output_str
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--root", help="root of file tree", default=".")
parser.add_argument("-o", "--output", help="output file name", default="")
parser.add_argument("-xf", "--exclude_folder", nargs='*', help="exclude folder", default=[])
parser.add_argument("-xn", "--exclude_name", nargs='*', help="exclude name", default=[])
parser.add_argument("-m", "--max_level", help="max level",
type=int, default=-1)
args = parser.parse_args()
print(FileTreeMaker().make(args))
you will get this:
root:.
[.]
??[.idea]
? ??[scopes]
? ? ??scope_settings.xml
? ??.name
? ??Demo.iml
? ??encodings.xml
? ??misc.xml
? ??modules.xml
? ??vcs.xml
? ??workspace.xml
??[test1]
? ??test1.txt
??[test2]
? ??[test2-2]
? ? ??[test2-3]
? ? ??test2
? ? ??test2-3-1
? ??test2
??folder_tree_maker.py
??tree.py
You can't do it directly. There are a number of ways to do it:
Use a std::stringstream
:
std::ostringstream s;
s << "(" << c1 << ", " << c2 << ")";
storedCorrect[count] = s.str()
Use boost::lexical_cast
:
storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
Use std::snprintf
:
char buffer[256]; // make sure this is big enough!!!
snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
storedCorrect[count] = buffer;
There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3)
+ "-"
+ Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");
It turns out the compiler version I was using did not match the compiled version done with the coreset.o.
One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.
-qscale:v
to control qualityUse -qscale:v
(or the alias -q:v
) as an output option.
-qmin 1
output option (because the default is -qmin 2
).ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg
See the image muxer documentation for more options involving image outputs.
ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg
To add to marcio's awesome solution, dismissActionSheet:
can be implemented as follows.
Add this method to your code.
- (void)dismissActionSheet:(id)sender{
[_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
[_myButton setTitle:@"new title"]; //set to selected text if wanted
}
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
Here is a snippet I used within a Presenter filling a view with a Nullable Date/Time
memDateLogin = m.memDateLogin ?? DateTime.MinValue
Solution:
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
Model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
I use bootstrap 4.0.0
since we want to simulate .show
to hover event, it simply easy. just add all styles in .dropdown.show .dropdown-menu
to the :hover
. like this:
.dropdown:hover>.dropdown-menu {
opacity: 1;
visibility: visible;
transform: translate3d(0px, 0px, 0px);
}
Try this:
@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)
in your code should be,
@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})
if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
driver.findElement(By.id("idOfTheElement")).click();
}
I am calling myScript1.ps1 from myScript2.ps1 .
Assuming both of the script are at the same location, first get the location of the script by using this command :
$PSScriptRoot
And, then, append the script name you want to call like this :
& "$PSScriptRoot\myScript1.ps1"
This should work.
To go into why size_t
needed to exist and how we got here:
In pragmatic terms, size_t
and ptrdiff_t
are guaranteed to be 64 bits wide on a 64-bit implementation, 32 bits wide on a 32-bit implementation, and so on. They could not force any existing type to mean that, on every compiler, without breaking legacy code.
A size_t
or ptrdiff_t
is not necessarily the same as an intptr_t
or uintptr_t
. They were different on certain architectures that were still in use when size_t
and ptrdiff_t
were added to the Standard in the late ’80s, and becoming obsolete when C99 added many new types but not gone yet (such as 16-bit Windows). The x86 in 16-bit protected mode had a segmented memory where the largest possible array or structure could be only 65,536 bytes in size, but a far
pointer needed to be 32 bits wide, wider than the registers. On those, intptr_t
would have been 32 bits wide but size_t
and ptrdiff_t
could be 16 bits wide and fit in a register. And who knew what kind of operating system might be written in the future? In theory, the i386 architecture offers a 32-bit segmentation model with 48-bit pointers that no operating system has ever actually used.
The type of a memory offset could not be long
because far too much legacy code assumes that long
is exactly 32 bits wide. This assumption was even built into the UNIX and Windows APIs. Unfortunately, a lot of other legacy code also assumed that a long
is wide enough to hold a pointer, a file offset, the number of seconds that have elapsed since 1970, and so on. POSIX now provides a standardized way to force the latter assumption to be true instead of the former, but neither is a portable assumption to make.
It couldn’t be int
because only a tiny handful of compilers in the ’90s made int
64 bits wide. Then they really got weird by keeping long
32 bits wide. The next revision of the Standard declared it illegal for int
to be wider than long
, but int
is still 32 bits wide on most 64-bit systems.
It couldn’t be long long int
, which anyway was added later, since that was created to be at least 64 bits wide even on 32-bit systems.
So, a new type was needed. Even if it weren’t, all those other types meant something other than an offset within an array or object. And if there was one lesson from the fiasco of 32-to-64-bit migration, it was to be specific about what properties a type needed to have, and not use one that meant different things in different programs.
This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx
An example of this is to make a collection of items of a specific type.
class MyArray<T>
{
T[] array = new T[10];
public T GetItem(int index)
{
return array[index];
}
}
In your code, you could then do something like this:
MyArray<int> = new MyArray<int>();
In this case, T[] array
would work like int[] array
, and public T GetItem
would work like public int GetItem
.
Create Button and add image as its background swift 4
let img = UIImage(named: "imgname")
let myButton = UIButton(type: UIButtonType.custom)
myButton.frame = CGRect.init(x: 10, y: 10, width: 100, height: 45)
myButton.setImage(img, for: .normal)
myButton.addTarget(self, action: #selector(self.buttonClicked(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(myButton)
What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.
Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:
If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.
One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.
Here is how this particular deadlock problem actually occurred and how it was actually resolved. This is a fairly active database with 130K transactions occurring daily. The indexes in the tables in this database were originally clustered. The client requested us to make the indexes nonclustered. As soon as we did, the deadlocking began. When we reestablished the indexes as clustered, the deadlocking stopped.
Nothing much new to add, but I have had a lot of real-world experience in GIS and geocoding from a previous job. Here is what I remember:
If it is a "every once in a while" need in your application, I would definitely recommend the Google or Yahoo Geocoding APIs, but be careful to read their licensing terms.
I know that the Google Maps API in general is easy to license for even commercial web pages, but can't be used in a pay-to-access situation. In other words you can use it to advertise or provide a service that drives ad revenue, but you can't charge people to acess your site or even put it behind a password system.
Despite these restrictions, they are both excellent choices because they frequently update their street databases. Most of the free backend tools and libraries use Census and TIGER road data that is updated infrequently, so you are less likely to successfully geocode addresses in rapidly growing areas or new subdivisions.
Most of the services also restrict the number of geocoding queries you can make per day, so it's OK to look up addresses of, say, new customers who get added to your database, but if you run a batch job that feeds thousands of addresses from your database into the geocoder, you're going to get shutoff.
I don't think this one has been mentioned yet, but ESRI has ArcWeb web services that include geocoding, although they aren't very cheap. Last time I used them it cost around 1.5cents per lookup, but you had to prepay a certain amount to get started. Again the major advantage is that the road data they use is kept up to date in a timely manner and you can use the data in commercial situations that Google doesn't allow. The ArcWeb service will also serve up high-resolution satellite and aerial photos a la Google Maps, again priced per request.
If you want to roll your own or have access to much more accurate data, you can purchase subscriptions to GIS data from companies like TeleAtlas, but that ain't cheap. You can buy only a state or county worth of data if your needs are extremely local. There are several tiers of data - GIS features only, GIS plus detailed streets, all that plus geocode data, all of that plus traffic flow/direction/speed limits for routing. Of course, the price goes up as you go up the tiers.
Finally, the Wikipedia article on Geocoding has some good information on the algorithms and techniques. Even if you aren't doing it in your own code, it's useful to know what kind of errors and accuracy you can expect from various kinds of data sources.
Method Object JComboBox.getSelectedItem()
returns a value that is wrapped by Object
type so you have to cast it accordingly.
Syntax:
YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
The correct answer is
git checkout -m origin/master
It merges changes from the origin master branch with your local even uncommitted changes.
Android Studio -> Preferences -> Editor -> Intentions -> Java -> Declaration -> Enable "Add JavaDoc"
And, While selecting Methods to Implement (Ctrl/Cmd + i), on the left bottom, you should be seeing checkbox to enable Copy JavaDoc.
For those who have updated to the latest version of google-play-services_lib and/or have this error Google Play services out of date. Requires 3136100 but found 2012110
this newer version of com.google.android.gms.apk (Google Play Services 3.1.36) and com.android.vending.apk (Google Play Store 4.1.6) should work.
Test with this configuration on Android SDK Tools 22.0.1. Another configuration that targets pure Android, not the Google one, should work too.
...
Execute this in the terminal / cmd
adb -e install com.google.android.gms.apk
adb -e install com.android.vending.apk
Restart the AVD
I found this way to be the easiest, cleanest and it works with the newest version of the software, which allow you to get all the bug fixes.
id
overviewAn Android id
is an integer commonly used to identify views; this id
can be assigned via XML (when possible) and via code (programmatically.) The id
is most useful for getting references for XML-defined View
s generated by an Inflater
(such as by using setContentView
.)
id
via XML
android:id="@+id/
somename"
to your view.android:id
will be assigned a unique int
for use in code.android:id
's int
value in code using "R.id.
somename" (effectively a constant.)int
can change from build to build so never copy an id from gen/
package.name/R.java
, just use "R.id.
somename".id
assigned to a Preference
in XML is not used when the Preference
generates its View
.)id
via code (programmatically)id
s using someView.setId(
int);
int
must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)id
sXML
-assigned id
s will be unique.id
s do not have to be uniqueid
s can (theoretically) conflict with XML
-assigned id
s.id
s won't matter if queried correctly (keep reading).id
s don't matterfindViewById(int)
will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View
it finds with a matching id
.id
s assigned before an XML-defined id
in the hierarchy, findViewById(R.id.somename)
will always return the XML-defined View so id
'd.ID
sViewGroup
with id
.LinearLayout
with android:id="@+id/placeholder"
.ViewGroup
with View
s.id
s that are convenient to each view.Query these child views using placeholder.findViewById(convenientInt);
API 17 introduced View.generateViewId()
which allows you to generate a unique ID.
If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext()
and be sure to set each reference to null in onDestroy
. Apparently leaking the Activity
(hanging onto it after is is destroyed) is wasteful.. :)
android:id
for use in codeAPI 17 introduced View.generateViewId()
which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*
If your ViewGroup
cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:
Here, values/ids.xml defines a custom id
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>
Then once the ViewGroup or View has been created, you can attach the custom id
myViewGroup.setId(R.id.reservedNamedId);
id
exampleFor clarity by way of obfuscating example, lets examine what happens when there is an id
conflict behind the scenes.
layout/mylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
To simulate a conflict, lets say our latest build assigned R.id.placeholder
(@+id/placeholder
) an int
value of 12
..
Next, MyActivity.java defines some adds views programmatically (via code):
int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
TextView tv = new TextView(this.getApplicationContext());
// One new TextView will also be assigned an id==12:
tv.setId(i);
placeholder.addView(tv);
}
So placeholder
and one of our new TextView
s both have an id
of 12! But this isn't really a problem if we query placeholder's child views:
// Will return a generated TextView:
placeholder.findViewById(12);
// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12:
Activity.this.findViewById(12);
*Not so bad
Here is the missing example
library(rjson)
url <- 'http://someurl/data.json'
document <- fromJSON(file=url, method='C')
Following a Google...
Taking the code from the website:
CREATE TABLE CRLF
(
col1 VARCHAR(1000)
)
INSERT CRLF SELECT 'The quick brown@'
INSERT CRLF SELECT 'fox @jumped'
INSERT CRLF SELECT '@over the '
INSERT CRLF SELECT 'log@'
SELECT col1 FROM CRLF
Returns:
col1
-----------------
The quick brown@
fox @jumped
@over the
log@
(4 row(s) affected)
UPDATE CRLF
SET col1 = REPLACE(col1, '@', CHAR(13))
Looks like it can be done by replacing a placeholder with CHAR(13)
Good question, never done it myself :)
You can also reference a local gem with git if you happen to be working on it.
gem 'foo',
:git => '/Path/to/local/git/repo',
:branch => 'my-feature-branch'
Then, if it changes I run
bundle exec gem uninstall foo
bundle update foo
But I am not sure everyone needs to run these two steps.
If you can install glob2 package...
import glob2
filenames = glob2.glob("C:\\top_directory\\**\\*.ext") # Where ext is a specific file extension
folders = glob2.glob("C:\\top_directory\\**\\")
All filenames and folders:
all_ff = glob2.glob("C:\\top_directory\\**\\**")
Given the R data.frame:
> df1
a b c
1 1 1 0
2 1 0 0
3 0 1 0
4 0 0 0
Shuffle row-wise:
> df2 <- df1[sample(nrow(df1)),]
> df2
a b c
3 0 1 0
4 0 0 0
2 1 0 0
1 1 1 0
By default sample()
randomly reorders the elements passed as the first argument. This means that the default size is the size of the passed array. Passing parameter replace=FALSE
(the default) to sample(...)
ensures that sampling is done without replacement which accomplishes a row wise shuffle.
Shuffle column-wise:
> df3 <- df1[,sample(ncol(df1))]
> df3
c a b
1 0 1 1
2 0 1 0
3 0 0 1
4 0 0 0
That's a good problem. In order to solve that problem you will also have to disable ASLR otherwise the address of g() will be unpredictable.
Disable ASLR:
sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'
Disable canaries:
gcc overflow.c -o overflow -fno-stack-protector
After canaries and ASLR are disabled it should be a straight forward attack like the ones described in Smashing the Stack for Fun and Profit
Here is a list of security features used in ubuntu: https://wiki.ubuntu.com/Security/Features You don't have to worry about NX bits, the address of g() will always be in a executable region of memory because it is within the TEXT memory segment. NX bits only come into play if you are trying to execute shellcode on the stack or heap, which is not required for this assignment.
Now go and clobber that EIP!
You can use the input
Javascript event in jQuery like this:
$('#inputDatabaseName').on('input',function(e){
alert('Changed!')
});
In pure JavaScript:
document.querySelector("input").addEventListener("change",function () {
alert("Input Changed");
})
Or like this:
<input id="inputDatabaseName" onchange="youFunction();"
onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
way of getting home directory of current user is
String currentUsersHomeDir = System.getProperty("user.home");
and to append path separator
String otherFolder = currentUsersHomeDir + File.separator + "other";
The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.
A quick way is to run a jQuery command in the developer console. On any browser hit F12 and try to access any of the element .
$("#sideTab2").css("background-color", "yellow");
The document looks fine to me but I suspect that it contains invisible characters. Open it in a hex editor to check that there really isn't anything before the very first "<". Make sure the spaces in the XML header are spaces. Maybe delete the space before "?>". Check which line breaks are used.
Make sure the document is proper UTF-8. Some windows editors save the document as UTF-16 (i.e. every second byte is 0).
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
If you are trying to track down which line caused an error, if you right-click in the Python shell where the line error is displayed it will come up with a "Go to file/line" which takes you directly to the line in question.
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
$("#select_location_id").val(value);
$("#select_location_id").select2().trigger('change');
I solved my problem with this simple code. Where #select_location_id is an ID of select box and value is value of an option listed in select2 box.
If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:
system("The same thing you type into console");
But if it does not solve the problem, you probably have installed sql 2008 R2, so the solution that worked to me was this wamp server problems yellow symbol
If you have the tables in a database, you can make a full outer join to get the differences. Example:
select t1.Field1, t1.Field2, t2.Field1, t2.Field2
from Table1 t1
full outer join Table2 t2 on t1.Field1 = t2.Field1 and t1.Field2 = t2.Field2
where t1.Field1 is null or t2.Field2 is null
All records that are identical are filtered out. There is data either in the first two or the last two fields, depending on what table the record comes from.
Please DISCARD the tablespace before IMPORT
I got same issue solution is below
First you have to drop your database name. if your database is not deleting you have flow me. For Windows system your directory will be C:/xampp/mysql/data/yourdabasefolder remove "yourdabasefolder"
Again you have to create new database and import your old sql file. It will be work
Thanks
You should also try checking the error messages in curl_error(). You might need to do this once after each curl_* function.
That should work:
>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
A
0 0
1 1
2 2
But the append
doesn't happen in-place, so you'll have to store the output if you want it:
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
A
0 0
1 1
2 2
For Matching the ID:
Select * from table_name where 1=1
For Matching the Pattern:
Select * from table_name column_name Like '%string%'
Today, I had the same problem. My eclipse refused to start. When I double clicked on Eclipse icon I was able to see splashscreen for a second and then nothing happen. Tried most of the solutions here: removed lock file, renamed workspace, tried to start Eclipse with different clean parameters. I even put a new copy of Eclispe and tried to start with a new workspace. Nothing!
My logs were showing bunch of errors from yesterday when my workstation was rebooted at 17:45.
!ENTRY org.eclipse.ui.workbench 4 2 2014-12-17 17:45:12.178
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.ui.workbench".
!STACK 0
java.lang.NullPointerException
In the end this very simple change (look below) saved my Eclipse together with my workspace!
SOLUTION:
I edited eclipse.ini
and added following line:
-vm
C:\Program Files\Java\jdk1.6.0_26\bin\javaw.exe
Eclipse has started again with all my projects inside! I hope this can help.
You should try it like this:
var result =
from priceLog in PriceLogList
group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
select new {
LogDateTime = dateGroup.Key,
AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
};
When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line
var selectedTab = $("#TabList").tabs().data("selected.tabs");
is ran in the event like this:
$("#TabList").bind("tabsselect", function(event, ui) {
var selectedTab = $("#TabList").tabs().data("selected.tabs");
});
selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.
However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.
Here are some differences between the two languages:
this
scope for non-static methods, and implicit class scope; JavaScript has implicit global scope.Here are some features that I think are particular strengths of JavaScript:
Here is a solution that can help you dump all the logs onto a text file
adb logcat -d > logs.txt
You can set the default value of your Id in your db to newsequentialid() or newid(). Then the identity configuration of EF should work.
You are supposed to add the javascript code in a $(document).ready(function() {});
block.
i.e.
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"
I had a similar issue and upgrading pip fixed it for me.
python -m pip install --upgrade pip
This was on Windows and the path to python inside pip.exe was incorrect. See Archimedix answer for more information about the path.
There are a bunch of similar questions about this, so I'll post what I wrote before:
The only way I got this to work on my machine was to do it this way:
# Ignore all directories, and all sub-directories, and it's contents:
*/*
#Now ignore all files in the current directory
#(This fails to ignore files without a ".", for example
#'file.txt' works, but
#'file' doesn't):
*.*
#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
!wordpress/*/wp-content/themes/*
!wordpress/*/wp-content/themes/*/*
!wordpress/*/wp-content/themes/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*/*
Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.
This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153
These were useful topics:
I also tried
*
*/*
**/**
and **/wp-content/themes/**
or /wp-content/themes/**/*
None of that worked for me, either. Lots of trial and error!
You can learn something called "mocking". You can use this, for example, to check if: - a function was called - a function was called x times - a function was called at least x times - a function was called with a specific set of parameters. In your case, for example, you can use mocking to check that method3 was called once with whatever you pass as arg1 and arg2.
Have a look at these: https://code.google.com/p/mockito/ https://code.google.com/p/powermock/
If you would like to mount a particular host directory (/disk1/prometheus-data
in the following example) as a volume in the volumes
section of the Docker Compose YAML file, you can do it as below, e.g.:
version: '3'
services:
prometheus:
image: prom/prometheus
volumes:
- prometheus-data:/prometheus
volumes:
prometheus-data:
driver: local
driver_opts:
o: bind
type: none
device: /disk1/prometheus-data
By the way, in prometheus's Dockerfile, You may find the VOLUME
instruction as below, which marks it as holding externally mounted volumes from native host, etc. (Note however: this instruction is not a must though to mount a volume into a container.):
Dockerfile
...
VOLUME ["/prometheus"]
...
Refs:
Replace with:
$('#something').click(function() {
location.reload();
});
Setting spring.datasource.tomcat.testOnBorrow=true
in application.properties didn't work.
Programmatically setting like below worked without any issues.
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
@Bean
public DataSource dataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setUrl(this.properties.getDatabase().getUrl());
poolProperties.setUsername(this.properties.getDatabase().getUsername());
poolProperties.setPassword(this.properties.getDatabase().getPassword());
//here it is
poolProperties.setTestOnBorrow(true);
poolProperties.setValidationQuery("SELECT 1");
return new DataSource(poolProperties);
}
You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)
my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])
SELECT * FROM TABLENAME WHERE FIND_IN_SET(@search, column)
If it turns out your column has whitespaces in between the list items, use
SELECT * FROM TABLENAME WHERE FIND_IN_SET(@search, REPLACE(column, ' ', ''))
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
Fowloing code remove newline from both side of string:
select ltrim(rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)),''||CHR(10)||CHR(13)) from dual
but in most cases this one is just enought :
select rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13))) from dual
Perhaps you should divide your content like such using floats:
<div style="overflow: auto;">
<div style="float: left; width: 600px;">
Here is my content!
</div>
<div style="float: right; width: 300px;">
Here is my sidebar!
</div>
</div>
Notice the overflow: auto;
, this is to ensure that you have some height to your container. Floating things takes them out of the DOM, to ensure that your elements below don't overlap your wandering floats, set a container div
to have an overflow: auto
(or overflow: hidden
) to ensure that floats are accounted for when drawing your height. Check out more information on floats and how to use them here.
Try this: