You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Override the default input onChange behavior (call the function only when control loss focus and value was change)
NOTE: ngChange is not similar to the classic onChange event it firing the event while the value is changing This directive stores the value of the element when it gets the focus
On blurs it checks whether the new value has changed and if so it fires the event@param {String} - function name to be invoke when the "onChange" should be fired
@example < input my-on-change="myFunc" ng-model="model">
angular.module('app', []).directive('myOnChange', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
myOnChange: '='
},
link: function (scope, elm, attr) {
if (attr.type === 'radio' || attr.type === 'checkbox') {
return;
}
// store value when get focus
elm.bind('focus', function () {
scope.value = elm.val();
});
// execute the event when loose focus and value was change
elm.bind('blur', function () {
var currentValue = elm.val();
if (scope.value !== currentValue) {
if (scope.myOnChange) {
scope.myOnChange();
}
}
});
}
};
});
Something like this will do it. The for
loop may need to be modified depending on which filenames you wish to capture.
for fspec1 in DET01-ABC-5_50-*.dat ; do
fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
mv ${fspec1} ${fspec2}
done
You should always test these scripts on copies of your data, by the way, and in totally different directories.
The inner join
in your sub-query is unnecessary. It looks like you want to delete the entries in story_category
where the category_id
is not in the category
table.
Do this:
DELETE FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category);
Instead of that:
DELETE FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
To clarify, the above example does work, my code in the example did not work for unrelated reasons.
If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.
The following will cause the div to show:
$scope.myvar = "Hello World";
or
$scope.myvar = true;
The following will hide the div:
$scope.myvar = null;
or
$scope.myvar = false;
I've found a solution for this
Create a custom transparent dialog and inside that dialog open the popup window:
dialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
emptyDialog = LayoutInflater.from(context).inflate(R.layout.empty, null);
/* blur background*/
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.dimAmount=0.0f;
dialog.getWindow().setAttributes(lp);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
dialog.setContentView(emptyDialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnShowListener(new OnShowListener()
{
@Override
public void onShow(DialogInterface dialogIx)
{
mQuickAction.show(emptyDialog); //open the PopupWindow here
}
});
dialog.show();
xml for the dialog(R.layout.empty):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent" android:layout_width="match_parent"
style="@android:style/Theme.Translucent.NoTitleBar" />
now you want to dismiss the dialog when Popup window dismisses. so
mQuickAction.setOnDismissListener(new OnDismissListener()
{
@Override
public void onDismiss()
{
if(dialog!=null)
{
dialog.dismiss(); // dismiss the empty dialog when the PopupWindow closes
dialog = null;
}
}
});
Note: I've used NewQuickAction
plugin for creating PopupWindow here. It can also be done on native Popup Windows
Native events of components aren't directly accessible from parent elements. Instead you should try v-on:click.native="testFunction"
, or you can emit an event from Test
component as well. Like v-on:click="$emit('click')"
.
The best solution is the tuple applied to a list comprehension, but to extract one item this could work:
def pop_tuple(tuple, n):
return tuple[:n]+tuple[n+1:], tuple[n]
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
Yes, the first one is a static method
also called class method
, while the second one is an instance method
.
Consider the following examples, to understand it in more detail.
In ES5
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.isPerson = function(obj) {
return obj.constructor === Person;
}
Person.prototype.sayHi = function() {
return "Hi " + this.firstName;
}
In the above code, isPerson
is a static method, while sayHi
is an instance method of Person
.
Below, is how to create an object from Person
constructor.
var aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
In ES6
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
static isPerson(obj) {
return obj.constructor === Person;
}
sayHi() {
return `Hi ${this.firstName}`;
}
}
Look at how static
keyword was used to declare the static method isPerson
.
To create an object of Person
class.
const aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
NOTE: Both examples are essentially the same, JavaScript remains a classless language. The class
introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.
You could use :focus
which will remain the style as long as the user doesn't click elsewhere.
button:active {
border: 2px solid green;
}
button:focus {
border: 2px solid red;
}
This is against the general mechanism of Stream. Say you can split Stream S0 to Sa and Sb like you wanted. Performing any terminal operation, say count()
, on Sa will necessarily "consume" all elements in S0. Therefore Sb lost its data source.
Previously, Stream had a tee()
method, I think, which duplicate a stream to two. It's removed now.
Stream has a peek() method though, you might be able to use it to achieve your requirements.
void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
int i;
for(i = 0; i < (len / 2); i++)
{
*(hex_ptr+i) = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) : (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
*(hex_ptr+i) |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') : (*(ascii_ptr+(2*i)+1) - 'A' + 10);
}
}
Based on @tenshi's and @pkalinow's comments (also kudos to @rogerdpack), the following is a simple solution for creating a list argument captor that also disables the "uses unchecked or unsafe operations" warning:
@SuppressWarnings("unchecked")
final ArgumentCaptor<List<SomeType>> someTypeListArgumentCaptor =
ArgumentCaptor.forClass(List.class);
Full example here and corresponding passing CI build and test run here.
Our team has been using this for some time in our unit tests and this looks like the most straightforward solution for us.
This error occurred for me inside Travis when I forgot to add new files to my git repository. Silly mistake, but I can see it being quite common.
Are you using unmanaged code? If you are not using unmanaged code, according to Microsoft, memory leaks in the traditional sense are not possible.
Memory used by an application may not be released however, so an application's memory allocation may grow throughout the life of the application.
From How to identify memory leaks in the common language runtime at Microsoft.com
A memory leak can occur in a .NET Framework application when you use unmanaged code as part of the application. This unmanaged code can leak memory, and the .NET Framework runtime cannot address that problem.
Additionally, a project may only appear to have a memory leak. This condition can occur if many large objects (such as DataTable objects) are declared and then added to a collection (such as a DataSet). The resources that these objects own may never be released, and the resources are left alive for the whole run of the program. This appears to be a leak, but actually it is just a symptom of the way that memory is being allocated in the program.
For dealing with this type of issue, you can implement IDisposable. If you want to see some of the strategies for dealing with memory management, I would suggest searching for IDisposable, XNA, memory management as game developers need to have more predictable garbage collection and so must force the GC to do its thing.
One common mistake is to not remove event handlers that subscribe to an object. An event handler subscription will prevent an object from being recycled. Also, take a look at the using statement which allows you to create a limited scope for a resource's lifetime.
If anyone gets
ERROR: Module phpX.X does not exist!
just install the module for your current php version:
apt-get install libapache2-mod-phpX.X
Whenever I need to access config variables I tend to use: $this->config->config['variable_name'];
I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:
borrowed from: https://gist.github.com/gsakkis/4572159
The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:
# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime
from sqlalchemy.orm import Query
try:
basestring
except NameError:
basestring = str
def render_query(statement, dialect=None):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement.
WARNING: This method of escaping is insecure, incomplete, and for debugging
purposes only. Executing SQL statements with inline-rendered user values is
extremely insecure.
Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
"""
if isinstance(statement, Query):
if dialect is None:
dialect = statement.session.bind.dialect
statement = statement.statement
elif dialect is None:
dialect = statement.bind.dialect
class LiteralCompiler(dialect.statement_compiler):
def visit_bindparam(self, bindparam, within_columns_clause=False,
literal_binds=False, **kwargs):
return self.render_literal_value(bindparam.value, bindparam.type)
def render_array_value(self, val, item_type):
if isinstance(val, list):
return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
return self.render_literal_value(val, item_type)
def render_literal_value(self, value, type_):
if isinstance(value, long):
return str(value)
elif isinstance(value, (basestring, date, datetime, timedelta)):
return "'%s'" % str(value).replace("'", "''")
elif isinstance(value, list):
return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
return super(LiteralCompiler, self).render_literal_value(value, type_)
return LiteralCompiler(dialect, statement).process(statement)
Tested to two levels of nested arrays.
Open your page in Firefox and get the HTTPFox addon. It will tell you all that you need.
Found this on archivist.incuito:
http://archivist.incutio.com/viewlist/css-discuss/76444
When you first request a page, your browser sends a GET request to the server, which returns the HTML to the browser. The browser then starts parsing the page (possibly before all of it has been returned).
When it finds a reference to an external entity such as a CSS file, an image file, a script file, a Flash file, or anything else external to the page (either on the same server/domain or not), it prepares to make a further GET request for that resource.
However the HTTP standard specifies that the browser should not make more than two concurrent requests to the same domain. So it puts each request to a particular domain in a queue, and as each entity is returned it starts the next one in the queue for that domain.
The time it takes for an entity to be returned depends on its size, the load the server is currently experiencing, and the activity of every single machine between the machine running the browser and the server. The list of these machines can in principle be different for every request, to the extent that one image might travel from the USA to me in the UK over the Atlantic, while another from the same server comes out via the Pacific, Asia and Europe, which takes longer. So you might get a sequence like the following, where a page has (in this order) references to three script files, and five image files, all of differing sizes:
- GET script1 and script2; queue request for script3 and images1-5.
- script2 arrives (it's smaller than script1): GET script3, queue images1-5.
- script1 arrives; GET image1, queue images2-5.
- image1 arrives, GET image2, queue images3-5.
- script3 fails to arrive due to a network problem - GET script3 again (automatic retry).
- image2 arrives, script3 still not here; GET image3, queue images4-5.
- image 3 arrives; GET image4, queue image5, script3 still on the way.
- image4 arrives, GET image5;
- image5 arrives.
- script3 arrives.
In short: any old order, depending on what the server is doing, what the rest of the Internet is doing, and whether or not anything has errors and has to be re-fetched. This may seem like a weird way of doing things, but it would quite literally be impossible for the Internet (not just the WWW) to work with any degree of reliability if it wasn't done this way.
Also, the browser's internal queue might not fetch entities in the order they appear in the page - it's not required to by any standard.
(Oh, and don't forget caching, both in the browser and in caching proxies used by ISPs to ease the load on the network.)
I have done EXACTLY what you want to do and it works great. Unit tests "*Tests" always run, and "*IntegrationTests" only run when you do a mvn verify or mvn install. Here it the snippet from my POM. serg10 almost had it right....but not quite.
<plugin>
<!-- Separates the unit tests from the integration tests. -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- Skip the default running of this plug-in (or everything is run twice...see below) -->
<skip>true</skip>
<!-- Show 100% of the lines from the stack trace (doesn't work) -->
<trimStackTrace>false</trimStackTrace>
</configuration>
<executions>
<execution>
<id>unit-tests</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<!-- Never skip running the tests when the test phase is invoked -->
<skip>false</skip>
<includes>
<!-- Include unit tests within integration-test phase. -->
<include>**/*Tests.java</include>
</includes>
<excludes>
<!-- Exclude integration tests within (unit) test phase. -->
<exclude>**/*IntegrationTests.java</exclude>
</excludes>
</configuration>
</execution>
<execution>
<id>integration-tests</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<!-- Never skip running the tests when the integration-test phase is invoked -->
<skip>false</skip>
<includes>
<!-- Include integration tests within integration-test phase. -->
<include>**/*IntegrationTests.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
Good luck!
Use CSS. It's easier and faster than javascript.
overflow-x: hidden;
overflow-y: scroll;
You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.
In app.py put below code segment.
#rendering the HTML page which has the button
@app.route('/json')
def json():
return render_template('json.html')
#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
print ("Hello")
return ("nothing")
And your json.html page should look like below.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').on('click', function(e) {
e.preventDefault()
$.getJSON('/background_process_test',
function(data) {
//do nothing
});
return false;
});
});
</script>
//button
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.
.zip application/zip, application/octet-stream
In a nutshell: it's by far the most memory-efficient.
A std::string
comes with a pointer, a length, and a "short-string-optimization" buffer. But my situation is I need to store a string that is almost always empty, in a structure that I have hundreds of thousands of. In C, I would just use char *
, and it would be null most of the time. Which works for C++, too, except that a char *
has no destructor, and doesn't know to delete itself. By contrast, a std::unique_ptr<char[]>
will delete itself when it goes out of scope. An empty std::string
takes up 32 bytes, but an empty std::unique_ptr<char[]>
takes up 8 bytes, that is, exactly the size of its pointer.
The biggest downside is, every time I want to know the length of the string, I have to call strlen
on it.
Try "android update adb" command. It helps me with samsung galaxy gear.
You only have to add the millisecond field in your date format string:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
The API doc of SimpleDateFormat describes the format string in detail.
With ES6 (or using Babel or Typescipt) you can simply do:
var duplicates = myArray.filter(i => myArray.filter(ii => ii === i).length > 1);
I found a good way to do this with using a function and basic code. This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.
def check(count):
lowercase = 0
uppercase = 0
other = 0
low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
for n in count:
if n in low:
lowercase += 1
elif n in upper:
uppercase += 1
else:
other += 1
print("There are " + str(lowercase) + " lowercase letters.")
print("There are " + str(uppercase) + " uppercase letters.")
print("There are " + str(other) + " other elements to this sentence.")
From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:
Parent:
.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';
Child:
require: {
myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';
I would use the built-in ngInclude
directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.
Here's a working demo: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview
<p>Select page content template via dropdown</p>
<select ng-model="template">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>
<ng-include src="template"></ng-include>
<script type="text/ng-template" id="page1">
<h1 style="color: blue;">This is the page 1 content</h1>
</script>
<script type="text/ng-template" id="page2">
<h1 style="color:green;">This is the page 2 content</h1>
</script>
I tried the following and it works for me better
Code:
.unstyled-link{
color: inherit;
text-decoration: inherit;
&:link,
&:hover {
color: inherit;
text-decoration: inherit;
}
}
Only JWT's privateKey, which is on your server will decrypt the encrypted JWT. Those who know the privateKey will be able to decrypt the encrypted JWT.
Hide the privateKey in a secure location in your server and never tell anyone the privateKey.
Never use escape()
. It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.
If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
However whilst this is enough to put your user_id
in places like the input value
, it's not enough for id
because IDs can only use a limited selection of characters. (And %
isn't among them, so escape()
or even encodeURIComponent()
is no good.)
You could invent your own encoding scheme to put any characters in an ID, for example:
function encodeID(s) {
if (s==='') return '_';
return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
return '_'+match[0].charCodeAt(0).toString(16)+'_';
});
}
But you've still got a problem if the same user_id
occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById
, or worrying about how arbitrary strings are inserted into IDs.
eg.:
function addChut(user_id) {
var log= document.createElement('div');
log.className= 'log';
var textarea= document.createElement('textarea');
var input= document.createElement('input');
input.value= user_id;
input.readonly= True;
var button= document.createElement('input');
button.type= 'button';
button.value= 'Message';
var chut= document.createElement('div');
chut.className= 'chut';
chut.appendChild(log);
chut.appendChild(textarea);
chut.appendChild(input);
chut.appendChild(button);
document.getElementById('chuts').appendChild(chut);
button.onclick= function() {
alert('Send '+textarea.value+' to '+user_id);
};
return chut;
}
You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.
ETA:
I'm using jQuery at the moment as a framework
OK, then consider the jQuery 1.4 creation shortcuts, eg.:
var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...
The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.
You can keep a lookup of user_id
to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id
are restricted.
var chut_lookup= {};
...
function getChut(user_id) {
var key= '_map_'+user_id;
if (key in chut_lookup)
return chut_lookup[key];
return chut_lookup[key]= addChut(user_id);
}
(The _map_
prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object
member names, confuse it.)
To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.
Mysql-native has been outdated so it became MySQL2 that is a new module created with the help of the original MySQL module's team. This module has more features and I think it has what you want as it has prepared statements(by using.execute()) like in PHP for more security.
It's also very active(the last change was from 2-1 days) I didn't try it before but I think it's what you want and more.
if((int)letter != 0) { }
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
I offer this suggestion only because control over open flags is sometimes useful, for example, you may want to truncate it an existing file first and then append a series of writes to it - in which case use the 'w' flag when opening the file and don't close it until all the writes are done. Of course appendFile may be what you're after :-)
fs.open('log.txt', 'a', function(err, log) {
if (err) throw err;
fs.writeFile(log, 'Hello Node', function (err) {
if (err) throw err;
fs.close(log, function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
});
Yes: you can hide the built-in browser UI (by removing the controls
attribute from audio
) and instead build your own interface and control the playback using Javascript (source):
<audio id="player" src="vincent.mp3"></audio>
<div>
<button onclick="document.getElementById('player').play()">Play</button>
<button onclick="document.getElementById('player').pause()">Pause</button>
<button onclick="document.getElementById('player').volume += 0.1">Vol +</button>
<button onclick="document.getElementById('player').volume -= 0.1">Vol -</button>
</div>
You can then style the elements however you wish using CSS.
If by any chance you use VSCode and has installed the docker extension, just right+click on the docker you want to check (within the docker extension), click on Inspect, and there search for env, you will find all your env variables values
you can use this syntax:
INSERT INTO table_name ( name, age )
select 'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');
if its open an pop for asking as "enter substitution variable" then use this before the above queries:
set define off;
INSERT INTO table_name ( name, age )
select 'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');
I couldn't find an off-the-shelf module that added this function, so I wrote one:
In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:
Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String
Substring_Index = delims
start = 0
test = ""
For i = 1 To intCount
oldstart = start + 1
start = InStr(oldstart, strWord, strDelim)
Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i
End Function
Save the module as module1 (the default). You can now use statements like:
SELECT Substring_Index([fieldname],",",2) FROM table
as other answers here have mentioned, you probably want to either require a local json file that you know is safe and present, like a configuration file:
var objectFromRequire = require('path/to/my/config.json');
or to use the global JSON object to parse a string value into an object:
var stringContainingJson = '\"json that is obtained from somewhere\"';
var objectFromParse = JSON.parse(stringContainingJson);
note that when you require a file the content of that file is evaluated, which introduces a security risk in case it's not a json file but a js file.
here, i've published a demo where you can see both methods and play with them online (the parsing example is in app.js file - then click on the run button and see the result in the terminal): http://staging1.codefresh.io/labs/api/env/json-parse-example
you can modify the code and see the impact...
You forgot braces around the if block, and a semicolon between the statements in the block.
awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out
This is an old question and most answers are a bit dated. Currently, I would do 1 of 2 things.
1. Create a program that takes the screenshots
I would use Pyppeteer to take screenshots of websites. This runs on the Puppeteer package. Puppeteer spins up a headless chrome browser, so the screenshots will look exactly like they would in a normal browser.
This is taken from the pyppeteer documentation:
import asyncio
from pyppeteer import launch
async def main():
browser = await launch()
page = await browser.newPage()
await page.goto('https://example.com')
await page.screenshot({'path': 'example.png'})
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
2. Use a screenshot API
You could also use a screenshot API such as this one. The nice thing is that you don't have to set everything up yourself but can simply call an API endpoint.
This is taken from the screenshot API's documentation:
import urllib.parse
import urllib.request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# The parameters.
token = "YOUR_API_TOKEN"
url = urllib.parse.quote_plus("https://example.com")
width = 1920
height = 1080
output = "image"
# Create the query URL.
query = "https://screenshotapi.net/api/v1/screenshot"
query += "?token=%s&url=%s&width=%d&height=%d&output=%s" % (token, url, width, height, output)
# Call the API.
urllib.request.urlretrieve(query, "./example.png")
you need to place the opening brace after main
, not before it
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
As you might have already about knew the error. This is due to trying to access the empty array or trying to access the value of empty key of array. In my project, I am dealing with this error with counting the array and displaying result.
You can do it like this:
if(count($votes) == '0'){
echo 'Sorry, no votes are available at the moment.';
}
else{
//do the stuff with votes
}
count($votes)
counts the $votes
array. If it is equal to zero (0)
, you can display your custom message or redirect to certain page else you can do stuff with $votes
. In this way you can remove the Notice: Undefined offset: 0
in notice in PHP.
For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage()
returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.
Simple example from documentation:
>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.
Here's my solution for this, which allows you to easily customize the JSON as well as organize related records
Firstly implement a method on the model. I call is json
but you can call it whatever you like, e.g.:
class Car(Model):
...
def json(self):
return {
'manufacturer': self.manufacturer.name,
'model': self.model,
'colors': [color.json for color in self.colors.all()],
}
Then in the view I do:
data = [car.json for car in Car.objects.all()]
return HttpResponse(json.dumps(data), content_type='application/json; charset=UTF-8', status=status)
In Python 3 it's quite easy: read the file and rewrite it with utf-8
encoding:
s = open(bom_file, mode='r', encoding='utf-8-sig').read()
open(bom_file, mode='w', encoding='utf-8').write(s)
I use the following method:
public static <T> T getBean(final String beanName, final Class<T> clazz) {
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
return (T) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, beanName);
}
This allows me to get the returned object in a typed manner.
I occasionally see this when spinning up a VM. Our automation system starts applying updates, so depending on timing can hit an update to critical packages.
Upshot - this might happen if ssh or other related packages are being updated on the destination machine.
What I looked for is not exactly pointed out in here in SO, I'm writing for the benefit of others who might search for similar. I faced an issue with one file (present in old repo) getting removed in the repo. And when I apply the patch, it fails as it couldn't find the file to be applied. (so my case is git patch fails for file got removed) '#git apply --reject' definitely gave a view but didn't quite get me to the fix. I couldn't use wiggle as it is not available for us in our build servers. In my case, I got through this problem by removing the entry of the 'file which got removed in the repo' from patch file I've tried applying, so I got all other changes applied without an issue (using 3 way merge, avoiding white space errors), And then manually merging content of file removed into where its moved.
Here is an example that does a union between two completely unrelated tables: the Student and the Products table. It generates an output that is 4 columns:
select
FirstName as Column1,
LastName as Column2,
email as Column3,
null as Column4
from
Student
union
select
ProductName as Column1,
QuantityPerUnit as Column2,
null as Column3,
UnitsInStock as Column4
from
Products
Obviously you'll tweak this for your own environment...
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
Well, the $key => $value
in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,... In PHP, associative arrays look like this:
$featured = array('key1' => 'value1', 'key2' => 'value2', etc.);
In the PHP code: $featured
is the associative array being looped through, and as $key => $value
means that each time the loop runs and selects a key-value pair from the array, it stores the key in the local $key
variable to use inside the loop block and the value in the local $value
variable. So for our example array above, the foreach loop would reach the first key-value pair, and if you specified as $key => $value
, it would store 'key1'
in the $key
variable and 'value1'
in the $value
variable.
Since you don't use the $key
variable inside your loop block, adding it or removing it doesn't change the output of the loop, but it's best to include the key-value pair to show that it's an associative array.
Also note that the as $key => $value
designation is arbitrary. You could replace that with as $foo => $bar
and it would work fine as long as you changed the variable references inside the loop block to the new variables, $foo
and $bar
. But making them $key
and $value
helps to keep track of what they mean.
I wouldn't use arrays. They're problematic for several reasons and you can't declare it in terms of a specific array size anyway. Try:
List<List<String>> addresses = new ArrayList<List<String>>();
But honestly for addresses, I'd create a class to model them.
If you were to use arrays it would be:
List<String[]> addresses = new ArrayList<String[]>();
ie you can't declare the size of the array.
Lastly, don't declare your types as concrete types in instances like this (ie for addresses
). Use the interface as I've done above. This applies to member variables, return types and parameter types.
CTRL-W >
and
CTRL-W <
to make the window wider or narrower.
create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test
You should put the print function in your view-details.php file and call it once the file is loaded, by either using
<body onload="window.print()">
or
$(document).ready(function () {
window.print();
});
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
You can use a .Net environment Visual studio, Take a look at the differences with the PC version.
A lighter editor would be Visual Code
Alternatives :
Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)
Virtual machine (VMWare Fusion perhaps)
Update your codebase to .Net Core, (before choosing this option take a look at this migration process)
.Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux
As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.
[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license
$this->container->get('security.token_storage')->getToken()->getUser();
If you're giving the same seed, that's normal. That's an important feature allowing tests.
Check this to understand pseudo random generation and seeds:
A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.
If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random
instance should of course be kept outside of your method.
Your code should probably be like this:
private Random generator = new Random();
double randomGenerator() {
return generator.nextDouble()*0.5;
}
I found a solution that doesn't need to access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.
The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.
If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.
This function downsample to half at a time until reaching the desired size:
function resize_image( src, dst, type, quality ) {
var tmp = new Image(),
canvas, context, cW, cH;
type = type || 'image/jpeg';
quality = quality || 0.92;
cW = src.naturalWidth;
cH = src.naturalHeight;
tmp.src = src.src;
tmp.onload = function() {
canvas = document.createElement( 'canvas' );
cW /= 2;
cH /= 2;
if ( cW < src.width ) cW = src.width;
if ( cH < src.height ) cH = src.height;
canvas.width = cW;
canvas.height = cH;
context = canvas.getContext( '2d' );
context.drawImage( tmp, 0, 0, cW, cH );
dst.src = canvas.toDataURL( type, quality );
if ( cW <= src.width || cH <= src.height )
return;
tmp.src = dst.src;
}
}
// The images sent as parameters can be in the DOM or be image objects
resize_image( $( '#original' )[0], $( '#smaller' )[0] );
All the primitive wrapper objects are immutable.
I'm maybe late to the question but I want to add and clarify that when you do playerID++
, what really happens is something like this:
playerID = Integer.valueOf( playerID.intValue() + 1);
Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
Dive into python has a bit where he talks about what he calls the and-or trick, which seems like an effective way to cram complex logic into a single line.
Basically, it simulates the ternary operater in c, by giving you a way to test for truth and return a value based on that. For example:
>>> (1 and ["firstvalue"] or ["secondvalue"])[0]
"firstvalue"
>>> (0 and ["firstvalue"] or ["secondvalue"])[0]
"secondvalue"
The last (third to be exactly) RFC for this issue is RFC-6265 (Obsoletes RFC-2965 that in turn obsoletes RFC-2109).
According to it if the server omits the Domain attribute, the user agent will return the cookie only to the origin server (the server on which a given resource resides). But it's also warning that some existing user agents treat an absent Domain attribute as if the Domain attribute were present and contained the current host name (For example, if example.com returns a Set-Cookie header without a Domain attribute, these user agents will erroneously send the cookie to www.example.com as well).
When the Domain attribute have been specified, it will be treated as complete domain name (if there is the leading dot in attribute it will be ignored). Server should match the domain specified in attribute (have exactly the same domain name or to be a subdomain of it) to get this cookie. More accurately it specified here.
So, for example:
Domain=.example.com
is equivalent to Domain=example.com
Domain=www.example.com
will close the way for www4.example.comPS: trailing comma in Domain attribute will cause the user agent to ignore the attribute =(
Mutex is binary semaphore. It must be initialized with 1, so that the First Come First Serve principle is met. This brings us to the other special property of each mutex: the one who did down, must be the one who does up. Ergo we have obtained mutual exclusion over some resource.
Now you could see that a mutex is a special case of general semaphore.
The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).
this is what you want:
<html>
<head>
<style>
li { color: blue }<br>
li:nth-child(even) { color:red }
li:nth-child(odd) { color:green}
</style>
</head>
<body>
<ul>
<li>ho</li>
<li>ho</li>
<li>ho</li>
<li>ho</li>
<li>ho</li>
</ul>
</body>
</html>
Starting from C# 6.0, when $ - string interpolation has been introduced, there is one more way:
var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array}");
//output
A, B, C
Concatenation could be archived using the System.Linq
, convert the string[]
to char[]
and print as a string
var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");
//output
ABC
With keys as tuples, you just filter the keys with given second component and sort it:
blue_fruit = sorted([k for k in data.keys() if k[1] == 'blue'])
for k in blue_fruit:
print k[0], data[k] # prints 'banana 24', etc
Sorting works because tuples have natural ordering if their components have natural ordering.
With keys as rather full-fledged objects, you just filter by k.color == 'blue'
.
You can't really use dicts as keys, but you can create a simplest class like class Foo(object): pass
and add any attributes to it on the fly:
k = Foo()
k.color = 'blue'
These instances can serve as dict keys, but beware their mutability!
You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.
There are different levels of uniqueness.
If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.
If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)
for x in reversed(whatever):
do_something()
This works on basically everything that has a defined order, including xrange
objects and lists.
if(!File.Exists(filename)) //No File? Create
{
fs = File.Create(filename);
fs.Close();
}
if(File.ReadAllBytes().Length >= 100*1024*1024) // (100mB) File to big? Create new
{
string filenamebase = "myLogFile"; //Insert the base form of the log file, the same as the 1st filename without .log at the end
if(filename.contains("-")) //Check if older log contained -x
{
int lognumber = Int32.Parse(filename.substring(filename.lastIndexOf("-")+1, filename.Length-4); //Get old number, Can cause exception if the last digits aren't numbers
lognumber++; //Increment lognumber by 1
filename = filenamebase + "-" + lognumber + ".log"; //Override filename
}
else
{
filename = filenamebase + "-1.log"; //Override filename
}
fs = File.Create(filename);
fs.Close();
}
Refer link:
http://www.codeproject.com/Questions/163337/How-to-write-in-log-Files-in-C
You have a typo.
Change: headers.append('authentication', ${student.token});
To: headers.append('Authentication', student.token);
NOTE the Authentication is capitalized
Here's how I did it, I think the most elegant way I could. With this solution, the only things you need to do in your layouts are:
xmlns
declarationTextView
s source text namespace from android to your new namespaceTextView
s with x.y.z.JustifiedTextView
Here's the code. Works perfectly fine on my phones (Galaxy Nexus Android 4.0.2, Galaxy Teos Android 2.1). Feel free, of course, to replace my package name with yours.
/assets/justified_textview.css:
body {
font-size: 1.0em;
color: rgb(180,180,180);
text-align: justify;
}
@media screen and (-webkit-device-pixel-ratio: 1.5) {
/* CSS for high-density screens */
body {
font-size: 1.05em;
}
}
@media screen and (-webkit-device-pixel-ratio: 2.0) {
/* CSS for extra high-density screens */
body {
font-size: 1.1em;
}
}
/res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="JustifiedTextView">
<attr name="text" format="reference" />
</declare-styleable>
</resources>
/res/layout/test.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/net.bicou.myapp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<net.bicou.myapp.widget.JustifiedTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
myapp:text="@string/surv1_1" />
</LinearLayout>
</ScrollView>
/src/net/bicou/myapp/widget/JustifiedTextView.java:
package net.bicou.myapp.widget;
import net.bicou.myapp.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebView;
public class JustifiedTextView extends WebView {
public JustifiedTextView(final Context context) {
this(context, null, 0);
}
public JustifiedTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public JustifiedTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (attrs != null) {
final TypedValue tv = new TypedValue();
final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.JustifiedTextView, defStyle, 0);
if (ta != null) {
ta.getValue(R.styleable.JustifiedTextView_text, tv);
if (tv.resourceId > 0) {
final String text = context.getString(tv.resourceId).replace("\n", "<br />");
loadDataWithBaseURL("file:///android_asset/",
"<html><head>" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"justified_textview.css\" />" +
"</head><body>" + text + "</body></html>",
"text/html", "UTF8", null);
setTransparentBackground();
}
}
}
}
public void setTransparentBackground() {
try {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
} catch (final NoSuchMethodError e) {
}
setBackgroundColor(Color.TRANSPARENT);
setBackgroundDrawable(null);
setBackgroundResource(0);
}
}
We need to set the rendering to software in order to get transparent background on Android 3+. Hence the try-catch for older versions of Android.
Hope this helps!
PS: please not that it might be useful to add this to your whole activity on Android 3+ in order to get the expected behavior:
android:hardwareAccelerated="false"
you can use val function to collect data from inputs:
jQuery("#myInput1").val();
private void Test_Click(object sender, System.EventArgs e){
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
Console.WriiteLine( path );
}
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
See docs.python.org:
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
Hence use close()
elegantly with try/finally
:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
This ensures that even if # do stuff with f
raises an exception, f
will still be closed properly.
Note that open
should appear outside of the try
. If open
itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open
raises an exception its result is not assigned to f
and it is an error to call f.close()
.
You can't disable a link (in a portable way). You can use one of these techniques (each one with its own benefits and disadvantages).
This should be the right way (but see later) to do it when most of browsers will support it:
a.disabled {
pointer-events: none;
}
It's what, for example, Bootstrap 3.x does. Currently (2016) it's well supported only by Chrome, FireFox and Opera (19+). Internet Explorer started to support this from version 11 but not for links however it's available in an outer element like:
span.disable-links {
pointer-events: none;
}
With:
<span class="disable-links"><a href="#">...</a></span>
We, probably, need to define a CSS class for pointer-events: none
but what if we reuse the disabled
attribute instead of a CSS class? Strictly speaking disabled
is not supported for <a>
but browsers won't complain for unknown attributes. Using the disabled
attribute IE will ignore pointer-events
but it will honor IE specific disabled
attribute; other CSS compliant browsers will ignore unknown disabled
attribute and honor pointer-events
. Easier to write than to explain:
a[disabled] {
pointer-events: none;
}
Another option for IE 11 is to set display
of link elements to block
or inline-block
:
<a style="pointer-events: none; display: inline-block;" href="#">...</a>
Note that this may be a portable solution if you need to support IE (and you can change your HTML) but...
All this said please note that pointer-events
disables only...pointer events. Links will still be navigable through keyboard then you also need to apply one of the other techniques described here.
In conjunction with above described CSS technique you may use tabindex
in a non-standard way to prevent an element to be focused:
<a href="#" disabled tabindex="-1">...</a>
I never checked its compatibility with many browsers then you may want to test it by yourself before using this. It has the advantage to work without JavaScript. Unfortunately (but obviously) tabindex
cannot be changed from CSS.
Use a href
to a JavaScript function, check for the condition (or the disabled attribute itself) and do nothing in case.
$("td > a").on("click", function(event){
if ($(this).is("[disabled]")) {
event.preventDefault();
}
});
To disable links do this:
$("td > a").attr("disabled", "disabled");
To re-enable them:
$("td > a").removeAttr("disabled");
If you want instead of .is("[disabled]")
you may use .attr("disabled") != undefined
(jQuery 1.6+ will always return undefined
when the attribute is not set) but is()
is much more clear (thanks to Dave Stewart for this tip). Please note here I'm using the disabled
attribute in a non-standard way, if you care about this then replace attribute with a class and replace .is("[disabled]")
with .hasClass("disabled")
(adding and removing with addClass()
and removeClass()
).
Zoltán Tamási noted in a comment that "in some cases the click event is already bound to some "real" function (for example using knockoutjs) In that case the event handler ordering can cause some troubles. Hence I implemented disabled links by binding a return false handler to the link's touchstart
, mousedown
and keydown
events. It has some drawbacks (it will prevent touch scrolling started on the link)" but handling keyboard events also has the benefit to prevent keyboard navigation.
Note that if href
isn't cleared it's possible for the user to manually visit that page.
Clear the href
attribute. With this code you do not add an event handler but you change the link itself. Use this code to disable links:
$("td > a").each(function() {
this.data("href", this.attr("href"))
.attr("href", "javascript:void(0)")
.attr("disabled", "disabled");
});
And this one to re-enable them:
$("td > a").each(function() {
this.attr("href", this.data("href")).removeAttr("disabled");
});
Personally I do not like this solution very much (if you do not have to do more with disabled links) but it may be more compatible because of various way to follow a link.
Add/remove an onclick
function where you return false
, link won't be followed. To disable links:
$("td > a").attr("disabled", "disabled").on("click", function() {
return false;
});
To re-enable them:
$("td > a").removeAttr("disabled").off("click");
I do not think there is a reason to prefer this solution instead of the first one.
Styling is even more simple, whatever solution you're using to disable the link we did add a disabled
attribute so you can use following CSS rule:
a[disabled] {
color: gray;
}
If you're using a class instead of attribute:
a.disabled {
color: gray;
}
If you're using an UI framework you may see that disabled links aren't styled properly. Bootstrap 3.x, for example, handles this scenario and button is correctly styled both with disabled
attribute and with .disabled
class. If, instead, you're clearing the link (or using one of the others JavaScript techniques) you must also handle styling because an <a>
without href
is still painted as enabled.
Do not forget to also include an attribute aria-disabled="true"
together with disabled
attribute/class.
I have try twitter geo api, failed.
Google map api, failed, so far, no way you can get city limit by any api.
twitter api geo endpoint will NOT give you city boundary,
what they provide you is ONLY bounding box with 5 point(lat, long)
A good question. Should tell you it took some time to crack this one. Here is my result.
DECLARE @TABLE TABLE
(
ID INT,
USERS VARCHAR(10),
ACTIVITY VARCHAR(10),
PAGEURL VARCHAR(10)
)
INSERT INTO @TABLE
VALUES (1, 'Me', 'act1', 'ab'),
(2, 'Me', 'act1', 'cd'),
(3, 'You', 'act2', 'xy'),
(4, 'You', 'act2', 'st')
SELECT T1.USERS, T1.ACTIVITY,
STUFF(
(
SELECT ',' + T2.PAGEURL
FROM @TABLE T2
WHERE T1.USERS = T2.USERS
FOR XML PATH ('')
),1,1,'')
FROM @TABLE T1
GROUP BY T1.USERS, T1.ACTIVITY
After digging into hibernate source code and Below configuration goes to Oracle db for the next value after 50 inserts. So make your INST_PK_SEQ increment 50 each time it is called.
Hibernate 5 is used for below strategy
Check also below http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators-sequence
@Id
@Column(name = "ID")
@GenericGenerator(name = "INST_PK_SEQ",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@org.hibernate.annotations.Parameter(
name = "optimizer", value = "pooled-lo"),
@org.hibernate.annotations.Parameter(
name = "initial_value", value = "1"),
@org.hibernate.annotations.Parameter(
name = "increment_size", value = "50"),
@org.hibernate.annotations.Parameter(
name = SequenceStyleGenerator.SEQUENCE_PARAM, value = "INST_PK_SEQ"),
}
)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "INST_PK_SEQ")
private Long id;
Simple solution:
min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
margin: 0;
padding: 0;
By the way, if you want to center it in a parent div container, you can add those css properties:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
It should really work as expected :)
If you want to change the range to [0, 1], make sure the output data type is float
.
image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR) # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
If using ActiveAdmin don't forget that there is also a permit_params in the model register block:
ActiveAdmin.register Api::V1::Person do
permit_params :name, :address, :etc
end
These need to be set along with those in the controller:
def api_v1_person_params
params.require(:api_v1_person).permit(:name, :address, :etc)
end
Otherwise you will get the error:
ActiveModel::ForbiddenAttributesError
In VueJS 3 with createApp() you can use app.config.globalProperties
Like this:
const app = createApp(App);
app.config.globalProperties.foo = 'bar';
app.use(store).use(router).mount('#app');
and call your variable like this:
app.component('child-component', {
mounted() {
console.log(this.foo) // 'bar'
}
})
doc: https://v3.vuejs.org/api/application-config.html#warnhandler
If your data is reactive, you may want to use VueX.
If you are actually running into a performance problem I would suggest wrapping the calls that add/remove properties to/from the object with a function that also increments/decrements an appropriately named (size?) property.
You only need to calculate the initial number of properties once and move on from there. If there isn't an actual performance problem, don't bother. Just wrap that bit of code in a function getNumberOfProperties(object)
and be done with it.
From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections
is the value of maxThreads
unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads
.
I have some code in my game that displays live score. It is in a function for quick access.
def texts(score):
font=pygame.font.Font(None,30)
scoretext=font.render("Score:"+str(score), 1,(255,255,255))
screen.blit(scoretext, (500, 457))
and I call it using this in my while loop:
texts(score)
I prefer using the following method:
system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>
public static int reverse(int x) {
int tmp = x;
int oct = 0;
int res = 0;
while (true) {
oct = tmp % 10;
tmp = tmp / 10;
res = (res+oct)*10;
if ((tmp/10) == 0) {
res = res+tmp;
return res;
}
}
}
Add $("#id").select2()
out of document.ready()
function.
I get it to work without any reference to "class" or "ClassLoader".
Let's say we have three scenarios with the location of the file 'example.file' and your working directory (where your app executes) is home/mydocuments/program/projects/myapp:
a)A sub folder descendant to the working directory: myapp/res/files/example.file
b)A sub folder not descendant to the working directory: projects/files/example.file
b2)Another sub folder not descendant to the working directory: program/files/example.file
c)A root folder: home/mydocuments/files/example.file (Linux; in Windows replace home/ with C:)
1) Get the right path:
a)String path = "res/files/example.file";
b)String path = "../projects/files/example.file"
b2)String path = "../../program/files/example.file"
c)String path = "/home/mydocuments/files/example.file"
Basically, if it is a root folder, start the path name with a leading slash. If it is a sub folder, no slash must be before the path name. If the sub folder is not descendant to the working directory you have to cd to it using "../". This tells the system to go up one folder.
2) Create a File object by passing the right path:
File file = new File(path);
3) You are now good to go:
BufferedReader br = new BufferedReader(new FileReader(file));
class MathsOperations:
def __init__ (self, x, y):
self.a = x
self.b = y
def testAddition (self):
return (self.a + self.b)
def testMultiplication (self):
return (self.a * self.b)
then
temp = MathsOperations()
print(temp.testAddition())
The problem is that you mapped your servlet to /register.html
and it expects POST method, because you implemented only doPost()
method. So when you open register.html
page, it will not open html page with the form but servlet that handles the form data.
Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).
To fix:
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
This might help you to open all page links:
$(".myClass").each(
function(i,e){
window.open(e, '_blank');
}
);
It will open every <a href="" class="myClass"></a>
link items to another tab like you would had clicked each one.
You only need to paste it to browser console. jQuery framework required
After merging a development branch to master, I usually delete the development branch. However, if I want to cherry pick the commits in the development branch, I have to use the merge commit hash to avoid "bad object" error.
I believe fcntl()
is a POSIX function. Where as ioctl()
is a standard UNIX thing. Here is a list of POSIX io. ioctl()
is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl()
stuff might only work on certain OS or even certain revs of it's kernel.
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
Aggregate functions may help you out here. Aggregate functions ignore NULLs
(at least that's true on SQL Server, Oracle, and Jet/Access), so you could use a query like this (tested on SQL Server Express 2008 R2):
SELECT
FK,
MAX(Field1) AS Field1,
MAX(Field2) AS Field2
FROM
table1
GROUP BY
FK;
I used MAX
, but any aggregate which picks one value from among the GROUP BY
rows should work.
Test data:
CREATE TABLE table1 (FK int, Field1 varchar(10), Field2 varchar(10));
INSERT INTO table1 VALUES (3, 'ABC', NULL);
INSERT INTO table1 VALUES (3, NULL, 'DEF');
INSERT INTO table1 VALUES (4, 'GHI', NULL);
INSERT INTO table1 VALUES (4, 'JKL', 'MNO');
INSERT INTO table1 VALUES (4, NULL, 'PQR');
Results:
FK Field1 Field2
-- ------ ------
3 ABC DEF
4 JKL PQR
As AnaPana mentioned pathlib is more new and easier in python 3.4 and there is new with_suffix method that can handle this problem easily:
from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')
I found there was another solution for this problem rather than creating a symbolic link.
You set the path to your directory, where libmysqlclient.18.dylib resides, to DYLD_LIBRARY_PATH environment variable. What I did is to put following line in my .bash_profile:
export DYLD_LIBRARY_PATH=/usr/local/mysql-5.5.15-osx10.6-x86/lib/:$DYLD_LIBRARY_PATH
That's it.
Atom has been created by Github and it includes "git awareness". That is a feature I like quite a lot:
Also it highlights the files in the git tree that have changed with different colours depending on their commit status:
This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.
# Using a local.dev vhost
$ browser-sync start --proxy
# Using a local.dev vhost with PORT
$ browser-sync start --proxy local.dev:8001
# Using a localhost address
$ browser-sync start --proxy localhost:8001
# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1
I use DDD a lot, and it's pretty powerful once you learn to use it. One thing I would say is don't use it over X over the WAN because it seems to do a lot of unnecessary screen updates.
Also, if you're not mated to GDB and don't mind ponying up a little cash, then I would try TotalView. It has a bit of a steep learning curve (it could definitely be more intuitive), but it's the best C++ debugger I've ever used on any platform and can be extended to introspect your objects in custom ways (thus allowing you to view an STL list as an actual list of objects, and not a bunch of confusing internal data members, etc.)
In my case:
$("div.which-stores-content").append("<div class="content">Content</div>);
$("div.content").hide().show("fast");
you can adjust your css with visibility:hidden -> visibility:visible and adjust the transitions etc transition: visibility 1.0s;
In .NET 4.0, the runtime handles certain exceptions raised as Windows Structured Error Handling (SEH) errors as indicators of Corrupted State. These Corrupted State Exceptions (CSE) are not allowed to be caught by your standard managed code. I won't get into the why's or how's here. Read this article about CSE's in the .NET 4.0 Framework:
http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035
But there is hope. There are a few ways to get around this:
Recompile as a .NET 3.5 assembly and run it in .NET 4.0.
Add a line to your application's config file under the configuration/runtime element:
<legacyCorruptedStateExceptionsPolicy enabled="true|false"/>
Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions
attribute. See http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035 for details.
EDIT
Previously, I referenced a forum post for additional details. But since Microsoft Connect has been retired, here are the additional details in case you're interested:
From Gaurav Khanna, a developer from the Microsoft CLR Team
This behaviour is by design due to a feature of CLR 4.0 called Corrupted State Exceptions. Simply put, managed code shouldnt make an attempt to catch exceptions that indicate corrupted process state and AV is one of them.
He then goes on to reference the documentation on the HandleProcessCorruptedStateExceptionsAttribute and the above article. Suffice to say, it's definitely worth a read if you're considering catching these types of exceptions.
So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.
The Sender
header is used to identify in the message who submitted it. This is usually the same as the From
header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.
The Return-Path
header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.
For example, take a server that allows users to send mail from a web page. So, [email protected]
types in a message and submits it. The server then sends the message to its recipient with From
set to [email protected]
. The actual SMTP submission uses different credentials, something like [email protected]
. So, the sender
header is set to [email protected]
, to indicate the From
header doesn't indicate who actually submitted the message.
In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path
would also be set to [email protected]
so that any delivery reports go to it instead of the sender.
If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.
In my case, i just change some step below with iOS 9.3 To solve this problem:
Settings -> General -> Device Management -> Developer app Choose your current developer account name. Taps Trust "Your developer account name" Taps "Trust" in pop up. Done
Unicode and encodings are completely different, unrelated things.
Assigns a numeric ID to each character:
So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.
Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.
You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.
These numbers assigned to all characters by Unicode are called code points.
The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?
Note that Unicode code points are usually formatted with a leading U+
, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.
Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).
The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.
Map characters to bit patterns.
These bit patterns are used to represent the characters in computer memory or on disk.
There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:
Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.
Example:
You can see all the mappings in this table.
Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.
Example:
You can see all the mappings in this table.
Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).
Example:
The way UTF-8 encodes characters to bit strings is very well described here.
Looking at the above examples, it becomes clear how Unicode is useful.
For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:
"I encode that a with an aigu (or however you call that rising bar) as 11100001"
But I can just say:
"I encode U+00E1 as 11100001"
And if I'm UTF-8, I can say:
"Me, in turn, I encode U+00E1 as 11000011 10100001"
And it's unambiguously clear to everybody which character we mean.
It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.
For example:
Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.
Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.
The encoding used by your Python interpreter is UTF-8.
Here's what's going on in your examples:
The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a
.
>>> a = 'á'
When you look at the value of a
, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1'
:
>>> a
'\xc3\xa1'
The following saves the Unicode code point of á, which is U+00E1, in the variable ua
(we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):
>>> ua = u'á'
When you look at the value of ua
, Python tells you that it contains the code point U+00E1:
>>> ua
u'\xe1'
The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:
>>> ua.encode('utf-8')
'\xc3\xa1'
The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:
>>> ua.encode('latin1')
'\xe1'
There's no relation between the Unicode object ua
and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.
if your using python 3.4.1 just write this line from tkinter import *
this will put everything in the module into the default namespace of your program. in fact instead of referring to say a button like tkinter.Button
you just type Button
All the other response are very miss-leading for somebody coming from google and looking for "timestamp in go"! YYYYMMDDhhmmss is not a "timestamp".
To get the "timestamp" of a date in go (number of seconds from january 1970), the correct function is .Unix(), and it really return an integer
<div>
<img class="crop" src="http://lorempixel.com/500/200"/>
</div>
<img src="http://lorempixel.com/500/200"/>
div {
width: 200px;
height: 200px;
overflow: hidden;
margin: 10px;
position: relative;
}
.crop {
position: absolute;
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
margin: auto;
height: auto;
width: auto;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
SearchView searchView = (SearchView) myActionMenuItem.getActionView();
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(Color.WHITE); //You color here
The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:
DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';
I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database
For a simple two- (or one) liner this code can be:
checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);
Here the Array.prototype.slice.call()
part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value)
on the end of line 2.
The => is javascript's arrow function notation.
the following solution worked for me other solution gave me some space in the sides i.e not full screen
You need to make changes in onStart and onCreate method
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null)
{
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.MATCH_PARENT;
dialog.getWindow().setLayout(width, height);
}
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final Dialog dialog = new Dialog(requireContext());
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
The CPPFLAGS
macro is the one to use to specify #include
directories.
Both CPPFLAGS
and CFLAGS
work in your case because the make
(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).
You don't need to specify .
as an include-directory if you use the form #include "..."
. You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.
You will need a PDF renderer. There are a few more or less good ones on the market (ICEPdf, pdfrenderer), but without, you will have to rely on external tools. The free PDF renderers also cannot render embedded fonts, and so will only be good for creating thumbnails (what you eventually want).
My favorite external tool is Ghostscript, which can convert PDFs to images with a single command line invocation.
This converts Postscript (and PDF?) files to bmp for us, just as a guide to modify for your needs (Know you need the env vars for gs to work!):
pushd
setlocal
Set BIN_DIR=C:\Program Files\IKOffice_ACME\bin
Set GS=C:\Program Files\IKOffice_ACME\gs
Set GS_DLL=%GS%\gs8.54\bin\gsdll32.dll
Set GS_LIB=%GS%\gs8.54\lib;%GS%\gs8.54\Resource;%GS%\fonts
Set Path=%Path%;%GS%\gs8.54\bin
Set Path=%Path%;%GS%\gs8.54\lib
call "%GS%\gs8.54\bin\gswin32c.exe" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE#bmpmono -r600x600 -sOutputFile#%2 -f %1
endlocal
popd
UPDATE: pdfbox is now able to embed fonts, so no need for Ghostscript anymore.
If all you are trying to do is solve the content length error from amazon then you could just read the bytes from the input stream to a Long and add that to the metadata.
/*
* Obtain the Content length of the Input stream for S3 header
*/
try {
InputStream is = event.getFile().getInputstream();
contentBytes = IOUtils.toByteArray(is);
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s", e.getMessage());
}
Long contentLength = Long.valueOf(contentBytes.length);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(contentLength);
/*
* Reobtain the tmp uploaded file as input stream
*/
InputStream inputStream = event.getFile().getInputstream();
/*
* Put the object in S3
*/
try {
s3client.putObject(new PutObjectRequest(bucketName, keyName, inputStream, metadata));
} catch (AmazonServiceException ase) {
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Error Message: " + ace.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
}
You'll need to read the input stream twice using this exact method so if you are uploading a very large file you might need to look at reading it once into an array and then reading it from there.
No need to use any strings
.Its over burden.
int i = 124;
int last= i%10;
System.out.println(last); //prints 4
You can also init multiple values if your selectbox is a multipl:
$('#selectBox').val(['A', 'B', 'C']);
/*****************************************************************************
* return application path
* @return
*****************************************************************************/
public static String getApplcatonPath(){
CodeSource codeSource = MainApp.class.getProtectionDomain().getCodeSource();
File rootPath = null;
try {
rootPath = new File(codeSource.getLocation().toURI().getPath());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootPath.getParentFile().getPath();
}//end of getApplcatonPath()
I don't have IE8 to test this out, but I'm pretty sure it should work:
<div class="screen">
<!-- code -->
<div class="innerdiv">
text or other content
</div>
</div>
and the css:
.screen{
position: relative;
}
.innerdiv {
position: absolute;
bottom: 0;
right: 0;
}
This should place the .innerdiv in the bottom-right corner of the .screen class. I hope this helps :)
You're very close, the problem is you're comparing a DateTime to a TimeOfDay. What you need to do is add the .TimeOfDay property to the end of your Convert.ToDateTime() functions.
Apple simply recommends declaring an isX
getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:
@property (nonatomic, assign) BOOL working;
[self setWorking:YES]; // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;
Or
@property (nonatomic, assign, getter=isWorking) BOOL working;
[self setWorking:YES]; // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above
This function extends the function from Gaten's answer a bit in order to get the element back:
$.fn.delayKeyup = function(callback, ms){
var timer = 0;
var el = $(this);
$(this).keyup(function(){
clearTimeout (timer);
timer = setTimeout(function(){
callback(el)
}, ms);
});
return $(this);
};
$('#input').delayKeyup(function(el){
//alert(el.val());
// Here I need the input element (value for ajax call) for further process
},1000);
The best way is to user sass-loader. It is available as npm package. It resolves all path related issues and make it super easy.
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
On Selenium >= 3.41 (C#) the rigth syntax is:
webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));
double click tomcat , see configure setting with "timeout" modify the number. Maybe this not the tomcat error.U can see the DB connection is achievable.
I think I get what you mean. Let's say for example you want the right-most \ in the following string (which is stored in cell A1):
Drive:\Folder\SubFolder\Filename.ext
To get the position of the last \, you would use this formula:
=FIND("@",SUBSTITUTE(A1,"\","@",(LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))/LEN("\")))
That tells us the right-most \ is at character 24. It does this by looking for "@" and substituting the very last "\" with an "@". It determines the last one by using
(len(string)-len(substitute(string, substring, "")))\len(substring)
In this scenario, the substring is simply "\" which has a length of 1, so you could leave off the division at the end and just use:
=FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))
Now we can use that to get the folder path:
=LEFT(A1,FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))
Here's the folder path without the trailing \
=LEFT(A1,FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))-1)
And to get just the filename:
=MID(A1,FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))
However, here is an alternate version of getting everything to the right of the last instance of a specific character. So using our same example, this would also return the file name:
=TRIM(RIGHT(SUBSTITUTE(A1,"\",REPT(" ",LEN(A1))),LEN(A1)))
Doesn't the Directory.GetFiles(String, String)
overload already do that? You would just do Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)
If you want to put them in a list, then just replace the "*.jpg"
with a variable that iterates over a list and aggregate the results into an overall result set. Much clearer than individually specifying them. =)
Something like...
foreach(String fileExtension in extensionList){
foreach(String file in Directory.GetFiles(dir, fileExtension, SearchOption.AllDirectories)){
allFiles.Add(file);
}
}
(If your directories are large, using EnumerateFiles
instead of GetFiles
can potentially be more efficient)
No. Order is not guaranteed in JSON and most other key-value data structures, so therefore the last item could sometimes be carrot
and at other times be banana
and so on. If you need to rely on ordering, your best bet is to go with arrays. The power of key-value data structures lies in accessing values by their keys
, not in being able to get the nth
item of the object.
I see .btn:focus
has an outline
on it:
.btn:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
Try changing this to:
.btn:focus {
outline: none !important;
}
Basically, look for any instances of outline
on :focus
ed elements — that's what's causing it.
Update - For Bootstrap v4:
.btn:focus {
box-shadow: none;
}
keep it simple
<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>
The short answer is: most of the time time.clock()
will be better.
However, if you're timing some hardware (for example some algorithm you put in the GPU), then time.clock()
will get rid of this time and time.time()
is the only solution left.
Note: whatever the method used, the timing will depend on factors you cannot control (when will the process switch, how often, ...), this is worse with time.time()
but exists also with time.clock()
, so you should never run one timing test only, but always run a series of test and look at mean/variance of the times.
This is how i did it with jquery. This was all cobbled together from various answers on stack overflow. This solution caches the selectors for faster performance and also solves the "jumping" issue when the sticky div becomes sticky.
Check it out on jsfiddle: http://jsfiddle.net/HQS8s/
CSS:
.stick {
position: fixed;
top: 0;
}
JS:
$(document).ready(function() {
// Cache selectors for faster performance.
var $window = $(window),
$mainMenuBar = $('#mainMenuBar'),
$mainMenuBarAnchor = $('#mainMenuBarAnchor');
// Run this on scroll events.
$window.scroll(function() {
var window_top = $window.scrollTop();
var div_top = $mainMenuBarAnchor.offset().top;
if (window_top > div_top) {
// Make the div sticky.
$mainMenuBar.addClass('stick');
$mainMenuBarAnchor.height($mainMenuBar.height());
}
else {
// Unstick the div.
$mainMenuBar.removeClass('stick');
$mainMenuBarAnchor.height(0);
}
});
});
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
days = (endDate - beginDate)/(60*60*24)
git remote add coworker git://path/to/coworkers/repo.git
git fetch coworker
git checkout --track coworker/foo
This will setup a local branch foo
, tracking the remote branch coworker/foo
. So when your co-worker has made some changes, you can easily pull them:
git checkout foo
git pull
Response to comments:
Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?
You don't need to create a new branch, even though I recommend it. You might as well commit directly to foo
and have your co-worker pull your branch. But that branch already exists and your branch foo
need to be setup as an upstream branch to it:
git branch --set-upstream foo colin/foo
assuming colin
is your repository (a remote to your co-workers repository) defined in similar way:
git remote add colin git://path/to/colins/repo.git
A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.
Because your std::function
signature specifies that your function doesn't take any arguments (<void(void)>
), you must bind the first (and the only) argument.
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
If you want to bind a function with parameters, you need to specify placeholders:
using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);
Or, if your compiler supports C++11 lambdas:
std::function<void(int,int)> f = [=](int a, int b) {
this->doSomethingArgs(a, b);
}
(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)
Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:
In public class Startup
add a property
public IConfigurationRoot Configuration { get; }
And then add a singleton IHttpContextAccessor to DI in ConfigureServices.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
Then in Configure
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
)
{
add the DI Parameter IServiceProvider svp
, so the method looks like:
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
,IServiceProvider svp)
{
Next, create a replacement class for System.Web:
namespace System.Web
{
namespace Hosting
{
public static class HostingEnvironment
{
public static bool m_IsHosted;
static HostingEnvironment()
{
m_IsHosted = false;
}
public static bool IsHosted
{
get
{
return m_IsHosted;
}
}
}
}
public static class HttpContext
{
public static IServiceProvider ServiceProvider;
static HttpContext()
{ }
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
// var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
// Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
// context.Response.WriteAsync("Test");
return context;
}
}
} // End Class HttpContext
}
Now in Configure, where you added the IServiceProvider svp
, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)
and set HostingEnvironment.IsHosted to true
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ServiceProvider = svp;
System.Web.HttpContext.ServiceProvider = svp;
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest
, CookieHttpOnly=false
});
Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start
in global.asax.
I stress again, this only works if you actually added
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.
Perhaps a more maintainable method would be adding this helper class
namespace System.Web
{
public static class HttpContext
{
private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
{
m_httpContextAccessor = httpContextAccessor;
}
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
return m_httpContextAccessor.HttpContext;
}
}
}
}
And then calling HttpContext.Configure in Startup->Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
System.Web.HttpContext.Configure(app.ApplicationServices.
GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
);
You can find them in /var/log
within your root Magento installation
There will usually be two files by default, exception.log
and system.log
.
If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.
The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.
I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.
My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.
class Basket extends Array
constructor: ->
add: (item) ->
@push(item)
remove: (item) ->
index = @indexOf(item)
@.splice(index, 1)
contains: (item) ->
@indexOf(item) isnt -1
indexOf: (item) ->
indexOf = -1
@.forEach (stored_item, index) ->
if (item.id is stored_item.id)
indexOf = index
return indexOf
Then you initialize this in your controller and create a function for that action:
$scope.basket = new Basket()
$scope.addItemToBasket = (item) ->
$scope.basket.add(item)
Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:
li ng-repeat="item in items"
a href="#" ng-click="addItemToBasket(item)"
If you are looking for contains & not equals then i would propose below solution. Only drawback is if your searchItem in below solution is "DE" then also it would match
List<String> list = new ArrayList<>();
public static final String[] LIST_OF_ELEMENTS = { "ABC", "DEF","GHI" };
String searchItem= "def";
if(String.join(",", LIST_OF_ELEMENTS).contains(searchItem.toUpperCase())) {
System.out.println("found element");
break;
}
bool isNegative(int n) {
int i;
for (i = 0; i <= Int32.MaxValue; i++) {
if (n == i)
return false;
}
return true;
}
The comment states
// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).
You are setting
"default_line_ending": "LF",
You should set
"default_line_ending": "unix",
Taking Chetan Kumar solution and in case you need to apply to a map[string]int
package main
import (
"fmt"
"reflect"
)
type BaseStats struct {
Hp int
HpMax int
Mp int
MpMax int
Strength int
Speed int
Intelligence int
}
type Stats struct {
Base map[string]int
Modifiers []string
}
func StatsCreate(stats BaseStats) Stats {
s := Stats{
Base: make(map[string]int),
}
//Iterate through the fields of a struct
v := reflect.ValueOf(stats)
typeOfS := v.Type()
for i := 0; i< v.NumField(); i++ {
val := v.Field(i).Interface().(int)
s.Base[typeOfS.Field(i).Name] = val
}
return s
}
func (s Stats) GetBaseStat(id string) int {
return s.Base[id]
}
func main() {
m := StatsCreate(BaseStats{300, 300, 300, 300, 10, 10, 10})
fmt.Println(m.GetBaseStat("Hp"))
}
CREATE TABLE [dbo].[History](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]
After following the answers above , and did
Project -> Properties -> Application -> Target Framework -> select ".Net Framework 4"
It still didn't work until I went to
Project -> Add Reference
And selected System.web
.
And everything worked link a charm.
@phidah... Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too
So it would look like this instead:
<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />
If you need to reference a dynamically generated value you can also append query string paramters after the @URL.Action like so:
var id = $(this).attr('id');
var value = $(this).attr('value');
$('#user_content').load('@Url.Action("UserDetails","User")?Param1=' + id + "&Param2=" + value);
public ActionResult Details( int id, string value )
{
var model = GetFooModel();
if (Request.IsAjaxRequest())
{
return PartialView( "UserDetails", model );
}
return View(model);
}
try to implement with javascript this:
<div id="mydiv" onclick="myhref('http://web.com');" >some stuff </div>
<script type="text/javascript">
function myhref(web){
window.location.href = web;}
</script>
My preferred method is to use PadRight. Instead of clearing the line first, this clears the remainder of the line after the new text is displayed, saving a step:
Console.CursorTop = 0;
Console.CursorLeft = 0;
Console.Write("Whatever...".PadRight(Console.BufferWidth));
db.<collection>.find({}, {field1: <value>, field2: <value> ...})
In your example, you can do something like:
db.students.find({}, {"roll":true, "_id":false})
Projection
The projection parameter determines which fields are returned in the matching documents. The projection parameter takes a document of the following form:
{ field1: <value>, field2: <value> ... }
The <value> can be any of the following:
1 or true to include the field in the return documents.
0 or false to exclude the field.
NOTE
For the _id field, you do not have to explicitly specify _id: 1 to return the _id field. The find() method always returns the _id field unless you specify _id: 0 to suppress the field.
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
My very simple solution that worked: select another networkcard!
If it doesn't work, repeat steps and try yet another network adapter. The very basic PCnet adapters have a high succes-rate.
Good luck.
You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:
NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];
You can delete an index in python as follows
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host':'localhost', 'port':'9200'}])
es.index(index='grades',doc_type='ist_samester',id=1,body={
"Name":"Programming Fundamentals",
"Grade":"A"
})
es.indices.delete(index='grades')
You can also use the Cookies API and do:
browser.cookies.set({
url: 'example.com',
name: 'HelloWorld',
value: 'HelloWorld',
expirationDate: myDate
}
There's no need to remove an account: I switched Google Play to a second Google account, installed an update, and switched back to my original account.
Though apparently, it's sufficient to just switch to a second Google Account, and switch back to the original account, no need to install an update.
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
here is how you can do it:
string stringToCheck = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (stringToCheck.Contains(x))
{
// Process...
}
}
UPDATE: May be you are looking for a better solution.. refer to @Anton Gogolev's answer below which makes use of LINQ.
This will work nicely with in-line arrays. Plus, I think things are tidier and more reusable when wrapped up in a function.
function array_rand_value($a) {
return $a[array_rand($a)];
}
Usage:
array_rand_value(array("a", "b", "c", "d"));
On PHP < 7.1.0, array_rand()
uses rand()
, so you wouldn't want to this function for anything related to security or cryptography. On PHP 7.1.0+, use this function without concern since rand()
has been aliased to mt_rand()
.
I have implemented a C# version, it is easily converted to C++.
public bool Intersects ( Rectangle rect )
{
float ulx = Math.Max ( x, rect.x );
float uly = Math.Max ( y, rect.y );
float lrx = Math.Min ( x + width, rect.x + rect.width );
float lry = Math.Min ( y + height, rect.y + rect.height );
return ulx <= lrx && uly <= lry;
}
I did it like this in my Jtable its autorefreshing after 300 ms;
DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
JTable table = new JTable();
Timer t = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData(set);
table.setModel(model);
}
});
t.start();
private void addColumns() {
model.setColumnCount(0);
model.addColumn("NAME");
model.addColumn("EMAIL");}
private void remakeData(CollectionType< Objects > name) {
model.setRowCount(0);
for (CollectionType Objects : name){
String n = Object.getName();
String e = Object.getEmail();
model.insertRow(model.getRowCount(),new Object[] { n,e });
}}
I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange
You can use float:left in DIV or use SPAN tag, like
<div style="width:100px;float:left"> First </div>
<div> Second </div>
<br/>
or
<span style="width:100px;"> First </span>
<span> Second </span>
<br/>
It seems like one 'answer' to this is to implement an SMPT client. See email.js for a JavaScript library with an SMTP client.
Here's the GitHub repo for the SMTP client. Based on the repo's README, it appears that various shims or polyfills may be required depending on the client browser, but overall it does certainly seem feasible (if not actually significantly accomplished), tho not in a way that's easily describable by even a reasonably-long answer here.
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
Emacs can handle huge file sizes and you can use it on Windows or *nix.
string data = "THExxQUICKxxBROWNxxFOX";
return data.Replace("xx","|").Split('|');
Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!
Use the following: Long.valueOf(int);
.
Starting with SQL Server 2012, you can use FORMAT and DATEFROMPARTS to solve this problem. (If you want month names from other cultures, change: en-US
)
select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')
If you want a three-letter month:
select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMM', 'en-US')
If you really want to, you can create a function for this:
CREATE FUNCTION fn_month_num_to_name
(
@month_num tinyint
)
RETURNS varchar(20)
AS
BEGIN
RETURN FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')
END
I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.
I simply put my php files in the www/
folder, changed the name of .exe
and was able to run my php as an exe !!
Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.
You do not really need jQuery for such tasks. In the ES6 specification they already have out of the box methods startsWith and endsWith.
var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be")); // true
alert(str.startsWith("not to be")); // false
alert(str.startsWith("not to be", 10)); // true
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
Currently available in FF and Chrome. For old browsers you can use their polyfills or substr
if the name of your list is listlen
then just type len(listlen)
. This will return the size of your list in the python.
You can wrap it in your own function:
function isNullAndUndef(variable) {
return (variable !== null && variable !== undefined);
}
Vim has a branch operator \&
that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.
For example,
/.*jack\&.*james
will match a line containing jack
and james
, in any order.
See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.
Where do these values come from? The documentation for android:fontFamily does not list this information in any place
These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.
In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:
Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:
<item name="android:fontFamily">sans-serif</item>
Like the linked answer already stated, 12 variants are possible:
Regular (default):
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item>
Italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>
Bold:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
Bold-italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>
Light:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
Light-italic:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>
Thin :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>
Thin-italic :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>
Condensed regular:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>
Condensed italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>
Condensed bold:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>
Condensed bold-italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>
Medium:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>
Medium-italic:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>
Black:
<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>
For quick reference, this is how they all look like:
Working with Git 2.3.2 ...
git branch --set-upstream-to myfork/master
Now status
, push
and pull
are pointed to myfork
remote
If you're a fan of NumPy
ish syntax, then there's tensor.shape
.
In [3]: ar = torch.rand(3, 3)
In [4]: ar.shape
Out[4]: torch.Size([3, 3])
# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]
# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]
# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]
P.S.: Note that tensor.shape
is an alias to tensor.size()
, though tensor.shape
is an attribute of the tensor in question whereas tensor.size()
is a function.
I want to add somethings different from definitions of words. Most of them will be visual.
Technically, LDAP is just a protocol that defines the method by which directory data is accessed.Necessarily, it also defines and describes how data is represented in the directory service
Data is represented in an LDAP system as a hierarchy of objects, each of which is called an entry. The resulting tree structure is called a Directory Information Tree (DIT). The top of the tree is commonly called the root (a.k.a base or the suffix).
To navigate the DIT we can define a path (a DN) to the place where our data is (cn=DEV-India,ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com will take us to a unique entry) or we can define a path (a DN) to where we think our data is (say, ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com) then search for the attribute=value or multiple attribute=value pairs to find our target entry (or entries).
If you want to get more depth information, you visit here
The fastest way yuo get over it is to replace origin
with the suggestion it gives.
Instead of git push origin master
, use:
git push [email protected]:my_user_name/my_repo.git master
Static typed languages (compiler resolves method calls and compile references):
Dynamic typed languages (decisions taken in running program):
I liked @rich.kelly's answer, but I wanted to use the same nomenclature as classList.add()
(comma seperated strings), so a slight deviation.
DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function() {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function() {
for (var i = 0; i < arguments.length; i++) {
this.remove(arguments[i]);
}
}
So you can then use:
document.body.classList.addMany('class-one','class-two','class-three');
I need to test all browsers, but this worked for Chrome.
Should we be checking for something more specific than the existence of DOMTokenList.prototype.addMany
? What exactly causes classList.add()
to fail in IE11?
My quick & dirty JSON dump that eats dates and everything:
json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)
default
is a function applied to objects that aren't serializable.
In this case it's str
, so it just converts everything it doesn't know to strings. Which is great for serialization but not so great when deserializing (hence the "quick & dirty") as anything might have been string-ified without warning, e.g. a function or numpy array.
Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
All that's needed is: Start a new query and run:
SET SQL_SAFE_UPDATES = 0;
Then: Run the query that you were trying to run that wasn't previously working.
With the use of the bootstrap 4 utilities you could horizontally center an element itself by setting the horizontal margins to 'auto'.
To set the horizontal margins to auto you can use mx-auto
. The m
refers to margin and the x
will refer to the x-axis (left+right) and auto
will refer to the setting. So this will set the left margin and the right margin to the 'auto' setting. Browsers will calculate the margin equally and center the element. The setting will only work on block elements so the display:block needs to be added and with the bootstrap utilities this is done by d-block
.
<button type="submit" class="btn btn-primary mx-auto d-block">Submit</button>
You can consider all browsers to fully support auto margin settings according to this answer Browser support for margin: auto so it's safe to use.
The bootstrap 4 class text-center
is also a very good solution, however it needs a parent wrapper element. The benefit of using auto margin is that it can be done directly on the button element itself.
If you don't know what property caused the error, you can, using reflection, loop over all properties:
public static String ShowAllErrors<T>(this HtmlHelper helper) {
StringBuilder sb = new StringBuilder();
Type myType = typeof(T);
PropertyInfo[] propInfo = myType.GetProperties();
foreach (PropertyInfo prop in propInfo) {
foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Where T is the type of your "ViewModel".
var h = document.getElementById('First').scrollHeight;
$('#First').animate({ height : h+'px' },300);