For me, the menu item Inspect Devices wasn't available (not shown at all). But, simply browsing to chrome://inspect/#devices showed me my device and I was able to use the port forward etc. I have no idea why the menu item is not displayed.
Phone: Android Galaxy S4
OS: Mac OS X
Try using String.format()
:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(String.format("%s",x));
Question is too old and my answer might not add much but here are my two cents for making query a little useful:
;WITH DistinctRecords AS (
SELECT DISTINCT [col1,col2,col3,..]
FROM tableName
where [my condition]
),
serialize AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY [colNameAsNeeded] ORDER BY [colNameNeeded]) AS Sr,*
FROM DistinctRecords
)
SELECT * FROM serialize
Usefulness of using two cte's lies in the fact that now you can use serialized record much easily in your query and do count(*)
etc very easily.
DistinctRecords
will select all distinct records and serialize
apply serial numbers to distinct records. after wards you can use final serialized result for your purposes without clutter.
Partition By
might not be needed in most cases
table { width: 100%; }
Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.
$("#tableid").width($(window).width());
If not, use this snippet
<style>
body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
<tr>
<td>Just a Test
</td>
</tr>
</table>
You will notice that the width is perfectly covering the page.
The main thing is too nullify the margin
and padding
as I have shown at the body, then you are set.
For anyone who is using anaconda, you would install the certifi
package, see more at:
https://anaconda.org/anaconda/certifi
To install, type this line in your terminal:
conda install -c anaconda certifi
You could use actionLayout
from the support library.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/button_item"
android:title=""
app:actionLayout="@layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}
Call the function in this way:
self.parse_file()
You also need to define your parse_file() function like this:
def parse_file(self):
The parse_file
method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the object, in your case the instance is self
.
Have created a simple dictionary in JS here:
function JSdict() {
this.Keys = [];
this.Values = [];
}
// Check if dictionary extensions aren't implemented yet.
// Returns value of a key
if (!JSdict.prototype.getVal) {
JSdict.prototype.getVal = function (key) {
if (key == null) {
return "Key cannot be null";
}
for (var i = 0; i < this.Keys.length; i++) {
if (this.Keys[i] == key) {
return this.Values[i];
}
}
return "Key not found!";
}
}
// Check if dictionary extensions aren't implemented yet.
// Updates value of a key
if (!JSdict.prototype.update) {
JSdict.prototype.update = function (key, val) {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
// Verify dict integrity before each operation
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Values[i] = val;
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Adds a unique key value pair
if (!JSdict.prototype.add) {
JSdict.prototype.add = function (key, val) {
// Allow only strings or numbers as keys
if (typeof (key) == "number" || typeof (key) == "string") {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
return "Duplicate keys not allowed!";
}
}
this.Keys.push(key);
this.Values.push(val);
}
else {
return "Only number or string can be key!";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Removes a key value pair
if (!JSdict.prototype.remove) {
JSdict.prototype.remove = function (key) {
if (key == null) {
return "Key cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Keys.shift(key);
this.Values.shift(this.Values[i]);
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
var dict = new JSdict();
dict.add(1, "one")
dict.add(1, "one more")
"Duplicate keys not allowed!"
dict.getVal(1)
"one"
dict.update(1, "onne")
dict.getVal(1)
"onne"
dict.remove(1)
dict.getVal(1)
"Key not found!"
This is just a basic simulation. It can be further optimized by implementing a better running time algorithm to work in atleast O(nlogn) time complexity or even less. Like merge/quick sort on arrays and then some B-search for lookups. I Didn't give a try or searched about mapping a hash function in JS.
Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.
Hope this helps!
EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.
However, I would like to make a special mention about two methods that actually proved helpful to make it a convenient hashtable experience.
Viz: dict.hasOwnProperty(key) and delete dict[key]
Read this post as a good resource on this implementation/usage. Dynamically creating keys in JavaScript associative array
THanks!
Here is another oneliner to install the latest version of docker-compose using curl and sed.
curl -L "https://github.com/docker/compose/releases/download/`curl -fsSLI -o /dev/null -w %{url_effective} https://github.com/docker/compose/releases/latest | sed 's#.*tag/##g' && echo`/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose && chmod +x /usr/local/bin/docker-compose
DECLARE @t TABLE (ID UNIQUEIDENTIFIER DEFAULT NEWID(),myid UNIQUEIDENTIFIER
, friendid UNIQUEIDENTIFIER, time1 Datetime, time2 Datetime)
insert into @t (myid,friendid,time1,time2)
values
( CONVERT(uniqueidentifier,'0C6A36BA-10E4-438F-BA86-0D5B68A2BB15'),
CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E'),
'2014-01-05 02:04:41.953','2014-01-05 12:04:41.953')
SELECT * FROM @t
Result Set With out any errors
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
¦ ID ¦ myid ¦ friendid ¦ time1 ¦ time2 ¦
¦--------------------------------------+--------------------------------------+--------------------------------------+-------------------------+-------------------------¦
¦ CF628202-33F3-49CF-8828-CB2D93C69675 ¦ 0C6A36BA-10E4-438F-BA86-0D5B68A2BB15 ¦ DF215E10-8BD4-4401-B2DC-99BB03135F2E ¦ 2014-01-05 02:04:41.953 ¦ 2014-01-05 12:04:41.953 ¦
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Initialize express router
let router = require('express').Router();
router.get('/', function (req, res) {
res.json({
status: `API Its Working`,
route: router.stack.filter(r => r.route)
.map(r=> { return {"path":r.route.path,
"methods":r.route.methods}}),
message: 'Welcome to my crafted with love!',
});
});
Import user controller
var userController = require('./controller/userController');
User routes
router.route('/users')
.get(userController.index)
.post(userController.new);
router.route('/users/:user_id')
.get(userController.view)
.patch(userController.update)
.put(userController.update)
.delete(userController.delete);
Export API routes
module.exports = router;
Output
{"status":"API Its Working, APP Route","route":
[{"path":"/","methods":{"get":true}},
{"path":"/users","methods":{"get":true,"post":true}},
{"path":"/users/:user_id","methods": ....}
I'm not sure what format you're looking for in your difference but here's how to do it using DateTime
$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;
For this you can use the readonly
modifier. Object properties which are readonly
can only be assigned during initialization of the object.
Example in classes:
class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius * 2;
}
}
const circle = new Circle(12);
circle.radius = 12; // Cannot assign to 'radius' because it is a read-only property.
Example in Object literals:
type Rectangle = {
readonly height: number;
readonly width: number;
};
const square: Rectangle = { height: 1, width: 2 };
square.height = 5 // Cannot assign to 'height' because it is a read-only property
It's also worth knowing that the readonly
modifier is purely a typescript construct and when the TS is compiled to JS the construct will not be present in the compiled JS. When we are modifying properties which are readonly the TS compiler will warn us about it (it is valid JS).
Try:
printf("%04x",a);
0
- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4
(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x
- Specifier for hexadecimal
integer.More here
Here is a script:
SH1.csv
to SH200.csv
import glob
import re
# Looking for filenames like 'SH1.csv' ... 'SH200.csv'
pattern = re.compile("^SH([1-9]|[1-9][0-9]|1[0-9][0-9]|200).csv$")
file_parts = [name for name in glob.glob('*.csv') if pattern.match(name)]
with open("file_merged.csv","wb") as file_merged:
for (i, name) in enumerate(file_parts):
with open(name, "rb") as file_part:
if i != 0:
next(file_part) # skip headers if not first file
file_merged.write(file_part.read())
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.
snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811
The index of the current array item has been available for some time now via @index:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
For object iteration, use @key instead:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
When you push to a remote and you use the --set-upstream
flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.
Adding a remote tracking branch means that git then knows what you want to do when you git fetch
, git pull
or git push
in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.
You could achieve the same thing with git branch --set-upstream-to
or git checkout --track
. See the git help pages on tracking branches for more information.
You can use @WebFilter javax.servlet.annotation.WebFilter on a class that implements javax.servlet.Filter
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {}
Then use @ServletComponentScan to register
When you want to pass new information to your application, you need to use POST form. In Razor you can use the following
View Code:
@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
@Html.Hidden("id", Model.Id)
@Html.Hidden("productid", Model.ProductId)
@Html.TextBox("qty", Model.Quantity)
@Html.TextBox("unitrate", Model.UnitRate)
<input type="submit" value="Update" />
}
Controller's actions
[HttpGet]
public ActionResult Update(){
//[...] retrive your record object
return View(objRecord);
}
[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
if (ModelState.IsValid){
int _records = UpdatePrice(id,productid,qty,unitrate);
if (_records > 0){ {
return RedirectToAction("Index1", "Shopping");
}else{
ModelState.AddModelError("","Can Not Update");
}
}
return View("Index1");
}
Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity)
you can either have an input with the name (respectecting case) "Quantity"
or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:
Model
public class Record {
public string Id { get; set; }
public string ProductId { get; set; }
public string Quantity { get; set; }
public decimal UnitRate { get; set; }
}
View
@using(Html.BeginForm("Update")){
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.ProductId)
@Html.TextBoxFor(model=> model.Quantity)
@Html.TextBoxFor(model => model.UnitRate)
<input type="submit" value="Update" />
}
Post Action
[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well
if(TryValidateModel(rec)){
//update code
}
return View("Index1");
}
I just resolved the same problem.
Dependency Walker is misleading in this case and caused me to lose time. So, the list of "missing" DLL files from the first post is not helpful, and you can probably ignore it.
The solution is to find which references your project is calling and check if they are really installed on the server.
@Ben Brammer, it is not important which three .ocx files are missing, because they are missing only for Leo T Abraham's project. Your project probably calls other DLL files.
In my case, it was not three .ocx files, but missing MySQL connector DLL file. After installing of MySQL Connector for .NET on server, the problem disappeared.
So, in short, the solution is: check if all your project references are there.
Either way will add an entity to a PersistenceContext, the difference is in what you do with the entity afterwards.
Persist takes an entity instance, adds it to the context and makes that instance managed (ie future updates to the entity will be tracked).
Merge returns the managed instance that the state was merged to. It does return something what exists in PersistenceContext or creates a new instance of your entity. In any case, it will copy the state from the supplied entity, and return managed copy. The instance you pass in will not be managed (any changes you make will not be part of the transaction - unless you call merge again). Though you can use the returned instance (managed one).
Maybe a code example will help.
MyEntity e = new MyEntity();
// scenario 1
// tran starts
em.persist(e);
e.setSomeField(someValue);
// tran ends, and the row for someField is updated in the database
// scenario 2
// tran starts
e = new MyEntity();
em.merge(e);
e.setSomeField(anotherValue);
// tran ends but the row for someField is not updated in the database
// (you made the changes *after* merging)
// scenario 3
// tran starts
e = new MyEntity();
MyEntity e2 = em.merge(e);
e2.setSomeField(anotherValue);
// tran ends and the row for someField is updated
// (the changes were made to e2, not e)
Scenario 1 and 3 are roughly equivalent, but there are some situations where you'd want to use Scenario 2.
The easiest thing to do is to move the file from your local directory temporarily, then commit changes to your remote repo. Then add it back to your local repo, make sure to update .gitignore so it doesn't commit to remote again
I know this topic is old but I think my answer can be useful for a lot of people.
Here is jQuery plugin made from Pointy's answer using ES6:
/**
* Sort values alphabetically in select
* source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
*/
$.fn.extend({
sortSelect() {
let options = this.find("option"),
arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => { // sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
}
});
Use is very easy
$("select").sortSelect();
Near the top of the file, you need to write var fadeDiv = ...
instead of fadeDiv = ...
so that the variable is actually declared.
The error "Property 'fadeDiv' does not exist on type '{}'.
" seems to be triggering on a line you haven't posted in your example (there is no access of a fadeDiv
property anywhere in that snippet).
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
A more reliable REST endpoint would be http://freegeoip.net/json/
Returns the ip address along with the geo-location too. Also has cross-domain requests enabled (Access-Control-Allow-Origin: *) so you don't have to code around JSONP.
You can override the onBackPressed()
method in your activity and remove the call to super class.
@Override
public void onBackPressed() {
//remove call to the super class
//super.onBackPressed();
}
It's not in the language core, but a very mature library that does what you want is Twisted. It introduces the Deferred object, which you can attach callbacks or error handlers ("errbacks") to. A Deferred is basically a "promise" that a function will have a result eventually.
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
This is how you do it, I have checked it and it works on my Laravel 4.2.
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
Hope this helps.
Run
cordova -v
to see the currently running version. Run the npm info command
npm info cordova
for a longer listing that includes the current version along with other available version numbers
I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.
private void Info_MouseHover(object sender, EventArgs e)
{
Control senderObject = sender as Control;
string hoveredControl = senderObject.Tag.ToString();
// only instantiate a tooltip if the control's tag contains data
if (hoveredControl != "")
{
ToolTip info = new ToolTip
{
AutomaticDelay = 500
};
string tooltipMessage = string.Empty;
// add all conditionals here to modify message based on the tag
// of the hovered control
if (hoveredControl == "save button")
{
tooltipMessage = "This button will save stuff.";
}
info.SetToolTip(senderObject, tooltipMessage);
}
}
Use this FAQ page: Apache log4net Frequently Asked Questions
About 3/4 of the way down it tells you how to enable log4net debugging by using application tracing. This will tell you where your issue is.
The basics are:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
And you see the trace in the standard output
<iframe src="https://www.youtube.com/embed/7cjVj1ZyzyE?autoplay=1&loop=1&playlist=7cjVj1ZyzyE&mute=1" frameborder="0" allowfullscreen></iframe>
_x000D_
mute=1
you can use success function, once see this jquery.ajax settings
$('#ChangePermission').click(function(){
$.ajax({
url: 'change_permission.php',
type: 'POST',
data: {
'user': document.GetElementById("user").value,
'perm': document.GetElementById("perm").value
}
success:function(result)//we got the response
{
//you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
}
})
})
we can also have error() function
hope this helps you
Add this line to your jQuery code:
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
and done.
if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
echo 'Success';
} else {
echo 'Fail';
}
Although since you have or die(mysql_error())
it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result
The experiment was: EXPERIMENT
Add a method to Card that creates a full deck of cards, with one card of each combination of rank and suit.
So without modifying or enhancing the given code other than adding the method (and without using stuff that hasn't been taught yet), I came up with this solution:
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
func createDeck() -> [Card] {
var deck: [Card] = []
for rank in Rank.Ace.rawValue...Rank.King.rawValue {
for suit in Suit.Spades.rawValue...Suit.Clubs.rawValue {
let card = Card(rank: Rank(rawValue: rank)!, suit: Suit(rawValue: suit)!)
//println(card.simpleDescription())
deck += [card]
}
}
return deck
}
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
let deck = threeOfSpades.createDeck()
I have faced similar problem
So
I just do
1.update Maven Project
2.install maven.
Removing with
rm -rf .*
may get you into trouble or some more errors.
If you have /path/to/folder, and would like to remove everything inside, but not that folder, just run:
rm -rf /path/to/folder/*
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
Import connect
from react-redux
and use it to connect the component with the state connect(mapStates,mapDispatch)(component)
import React from "react";
import { connect } from "react-redux";
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
</div>
);
}
}
Finally you need to map the states to the props to access them with this.props
const mapStateToProps = state => {
return {
title: state.title
};
};
export default connect(mapStateToProps)(MyComponent);
Only the states that you map will be accessible via props
Check out this answer: https://stackoverflow.com/a/36214059/4040563
For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132
I would use git submodules
.
have a look here Git repository in a Git repository
As per February2019, I would suggest Monorepos
Yeah, no checkbox for you in iOS (-:
Here, this is what I did to create a checkbox:
UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:
[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Now in the target method do the following:
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected; /* Toggle */
[checkbox setSelected:checkBoxSelected];
}
That's it!
$ sudo apt-get update
$ sudo apt-get install htop
$ htop
I made a small library that lets you easily use a throbber without images.
It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.
// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);
// Start the throbber.
throbber.play();
// Pause the throbber.
throbber.pause();
If you are using "n" library @ https://github.com/tj/n . Do the following
echo $NODE_PATH
If node path is empty, then
sudo n latest - sudo is optional depending on your system
After switching Node.js versions using n, npm may not work properly.
curl -0 -L https://npmjs.com/install.sh | sudo sh
echo NODE_PATH
You should see your Node Path now. Else, it might be something else
One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frequently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory available for bitmaps.
Bitmaps on the previous activity layout are not properly de-allocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.
First, set the “id” attribute on the parent view of your XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/RootView"
>
...
Then, on the onDestroy()
method of your Activity, call the unbindDrawables()
method passing a reference to the parent View and then do a System.gc()
.
@Override
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.RootView));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
This unbindDrawables()
method explores the view tree recursively and:
There is no way to do this in C. There are a lot of different approaches. Typically the simplest is to define a set of constants that represent your strings and do a look up by string on to get the constant:
#define BADKEY -1
#define A1 1
#define A2 2
#define B1 3
#define B2 4
typedef struct { char *key; int val; } t_symstruct;
static t_symstruct lookuptable[] = {
{ "A1", A1 }, { "A2", A2 }, { "B1", B1 }, { "B2", B2 }
};
#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))
int keyfromstring(char *key)
{
int i;
for (i=0; i < NKEYS; i++) {
t_symstruct *sym = lookuptable[i];
if (strcmp(sym->key, key) == 0)
return sym->val;
}
return BADKEY;
}
/* ... */
switch (keyfromstring(somestring)) {
case A1: /* ... */ break;
case A2: /* ... */ break;
case B1: /* ... */ break;
case B2: /* ... */ break;
case BADKEY: /* handle failed lookup */
}
There are, of course, more efficient ways to do this. If you keep your keys sorted, you can use a binary search. You could use a hashtable too. These things change your performance at the expense of maintenance.
Not to reorganize imports (not to unfold .* and not to reorder lines) to have least VCS changeset
you can use custom eclipse clenup as this answer suggests
The issue in the original question is that you are not capturing "page" event, to resolve this you need to add (page)='yourEventHandler($event)
' as an attribute in the md-paginator tag.
check a working example here
You can also check the API docs here
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid
in its place, not just 1, of course. And, I just made up the cid
value.
I found my answer here https://stackoverflow.com/a/19271434/1363220, bassically
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
if($d && $d->format($format) === $date) {
//it's a proper date!
}
else {
//it's not a proper date
}
You can use **kwargs
to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):
>>> def print_keyword_args(**kwargs):
... # kwargs is a dict of the keyword args passed to the function
... for key, value in kwargs.iteritems():
... print "%s = %s" % (key, value)
...
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe
You can also use the **kwargs
syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:
>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith
The Python Tutorial contains a good explanation of how it works, along with some nice examples.
<--Update-->
For people using Python 3, instead of iteritems(), use items()
Based on what React Docs say:
Handling Multiple Inputs. When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value
});
};
render() {
return (
<div className="radio-buttons">
Windows
<input
id="windows"
value="windows"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Mac
<input
id="mac"
value="mac"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Linux
<input
id="linux"
value="linux"
name="platform"
type="radio"
onChange={this.handleChange}
/>
</div>
);
}
}
Link to example: https://codesandbox.io/s/6l6v9p0qkr
At first, none of the radio buttons is selected so this.state
is an empty object, but whenever the radio button is selected this.state
gets a new property with the name of the input and its value. It eases then to check whether user selected any radio-button like:
const isSelected = this.state.platform ? true : false;
EDIT:
With version 16.7-alpha of React there is a proposal for something called hooks
which will let you do this kind of stuff easier:
In the example below there are two groups of radio-buttons in a functional component. Still, they have controlled inputs:
function App() {
const [platformValue, plaftormInputProps] = useRadioButtons("platform");
const [genderValue, genderInputProps] = useRadioButtons("gender");
return (
<div>
<form>
<fieldset>
Windows
<input
value="windows"
checked={platformValue === "windows"}
{...plaftormInputProps}
/>
Mac
<input
value="mac"
checked={platformValue === "mac"}
{...plaftormInputProps}
/>
Linux
<input
value="linux"
checked={platformValue === "linux"}
{...plaftormInputProps}
/>
</fieldset>
<fieldset>
Male
<input
value="male"
checked={genderValue === "male"}
{...genderInputProps}
/>
Female
<input
value="female"
checked={genderValue === "female"}
{...genderInputProps}
/>
</fieldset>
</form>
</div>
);
}
function useRadioButtons(name) {
const [value, setState] = useState(null);
const handleChange = e => {
setState(e.target.value);
};
const inputProps = {
name,
type: "radio",
onChange: handleChange
};
return [value, inputProps];
}
Working example: https://codesandbox.io/s/6l6v9p0qkr
thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:
var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday then add 1 day
// my mac on bst still treats day 1 as sunday
var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') :
moment().startOf('week').format('dddd DD-MM-YYYY');
document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' +
begin.format('dddd DD-MM-YYYY') +
'<br /><br /> <b>should be monday:</b> <br>' + firstDay +
'<br><br> <b>could also be sunday or monday </b><br> ' +
begin2.format('dddd DD-MM-YYYY');
To be more clear, I will begin at the beginning.
I will rely on the sample code found in https://github.com/ExcelDataReader/ExcelDataReader, but with some modifications to avoid inconveniences.
The following code detects the file format, either xls or xlsx.
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader;
//1. Reading Excel file
if (Path.GetExtension(filePath).ToUpper() == ".XLS")
{
//1.1 Reading from a binary Excel file ('97-2003 format; *.xls)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else
{
//1.2 Reading from a OpenXml Excel file (2007 format; *.xlsx)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
//2. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//3. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = false;
Now we can access the file contents in a more convenient way. I use DataTable for this. The following is an example to access a specific cell, and print its value in the console:
DataTable dt = result.Tables[0];
Console.WriteLine(dt.Rows[rowPosition][columnPosition]);
If you do not want to do a DataTable, you can do the same as follows:
Console.WriteLine(result.Tables[0].Rows[rowPosition][columnPosition]);
It is important not try to read beyond the limits of the table, for this you can see the number of rows and columns as follows:
Console.WriteLine(result.Tables[0].Rows.Count);
Console.WriteLine(result.Tables[0].Columns.Count);
Finally, when you're done, you should close the reader and free resources:
//5. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
I hope you find it useful.
(I understand that the question is old, but I make this contribution to enhance the knowledge base, because there is little material about particular implementations of this library).
The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:
{
"env": {},
"extends": [],
"parser": "",
"plugins": [],
"rules": {},
"overrides": [
{
"files": ["test/*.spec.js"], // Or *.test.js
"rules": {
"require-jsdoc": "off"
}
}
],
"settings": {}
}
If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.
The end result is that the operation is amortized O(n).
e.g.
s = ""
for i in range(n):
s+=str(i)
used to be O(n^2), but now it is O(n).
From the source (bytesobject.c):
void
PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
PyBytes_Concat(pv, w);
Py_XDECREF(w);
}
/* The following function breaks the notion that strings are immutable:
it changes the size of a string. We get away with this only if there
is only one module referencing the object. You can also think of it
as creating a new string object and destroying the old one, only
more efficiently. In any case, don't use this if the string may
already be known to some other part of the code...
Note that if there's not enough memory to resize the string, the original
string object at *pv is deallocated, *pv is set to NULL, an "out of
memory" exception is set, and -1 is returned. Else (on success) 0 is
returned, and the value in *pv may or may not be the same as on input.
As always, an extra byte is allocated for a trailing \0 byte (newsize
does *not* include that), and a trailing \0 byte is stored.
*/
int
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
{
register PyObject *v;
register PyBytesObject *sv;
v = *pv;
if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
*pv = 0;
Py_DECREF(v);
PyErr_BadInternalCall();
return -1;
}
/* XXX UNREF/NEWREF interface should be more symmetrical */
_Py_DEC_REFTOTAL;
_Py_ForgetReference(v);
*pv = (PyObject *)
PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
if (*pv == NULL) {
PyObject_Del(v);
PyErr_NoMemory();
return -1;
}
_Py_NewReference(*pv);
sv = (PyBytesObject *) *pv;
Py_SIZE(sv) = newsize;
sv->ob_sval[newsize] = '\0';
sv->ob_shash = -1; /* invalidate cached hash value */
return 0;
}
It's easy enough to verify empirically.
$ python -m timeit -s"s=''" "for i in xrange(10):s+='a'" 1000000 loops, best of 3: 1.85 usec per loop $ python -m timeit -s"s=''" "for i in xrange(100):s+='a'" 10000 loops, best of 3: 16.8 usec per loop $ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 10000 loops, best of 3: 158 usec per loop $ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 1000 loops, best of 3: 1.71 msec per loop $ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 14.6 msec per loop $ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'" 10 loops, best of 3: 173 msec per loop
It's important however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance .
$ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'" 10000 loops, best of 3: 90.8 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'" 1000 loops, best of 3: 896 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 100 loops, best of 3: 9.03 msec per loop $ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 10 loops, best of 3: 89.5 msec per loop
So far so good, but then,
$ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 12.8 sec per loop
ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.
<button type="button" href="location.href='#/nameOfState'">Title on button</button>
Even more simple... (note the single quotes around the address)
I will add my upgraded version of filter which able to supports next syntax:
ng-repeat="(id, item) in $ctrl.modelData | orderObjectBy:'itemProperty.someOrder':'asc'
app.filter('orderObjectBy', function(){
function byString(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
return function(input, attribute, direction) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
if (input.hasOwnProperty(objectKey)) {
array.push(input[objectKey]);
}
}
array.sort(function(a, b){
a = parseInt(byString(a, attribute));
b = parseInt(byString(b, attribute));
return direction == 'asc' ? a - b : b - a;
});
return array;
}
})
Thanks to Armin and Jason for their answers in this thread, and Alnitak in this thread.
def (value1, value2) = '1128-2'.split('-')
should work.
Can anyone please try this in Groovy Console?
def (v, z) = '1128-2'.split('-')
assert v == '1128'
assert z == '2'
You can also set background is transparent. So the button looks like fit your icon.
<ImageButton
android:id="@+id/Button01"
android:scaleType="fitcenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cropToPadding="false"
android:paddingLeft="10dp"
android:background="@android:color/transparent"
android:src="@drawable/eye" />
You will love this framework.
And you will love this tool.
For learning about JSON you might like this resource.
And you'll probably love this tutorial.
We should always go for equals() method for comparison for two integers.Its the recommended practice.
If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.
Please see examples:
Case 1:
Integer a = 100; Integer b = 100;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.
Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.
Integer a = 220; Integer b = 220;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
Proper way:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
I hope this helps.
I realize this is a bit late, but I've had success with annotating a timestamp column with
@Column(name="timestamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
This should also work with CURRENT_DATE
and CURRENT_TIME
. I'm using JPA/Hibernate with Oracle, so YMMV.
This should handle issue:
SPOOL_FILE=${LOG_DIR}/${LOG_FILE_NAME}.spool
SQLPLUS_OUTPUT=`sqlplus -s "$SFDC_WE_CORE" <<EOF
SET HEAD OFF
SET AUTOPRINT OFF
SET TERMOUT OFF
SET SERVEROUTPUT ON
SPOOL ${SPOOL_FILE}
WHENEVER SQLERROR EXIT SQL.SQLCODE
DECLARE
BEGIN
foooo
--rollback;
END;
/
EOF`
RC=$?
if [[ $RC != 0 ]] ; then
echo " RDBMS exit code : $RC " | tee -a ${LOG_FILE}
cat ${SPOOL_FILE} | tee -a ${LOG_FILE}
cat ${LOG_FILE} | mail -s "Script ${INIT_EXE} failed on $SFDC_ENV" $SUPPORT_LIST
exit 3
fi
You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.
Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);
Now in your NewActivity, you can get this bundle and retrive your value.
Bundle bundle = getArguments();
String value = bundle.getString(key);
You can also pass data through the intent. In your current activity, set intent like this,
Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);
Now in your NewActivity, you can get that value from intent like this,
String value = getIntent().getExtras().getString(key);
Define it as
<return type> AnalyzeArray(ArrayList<Integer> list) {
Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup
$("#div").html($("#input").val());
r+
is the canonical mode for reading and writing at the same time. This is not different from using the fopen()
system call since file()
/ open()
is just a tiny wrapper around this operating system call.
Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.
Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:
public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime { get { return utcDateTime; } }
public TimeZoneInfo TimeZone { get { return timeZone; } }
public DateTime LocalTime
{
get
{
return TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}
}
}
You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.
The answer to your question is ultimately, it depends. The links in that navigation are added via different layout XML files. Here's the code that first defines the block in layout/customer.xml
. Notice that it also defines some links to add to the menu:
<block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
<action method="addLink" translate="label" module="customer"><name>account</name><path>customer/account/</path><label>Account Dashboard</label></action>
<action method="addLink" translate="label" module="customer"><name>account_edit</name><path>customer/account/edit/</path><label>Account Information</label></action>
<action method="addLink" translate="label" module="customer"><name>address_book</name><path>customer/address/</path><label>Address Book</label></action>
</block>
Other menu items are defined in other layout files. For example, the Reviews module uses layout/review.xml
to define its layout, and contains the following:
<customer_account>
<!-- Mage_Review -->
<reference name="customer_account_navigation">
<action method="addLink" translate="label" module="review"><name>reviews</name><path>review/customer</path><label>My Product Reviews</label></action>
</reference>
</customer_account>
To remove this link, just comment out or remove the <action method=...>
tag and the menu item will disappear. If you want to find all menu items at once, use your favorite file search and find any instances of name="customer_account_navigation"
, which is the handle that Magento uses for that navigation block.
You Can Get UIColor From String Code Like
circularSpinner.fillColor = [self getUIColorObjectFromHexString:@"27b8c8" alpha:9];
//Function For Hex Color Use
- (unsigned int)intFromHexString:(NSString *)hexStr
{
unsigned int hexInt = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
// Scan hex value
[scanner scanHexInt:&hexInt];
return hexInt;
}
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create color object, specifying alpha as well
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
blue:((CGFloat) (hexint & 0xFF))/255
alpha:alpha];
return color;
}
/Function For Hex Color Use
- (unsigned int)intFromHexString:(NSString *)hexStr
{
unsigned int hexInt = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
// Scan hex value
[scanner scanHexInt:&hexInt];
return hexInt;
}
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create color object, specifying alpha as well
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
blue:((CGFloat) (hexint & 0xFF))/255
alpha:alpha];
return color;
}
You can tailor how your object is represented as a string by implementing a __toString()
method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;
, or automatic echo $myObject
) you can control what is included and the string format.
If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.
Some code to demonstrate the difference:
class MyObject {
protected $name = 'JJ';
public function __toString() {
return "My name is: {$this->name}\n";
}
}
$obj = new MyObject;
echo $obj;
echo serialize($obj);
Output:
My name is: JJ
O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}
You can call CREATE Function
near the beginning of your script and DROP Function
near the end.
You need to call CLASS in button
<button class="tim" id="rock" onClick="choose(1)">Rock</button>
<style>
.tim{
font-size: 18px;
border: 2px solid #AD235E;
border-radius: 100px;
width: 150px;
height: 150px; background-image: url(images/Sun.jpg);
}
</style>
There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.
The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.
Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.
I think you 're looking for the solution described in this answer Exclude methods from code coverage with Cobertura Keep in mind that if you're using Sonar 3.2 you have specify that your coverage tool is cobertura and not jacoco ( default ), which doesn't support this kind of feature yet
If they are separate class files within the same project, then you do not need to have an 'import' statement. Just use the class straight off. If the files are in separate projects, you need to add a reference to the project first before you can use an 'import' statement on it.
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
Another option is to use datediff
from dateutils
(http://www.fresse.org/dateutils/#datediff):
$ datediff 10:33:56 10:36:10
134s
$ datediff 10:33:56 10:36:10 -f%H:%M:%S
0:2:14
$ datediff 10:33:56 10:36:10 -f%0H:%0M:%0S
00:02:14
You could also use gawk
. mawk
1.3.4 also has strftime
and mktime
but older versions of mawk
and nawk
don't.
$ TZ=UTC0 awk 'BEGIN{print strftime("%T",mktime("1970 1 1 10 36 10")-mktime("1970 1 1 10 33 56"))}'
00:02:14
Or here's another way to do it with GNU date
:
$ date -ud@$(($(date -ud'1970-01-01 10:36:10' +%s)-$(date -ud'1970-01-01 10:33:56' +%s))) +%T
00:02:14
If you are using new version of Kafka e.g. 5.3.3, you can use
kafka-broker-api-versions --bootstrap-server BROKER | grep 9092
You just need to pass one of the brokers
To solve this problem, github recommends Connecting over HTTPS.
Git's documentation discuss how to how to do exactly that using gitcredentials.
Solution 1
Static configuration of usernames for a given authentication context.
https://username:<personal-access-tokens>@repository-url.com
You will find the details in the documentation.
Solution 2
Use credential helpers to cache password (in memory for a short period of time).
git config --global credential.helper cache
Solution 3
Use credential helpers to store password (indefinitely on disk).
git config --global credential.helper 'store --file ~/.my-credentials'
You can find where the credential will be saved (If not set explicitly with --file) in the documentation.
If not set explicitly with --file, there are two files where git-credential-store will search for credentials in order of precedence:
~/.git-credentials
User-specific credentials file. $XDG_CONFIG_HOME/git/credentials Second user-specific credentials file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/credentials will be used. Any
credentials stored in this file will not be used if ~/.git-credentials has a matching credential as well. It is a good idea not to create this file if you sometimes use older versions of Git that do not support it.
P.S.
To address the concern:
your password is going to be stored completely unencrypted ("as is") at ~/.git-credentials.
You can always encrypt the file and decrypt it before using.
To do this task download.js library can be used. Here is an example from library docs:
download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");
Using just jQuery
, vanilla Javascript
, and the table2CSV
library:
export-to-html-table-as-csv-file-using-jquery
Put this code into a script to be loaded in the head
section:
$(document).ready(function () {
$('table').each(function () {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to spreadsheet");
$button.insertAfter($table);
$button.click(function () {
var csv = $table.table2CSV({
delivery: 'value'
});
window.location.href = 'data:text/csv;charset=UTF-8,'
+ encodeURIComponent(csv);
});
});
})
Notes:
Requires jQuery and table2CSV: Add script references to both libraries before the script above.
The table
selector is used as an example, and can be adjusted to suit your needs.
It only works in browsers with full Data URI
support: Firefox, Chrome and Opera, not in IE, which only supports Data URIs
for embedding binary image data into a page.
For full browser compatibility you would have to use a slightly different approach that requires a server side script to echo
the CSV.
I will not get into the details of how HashMap works, but will give an example so we can remember how HashMap works by relating it to reality.
We have Key, Value ,HashCode and bucket.
For sometime, we will relate each of them with the following:
Using Map.get(key) :
Stevie wants to get to his friend's(Josse) house who lives in a villa in a VIP society, let it be JavaLovers Society. Josse's address is his SSN(which is different for everyone). There's an index maintained in which we find out the Society's name based on SSN. This index can be considered to be an algorithm to find out the HashCode.
Using Map.put(key,Value)
This finds a suitable society for this Value by finding the HashCode and then the value is stored.
I hope this helps and this is open for modifications.
Edit filename: core/Common.php, line number: 257
Before
return $_config[0] =& $config;
After
$_config[0] =& $config;
return $_config[0];
Added by NikiC
In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).
This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.
In Python 3, urllib.quote
has been moved to urllib.parse.quote
and it does handle unicode by default.
>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'
I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:
My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
hidesBarsOnTap
on UINavigationController property come out to handle just this with iOS8 SDK
I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object
Here's code to add multiple JSONObjects to JSONArray.
JSONArray Obj = new JSONArray();
try {
for(int i = 0; i < 3; i++) {
// 1st object
JSONObject list1 = new JSONObject();
list1.put("val1",i+1);
list1.put("val2",i+2);
list1.put("val3",i+3);
obj.put(list1);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();
I found one solution for MYSQL its easy to add new column for SrNo or kind of tepropery auto increment column by following this query:
SELECT @ab:=@ab+1 as SrNo, tablename.* FROM tablename, (SELECT @ab:= 0)
AS ab
display:unset sets it back to some initial setting, not to the previous "display" values
i just copied the previous display value (in my case display: flex;) again(after display non), and it overtried the display:none successfuly
(i used display:none for hiding elements for mobile and small screens)
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0
, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes
import matplotlib.pyplot as plt
plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
I got this error, and it was because I had the arguments in the wrong order:
java maui.main.Examples tagging -jar maui-1.0.jar
java -jar maui-1.0.jar maui.main.Examples tagging
what isn't working about it? here's a tested version:
String.prototype.isValidDate = function() {
const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
if (!match || match.length !== 4) {
return false
}
const test = new Date(match[3], match[1] - 1, match[2]);
return (
(test.getMonth() == match[1] - 1) &&
(test.getDate() == match[2]) &&
(test.getFullYear() == match[3])
);
}
var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
This function will turn almost anything into an array:
function arr(x) {
if(x === null || x === undefined) {
return [];
}
if(Array.isArray(x)) {
return x;
}
if(isString(x) || isNumber(x)) {
return [x];
}
if(x[Symbol.iterator] !== undefined || x.length !== undefined) {
return Array.from(x);
}
return [x];
}
function isString(x) {
return Object.prototype.toString.call(x) === "[object String]"
}
function isNumber(x) {
return Object.prototype.toString.call(x) === "[object Number]"
}
It uses some newer browser features so you may want to polyfill this for maximum support.
Examples:
> arr(null);
[]
> arr(undefined)
[]
> arr(3.14)
[ 3.14 ]
> arr(1/0)
[ Infinity ]
> gen = function*() { yield 1; yield 2; yield 3; }
[Function: gen]
> arr(gen())
[ 1, 2, 3 ]
> arr([4,5,6])
[ 4, 5, 6 ]
> arr("foo")
[ 'foo' ]
N.B. strings will be converted into an array with a single element instead of an array of chars. Delete the isString
check if you would prefer it the other way around.
I've used Array.isArray
here because it's the most robust and also simplest.
a=[100,200,300,400,500]
def search(b):
try:
k=a.index(b)
return a[k]
except ValueError:
return 'not found'
print(search(500))
it'll return the object if found else it'll return "not found"
I got this error because there was an extra white space in the code
Instead of
<add key="owin:AutomaticAppStartup" value="false" />
It was
<add key="owin:AutomaticAppStartup " value="false" />
With one group in the pattern, you can only get one exact result in that group. If your capture group gets repeated by the pattern (you used the +
quantifier on the surrounding non-capturing group), only the last value that matches it gets stored.
You have to use your language's regex implementation functions to find all matches of a pattern, then you would have to remove the anchors and the quantifier of the non-capturing group (and you could omit the non-capturing group itself as well).
Alternatively, expand your regex and let the pattern contain one capturing group per group you want to get in the result:
^([A-Z]+),([A-Z]+),([A-Z]+)$
all examples are good....Here is nice visual illustration... source courtesy : DataFlair training of spark
Map : A map is a transformation operation in Apache Spark. It applies to each element of RDD and it returns the result as new RDD. In the Map, operation developer can define his own custom business logic. The same logic will be applied to all the elements of RDD.
Spark RDD map
function takes one element as input process it according to custom code (specified by the developer) and returns one element at a time. Map transforms an RDD of length N into another RDD of length N. The input and output RDDs will typically have the same number of records.
Example of map
using scala :
val x = spark.sparkContext.parallelize(List("spark", "map", "example", "sample", "example"), 3)
val y = x.map(x => (x, 1))
y.collect
// res0: Array[(String, Int)] =
// Array((spark,1), (map,1), (example,1), (sample,1), (example,1))
// rdd y can be re writen with shorter syntax in scala as
val y = x.map((_, 1))
y.collect
// res1: Array[(String, Int)] =
// Array((spark,1), (map,1), (example,1), (sample,1), (example,1))
// Another example of making tuple with string and it's length
val y = x.map(x => (x, x.length))
y.collect
// res3: Array[(String, Int)] =
// Array((spark,5), (map,3), (example,7), (sample,6), (example,7))
FlatMap :
A flatMap
is a transformation operation. It applies to each element of RDD and it returns the result as new RDD
. It is similar to Map, but FlatMap allows returning 0, 1 or more elements from map function. In the FlatMap operation, a developer can define his own custom business logic. The same logic will be applied to all the elements of the RDD.
What does "flatten the results" mean?
A FlatMap function takes one element as input process it according to custom code (specified by the developer) and returns 0 or more element at a time. flatMap
() transforms an RDD of length N into another RDD of length M.
Example of flatMap
using scala :
val x = spark.sparkContext.parallelize(List("spark flatmap example", "sample example"), 2)
// map operation will return Array of Arrays in following case : check type of res0
val y = x.map(x => x.split(" ")) // split(" ") returns an array of words
y.collect
// res0: Array[Array[String]] =
// Array(Array(spark, flatmap, example), Array(sample, example))
// flatMap operation will return Array of words in following case : Check type of res1
val y = x.flatMap(x => x.split(" "))
y.collect
//res1: Array[String] =
// Array(spark, flatmap, example, sample, example)
// RDD y can be re written with shorter syntax in scala as
val y = x.flatMap(_.split(" "))
y.collect
//res2: Array[String] =
// Array(spark, flatmap, example, sample, example)
Also DevExpress have Charts (see DevExpress.Com).
By using below method you can convert java.math.BigDecimal to String.
BigDecimal bigDecimal = new BigDecimal("10.0001");
String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
System.out.println("bigDecimal value in String: "+bigDecimalString);
Output:
bigDecimal value in String: 10.0001
I was finally able to figure out the issue. I had to change some settings in mysql configuration my.ini This article helped a lot http://mathiasbynens.be/notes/mysql-utf8mb4#character-sets
First i changed the character set in my.ini to utf8mb4 Next i ran the following commands in mysql client
SET NAMES utf8mb4;
ALTER DATABASE dreams_twitter CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
Use the following command to check that the changes are made
SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
You don't need regex to split a string on whitespace:
In [1]: text = '''WYATT - Ranked # 855 with 0.006 %
...: XAVIER - Ranked # 587 with 0.013 %
...: YONG - Ranked # 921 with 0.006 %
...: YOUNG - Ranked # 807 with 0.007 %'''
In [2]: print '\n'.join(line.split()[0] for line in text.split('\n'))
WYATT
XAVIER
YONG
YOUNG
I would thoroughly recommend making use of the Underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.
For instance:
_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...
if you have any problem with the library you can use Microsoft.Data.Sqlite;
public static DataTable GetData(string connectionString, string query)
{
DataTable dt = new DataTable();
Microsoft.Data.Sqlite.SqliteConnection connection;
Microsoft.Data.Sqlite.SqliteCommand command;
connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
try
{
connection.Open();
command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
dt.Load(command.ExecuteReader());
connection.Close();
}
catch
{
}
return dt;
}
you can add NuGet Package Microsoft.Data.Sqlite
In PHP 7.0.1, I was able to define this:
public static $kIdsByActions = array(
MyClass1::kAction => 0,
MyClass2::kAction => 1
);
And then use it like this:
MyClass::$kIdsByActions[$this->mAction];
As a best practice, especially if you have multiple date pickers, you should not hardcode the element's scope variable name.
Instead, you should get the clicked input's ng-model
and update its corresponding scope variable inside the onSelect
method.
app.directive('jqdatepicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
$(element).datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(date) {
var ngModelName = this.attributes['ng-model'].value;
// if value for the specified ngModel is a property of
// another object on the scope
if (ngModelName.indexOf(".") != -1) {
var objAttributes = ngModelName.split(".");
var lastAttribute = objAttributes.pop();
var partialObjString = objAttributes.join(".");
var partialObj = eval("scope." + partialObjString);
partialObj[lastAttribute] = date;
}
// if value for the specified ngModel is directly on the scope
else {
scope[ngModelName] = date;
}
scope.$apply();
}
});
}
};
});
EDIT
To address the issue that @Romain raised up (Nested Elements), I have modified my answer
If the system Python is borked (i.e. the OS packages split distutils in a python-devel package) and you can’t ask a sysadmin to install the missing piece, then you’ll have to install your own Python. It requires some header files and a compiler toolchain. If you can’t have those, try compiling a Python on an identical computer and just copying it.
Use the propfull
keyword.
It will generate a property and a variable.
Type keyword propfull
in the editor, followed by two TABs. It will generate code like:
private data_type var_name;
public data_type var_name1{ get;set;}
Video demonstrating the use of snippet 'propfull' (among other things), at 4 min 11 secs.
I'm starting to learn about this myself, being very new to android development and I found this video very helpful.
https://www.youtube.com/watch?v=qcotbMLjlA4
It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.
Code from the video for JSONArray to JSONObject:
JSONArray queryArray = quoteJSONObject.names();
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < queryArray.length(); i++){
list.add(queryArray.getString(i));
}
for(String item : list){
Log.v("JSON ARRAY ITEMS ", item);
}
2021 Update
Bootstrap 5 also has a flexbox Navbar, and introduces new RTL support. For this reason the concept of "left" and "right" has been replaced with "start" and "end". Therefore the margin utilities changed for Bootstrap 5 beta:
ml-auto
=> ms-auto
mr-auto
=> me-auto
Now that Bootstrap 4 has flexbox, Navbar alignment is much easier. Here are updated examples for left, right and center in the Bootstrap 4 Navbar, and many other alignment scenarios demonstrated here.
The flexbox, auto-margins, and ordering utility classes can be used to align Navbar content as needed. There are many things to consider including the order and alignment of Navbar items (brand, links, toggler) on both large screens and the mobile/collapsed views. Don't use the grid classes (row,col) for the Navbar.
Here are various examples...
Left, center(brand) and right links:
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<div class="navbar-collapse collapse w-100 order-1 order-md-0 dual-collapse2">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Left</a>
</li>
<li class="nav-item">
<a class="nav-link" href="//codeply.com">Codeply</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
<div class="mx-auto order-0">
<a class="navbar-brand mx-auto" href="#">Navbar 2</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Right</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
http://codeply.com/go/qhaBrcWp3v
Another BS4 Navbar option with center links and overlay logo image:
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="navbar-collapse collapse w-100 dual-collapse2 order-1 order-md-0">
<ul class="navbar-nav ml-auto text-center">
<li class="nav-item active">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
<div class="mx-auto my-2 order-0 order-md-1 position-relative">
<a class="mx-auto" href="#">
<img src="//placehold.it/120/ccff00" class="rounded-circle">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-2">
<ul class="navbar-nav mr-auto text-center">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
Or, these other Bootstrap 4 alignment scenarios:
brand left, dead center links, (empty right)
brand and links center, icons left and right
More Bootstrap 4 examples:
toggler left on mobile, brand right
center brand and links on mobile
right align links on desktop, center links on mobile
left links & toggler, center brand, search right
Also see: Bootstrap 4 align navbar items to the right
Bootstrap 4 navbar right align with button that doesn't collapse on mobile
Center an element in Bootstrap 4 Navbar
Option 1 - Brand center, with left/right nav links:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<a class="navbar-brand" href="#">Brand</a>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-left">
<li><a href="#">Left</a></li>
<li><a href="#about">Left</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#about">Right</a></li>
<li><a href="#contact">Right</a></li>
</ul>
</div>
</nav>
.navbar-brand
{
position: absolute;
width: 100%;
left: 0;
text-align: center;
margin:0 auto;
}
.navbar-toggle {
z-index:3;
}
http://bootply.com/98314 (3.x)
Option 2 - Left, center and right nav links:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#">Left</a></li>
</ul>
<ul class="nav navbar-nav navbar-center">
<li><a href="#">Center</a></li>
<li><a href="#">Center</a></li>
<li><a href="#">Center</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Right</a></li>
</ul>
</div>
</nav>
@media (min-width: 768px) {
.navbar-nav.navbar-center {
position: absolute;
left: 50%;
transform: translatex(-50%);
}
}
Option 3 - Center both brand and links
.navbar .navbar-header,
.navbar-collapse {
float:none;
display:inline-block;
vertical-align: top;
}
@media (max-width: 768px) {
.navbar-collapse {
display: block;
}
}
http://codeply.com/go/1lrdvNH9GI
More examples:
Left brand, center links
Left toggler, center brand
For 3.x also see nav-justified: Bootstrap center navbar
Center Navbar in Bootstrap
Bootstrap 4 align navbar items to the right
If you are interested in understand performance, the best answer is to use a profiler.
Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.
This approach using git-remote
worked well for me for HTTPS remotes:
$ git remote -v | grep "(fetch)" | sed 's/.*\/\([^ ]*\)\/.*/\1/'
| | | |
| | | +---------------+
| | | Extract capture |
| +--------------------+-----+
|Repository name capture|
+-----------------------+
Example
I like the simplicity of tabulary
package:
\usepackage{tabulary}
...
\begin{tabulary}{\linewidth}{LCL}
\hline
Short sentences & \# & Long sentences \\
\hline
This is short. & 173 & This is much loooooooonger, because there are many more words. \\
This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\
\hline
\end{tabulary}
In the example, you arrange the whole width of the table with respect to \textwidth. E.g 0.4 of it. Then the rest is automatically done by the package.
Most of the example is taken from http://en.wikibooks.org/wiki/LaTeX/Tables .
use global variable $post
<?php
global $post;
$post_slug=$post->post_name;
?>
cat 'filename' | grep '[^ ]' | wc -l
should do the trick just fine
Judging from your example, shouldn't it be {% url myproject.login.views.login_view %}
and end of story? (replace myproject
with your actual project name)
I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.
The accepted answer gives this example:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
But that doesn't really illustrate it well. Even without the $
, we would still have two different variable names here, email
and email_field
. That's plenty good right there. Why would we need to throw a $
into one of the names when we already have two different names?
Actually, I wouldn't have used email_field
here for two reasons: names_with_underscores
are not idiomatic JavaScript, and field
doesn't really make sense for a DOM element. But I did follow the same idea.
I tried a few different things, among them something very similar to the example:
var email = $("#email"), emailElement = $("#email")[0];
// Now email is a jQuery object and emailElement is the first/only DOM element in it
(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of id
selectors, so in those cases there was a 1:1 correspondence.)
I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var emailJQ = $(email);
// Now email is the DOM element and emailJQ is a jQuery object for it
}
Well that's a little confusing! In one of my bits of code, email
is the jQuery object and emailElement
is the DOM element, but in the other, email
is the DOM element and emailJQ
is the jQuery object.
There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides email
, emailElement
, and emailJQ
, I kept trying other variations too.
Then I noticed a common pattern:
var email = $("#email");
var emailJQ = $(email);
Since JavaScript treats $
as simply another letter for names, and since I always got a jQuery object back from a $(whatever)
call, the pattern finally dawned on me. I could take a $(...)
call and just remove some characters, and it would come up with a pretty nice name:
$
("#email")$
(email)
Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:
$email
That's when I realized I didn't need to make up a convention like emailElement
or emailJQ
. There was already a nice convention staring at me: take some characters out of a $(whatever)
call and it turns into $whatever
.
var $email = $("#email"), email = $email[0];
// $email is the jQuery object and email is the DOM object
and:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var $email = $(email);
// $email is the jQuery object and email is the DOM object
// Same names as in the code above. Yay!
}
So I didn't have to make up two different names all the time but could just use the same name with or without a $
prefix. And the $
prefix was a nice reminder that I was dealing with a jQuery object:
$('#email').click( ... );
or:
var $email = $('#email');
// Maybe do some other stuff with $email here
$email.click( ... );
If you're working with other developers, such as PHP or JSP (and i'm guessing rails) - you're going to have a much easier time converting or collaborating on pages because you wont have all those 'nasty' ASP.NET events and controls everywhere.
I get this problem everytime i save a file that gets dynamically compiled (ascx, aspx etc). I wait about 8-10 seconds then it goes away. It's hellishly annoying.
I thought it was perhaps an IIS Express problem so I tried in the inbuilt dev server and am still receiving it after saving a file. I'm running an MVC app, i'm also using T4MVC, maybe that is a factor...
//I think this way we could go :
int my_atoi(const char* snum)
{
int nInt(0);
int index(0);
while(snum[index])
{
if(!nInt)
nInt= ( (int) snum[index]) - 48;
else
{
nInt = (nInt *= 10) + ((int) snum[index] - 48);
}
index++;
}
return(nInt);
}
int main()
{
printf("Returned number is: %d\n", my_atoi("676987"));
return 0;
}
The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.
public class SOAPClientSAAJ {
public static void main(String args[]) throws Exception {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
SOAPPart soapPart=soapResponse.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope=soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();
@SuppressWarnings("unchecked")
Iterator<Node> itr=soapBody.getChildElements();
while (itr.hasNext()) {
Node node=(Node)itr.next();
if (node.getNodeType()==Node.ELEMENT_NODE) {
System.out.println("reading Node.ELEMENT_NODE");
Element ele=(Element)node;
System.out.println("Body childs : "+ele.getLocalName());
switch (ele.getNodeName()) {
case "VerifyEmailResponse":
NodeList statusNodeList = ele.getChildNodes();
for(int i=0;i<statusNodeList.getLength();i++){
Element emailResult = (Element) statusNodeList.item(i);
System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
switch (emailResult.getNodeName()) {
case "VerifyEmailResult":
NodeList emailResultList = emailResult.getChildNodes();
for(int j=0;j<emailResultList.getLength();j++){
Element emailResponse = (Element) emailResultList.item(j);
System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
switch (emailResponse.getNodeName()) {
case "ResponseText":
System.out.println(emailResponse.getTextContent());
break;
case "ResponseCode":
System.out.println(emailResponse.getTextContent());
break;
case "LastMailServer":
System.out.println(emailResponse.getTextContent());
break;
case "GoodEmail":
System.out.println(emailResponse.getTextContent());
default:
break;
}
}
break;
default:
break;
}
}
break;
default:
break;
}
} else if (node.getNodeType()==Node.TEXT_NODE) {
System.out.println("reading Node.TEXT_NODE");
//do nothing here most likely, as the response nearly never has mixed content type
//this is just for your reference
}
}
// print SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
soapConnection.close();
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ws.cdyne.com/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<example:VerifyEmail>
<example:email>[email protected]</example:email>
<example:LicenseKey>123</example:LicenseKey>
</example:VerifyEmail>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
soapBodyElem1.addTextNode("[email protected]");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
soapBodyElem2.addTextNode("123");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
soapMessage.saveChanges();
/* Print the request message */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("");
System.out.println("------");
return soapMessage;
}
}
Use a static method when you want to be able to access the method without an instance of the class.
Here is OpenSSL example of calculating sha-1 digest using BIO:
#include <openssl/bio.h>
#include <openssl/evp.h>
std::string sha1(const std::string &input)
{
BIO * p_bio_md = nullptr;
BIO * p_bio_mem = nullptr;
try
{
// make chain: p_bio_md <-> p_bio_mem
p_bio_md = BIO_new(BIO_f_md());
if (!p_bio_md) throw std::bad_alloc();
BIO_set_md(p_bio_md, EVP_sha1());
p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
if (!p_bio_mem) throw std::bad_alloc();
BIO_push(p_bio_md, p_bio_mem);
// read through p_bio_md
// read sequence: buf <<-- p_bio_md <<-- p_bio_mem
std::vector<char> buf(input.size());
for (;;)
{
auto nread = BIO_read(p_bio_md, buf.data(), buf.size());
if (nread < 0) { throw std::runtime_error("BIO_read failed"); }
if (nread == 0) { break; } // eof
}
// get result
char md_buf[EVP_MAX_MD_SIZE];
auto md_len = BIO_gets(p_bio_md, md_buf, sizeof(md_buf));
if (md_len <= 0) { throw std::runtime_error("BIO_gets failed"); }
std::string result(md_buf, md_len);
// clean
BIO_free_all(p_bio_md);
return result;
}
catch (...)
{
if (p_bio_md) { BIO_free_all(p_bio_md); }
throw;
}
}
Though it's longer than just calling SHA1
function from OpenSSL, but it's more universal and can be reworked for using with file streams (thus processing data of any length).
I have created a Generic Timer Widget which can be used to display any kind of timer and its flexible as well.
This Widget takes following properties
hh mm ss
string like 01 hours: 20 minutes: 45 seconds
you can provide a default formatter ( formatHHMMSS
) in case you don't want to supply it from every place.
// provide implementation for this - formatHHMMSS(duration.inSeconds);
or use below one which I have provided.
import 'package:flutter/material.dart';
class CountDownTimer extends StatefulWidget {
const CountDownTimer({
Key key,
int secondsRemaining,
this.countDownTimerStyle,
this.whenTimeExpires,
this.countDownFormatter,
}) : secondsRemaining = secondsRemaining,
super(key: key);
final int secondsRemaining;
final Function whenTimeExpires;
final Function countDownFormatter;
final TextStyle countDownTimerStyle;
State createState() => new _CountDownTimerState();
}
class _CountDownTimerState extends State<CountDownTimer>
with TickerProviderStateMixin {
AnimationController _controller;
Duration duration;
String get timerDisplayString {
Duration duration = _controller.duration * _controller.value;
return widget.countDownFormatter != null
? widget.countDownFormatter(duration.inSeconds)
: formatHHMMSS(duration.inSeconds);
// In case user doesn't provide formatter use the default one
// for that create a method which will be called formatHHMMSS or whatever you like
}
@override
void initState() {
super.initState();
duration = new Duration(seconds: widget.secondsRemaining);
_controller = new AnimationController(
vsync: this,
duration: duration,
);
_controller.reverse(from: widget.secondsRemaining.toDouble());
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed || status == AnimationStatus.dismissed) {
widget.whenTimeExpires();
}
});
}
@override
void didUpdateWidget(CountDownTimer oldWidget) {
if (widget.secondsRemaining != oldWidget.secondsRemaining) {
setState(() {
duration = new Duration(seconds: widget.secondsRemaining);
_controller.dispose();
_controller = new AnimationController(
vsync: this,
duration: duration,
);
_controller.reverse(from: widget.secondsRemaining.toDouble());
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
widget.whenTimeExpires();
} else if (status == AnimationStatus.dismissed) {
print("Animation Complete");
}
});
});
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Center(
child: AnimatedBuilder(
animation: _controller,
builder: (_, Widget child) {
return Text(
timerDisplayString,
style: widget.countDownTimerStyle,
);
}));
}
}
Usage:
Container(
width: 60.0,
padding: EdgeInsets.only(top: 3.0, right: 4.0),
child: CountDownTimer(
secondsRemaining: 30,
whenTimeExpires: () {
setState(() {
hasTimerStopped = true;
});
},
countDownStyle: TextStyle(
color: Color(0XFFf5a623),
fontSize: 17.0,
height: 1.2),
),
)
example for formatHHMMSS:
String formatHHMMSS(int seconds) {
int hours = (seconds / 3600).truncate();
seconds = (seconds % 3600).truncate();
int minutes = (seconds / 60).truncate();
String hoursStr = (hours).toString().padLeft(2, '0');
String minutesStr = (minutes).toString().padLeft(2, '0');
String secondsStr = (seconds % 60).toString().padLeft(2, '0');
if (hours == 0) {
return "$minutesStr:$secondsStr";
}
return "$hoursStr:$minutesStr:$secondsStr";
}
I believe the most simple and efficient way to loop through DataFrames is using numpy and numba. In that case, looping can be approximately as fast as vectorized operations in many cases. If numba is not an option, plain numpy is likely to be the next best option. As has been noted many times, your default should be vectorization, but this answer merely considers efficient looping, given the decision to loop, for whatever reason.
For a test case, let's use the example from @DSM's answer of calculating a percentage change. This is a very simple situation and as a practical matter you would not write a loop to calculate it, but as such it provides a reasonable baseline for timing vectorized approaches vs loops.
Let's set up the 4 approaches with a small DataFrame, and we'll time them on a larger dataset below.
import pandas as pd
import numpy as np
import numba as nb
df = pd.DataFrame( { 'close':[100,105,95,105] } )
pandas_vectorized = df.close.pct_change()[1:]
x = df.close.to_numpy()
numpy_vectorized = ( x[1:] - x[:-1] ) / x[:-1]
def test_numpy(x):
pct_chng = np.zeros(len(x))
for i in range(1,len(x)):
pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
return pct_chng
numpy_loop = test_numpy(df.close.to_numpy())[1:]
@nb.jit(nopython=True)
def test_numba(x):
pct_chng = np.zeros(len(x))
for i in range(1,len(x)):
pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
return pct_chng
numba_loop = test_numba(df.close.to_numpy())[1:]
And here are the timings on a DataFrame with 100,000 rows (timings performed with Jupyter's %timeit
function, collapsed to a summary table for readability):
pandas/vectorized 1,130 micro-seconds
numpy/vectorized 382 micro-seconds
numpy/looped 72,800 micro-seconds
numba/looped 455 micro-seconds
Summary: for simple cases, like this one, you would go with (vectorized) pandas for simplicity and readability, and (vectorized) numpy for speed. If you really need to use a loop, do it in numpy. If numba is available, combine it with numpy for additional speed. In this case, numpy + numba is almost as fast as vectorized numpy code.
Other details:
This worked for my GIT version 1.8.4:
import datetime
from calendar import monthrange
def date_dif(from_date,to_date): # ????????? ??????? ????? ??? ????
dd=(to_date-from_date).days
if dd>=0:
fromDM=from_date.year*12+from_date.month-1
toDM=to_date.year*12+to_date.month-1
mlen=monthrange(int((toDM)/12),(toDM)%12+1)[1]
d=to_date.day-from_date.day
dm=toDM-fromDM
m=(dm-int(d<0))%12
y=int((dm-int(d<0))/12)
d+=int(d<0)*mlen
# diference in Y,M,D, diference months,diference days, days in to_date month
return[y,m,d,dm,dd,mlen]
else:
return[0,0,0,0,dd,0]
I had the same issue it was due to that I had the bootstrap class "hidden-lg" on the table which caused it to stupidly become display: block !important;
I wonder how Bootstrap never considered to just instead do this:
@media (min-width: 1200px) {
.hidden-lg {
display: none;
}
}
And then just leave the element whatever display it had before for other screensizes.. Perhaps it is too advanced for them to figure out..
Anyway so:
table {
display: table; /* check so these really applies */
width: 100%;
}
should work
Well done Sebastian J above.
I had the "buffer problem" with a few lines of test code I had, and added the encoding information and it solved it, see below.
software
// process.stdin.setEncoding('utf8');
process.stdin.on('data', (data) => {
console.log(typeof(data), data);
});
input
hello world
output
object <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a>
software
process.stdin.setEncoding('utf8'); // <- Activate!
process.stdin.on('data', (data) => {
console.log(typeof(data), data);
});
input
hello world
output
string hello world
In Log4j2, the "extras" lib is not mandatory any more. Also the configuration format has changed.
An example is provided in the Apache documentation
property.filename = /foo/bar/test.log
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = /foo/bar/rolling/test1-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 2
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5
logger.rolling.name = com.example.my.class
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile
array.length
It is actually a final member of the array, not a method.
Add a second });
.
When properly indented, your code reads
$(function() {
$("#mewlyDiagnosed").hover(function() {
$("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
}, function() {
$("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
});
MISSING!
You never closed the outer $(function() {
.
A couple of more options :
With asplit
asplit(xy.df, 1)
#[[1]]
# x y
#0.1137 0.6936
#[[2]]
# x y
#0.6223 0.5450
#[[3]]
# x y
#0.6093 0.2827
#....
With split
and row
split(xy.df, row(xy.df)[, 1])
#$`1`
# x y
#1 0.1137 0.6936
#$`2`
# x y
#2 0.6223 0.545
#$`3`
# x y
#3 0.6093 0.2827
#....
data
set.seed(1234)
xy.df <- data.frame(x = runif(10), y = runif(10))
I had a similar issue and wrapped the component in "div" instead of "p" and the error went away.
# dump into file
pg_dump myDB > /tmp/myDB.sql
# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'
# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql
# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";'
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'
# see the result
psql myDB -c "SHOW LC_COLLATE"
The only way to do it is by checking the value of the isCancelled() method and stopping playback when it returns true.
My locale settings seemed incomplete, so I had too look beyond this SO answer and found:
http://docs.python.org/library/decimal.html#recipes
OS-independent
Just wanted to share here.
Resource is a RESTful subset of Endpoint.
An endpoint by itself is the location where a service can be accessed:
https://www.google.com # Serves HTML
8.8.8.8 # Serves DNS
/services/service.asmx # Serves an ASP.NET Web Service
A resource refers to one or more nouns being served, represented in namespaced fashion, because it is easy for humans to comprehend:
/api/users/johnny # Look up johnny from a users collection.
/v2/books/1234 # Get book with ID 1234 in API v2 schema.
All of the above could be considered service endpoints, but only the bottom group would be considered resources, RESTfully speaking. The top group is not expressive regarding the content it provides.
A REST request is like a sentence composed of nouns (resources) and verbs (HTTP methods):
GET
(method) the user named johnny
(resource).DELETE
(method) the book with id 1234
(resource).Endpoint typically refers to a service, but resource could mean a lot of things. Here are some examples of resource that are dependent on the context they're used in.
Something that can be used to help you:
The library was a valuable resource, and he frequently made use of it.
Resources are natural substances such as water and wood which are valuable in supporting life:
[ pl ] The earth has limited resources, and if we don’t recycle them we use them up.
Resources are also things of value such as money or possessions that you can use when you need them:
[ pl ] The government doesn’t have the resources to hire the number of teachers needed.
The term resource by definition has a lot of nuance. It all depends on the context its used in.
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
@FunctionalInterface
annotation is useful for compilation time checking of your code. You cannot have more than one method besides static
, default
and abstract methods that override methods in Object
in your @FunctionalInterface
or any other interface used as a functional interface.
But you can use lambdas without this annotation as well as you can override methods without @Override
annotation.
From docs
a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere
This can be used in lambda expression:
public interface Foo {
public void doSomething();
}
This cannot be used in lambda expression:
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
But this will give compilation error:
@FunctionalInterface
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
Invalid '@FunctionalInterface' annotation; Foo is not a functional interface
If the tables are already created using the scripts, then there is another way to copy the data is by using BCP command to copy all the data from your source server to your destination server
To export the table data into a text file on source server:
bcp <database name>.<schema name>.<table name> OUT C:\FILE.TXT -c -t -T -S <server_name[ \instance_name]> -U <username> -P <Password>
To import the table data from a text file on target server:
bcp <database name>.<schema name>.<table name> IN C:\FILE.TXT -c -t -T -S <server_name[ \instance_name]> -U <username> -P <Password>
declare @sql1 nvarchar(max)
SELECT @sql1 =
STUFF(
(
select ' drop table dbo.[' + name + ']'
FROM sys.sysobjects AS sobjects
WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
for xml path('')
),
1, 1, '')
execute sp_executesql @sql1
For me, on Yosemite
$ brew install mcrypt php56-mcrypt
restart computer
did the trick.
Select date1 - (date2 - 1) * 24 * 60 *60 * 1000 from Table;
All you need to do is edit the iframe code that facebook gives you and change the width to 47 (you need to change it in 2 places). Seems to work perfectly for me so far.
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
How about
SELECT id, COUNT(IF status=42 THEN 1 ENDIF) AS cnt
FROM table
GROUP BY table
Shorter than CASE
:)
Works because COUNT()
doesn't count null values, and IF
/CASE
return null when condition is not met and there is no ELSE
.
I think it's better than using SUM()
.
You can add escaped double quotes like this: String name = "\"john\"";
I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
most people implement that using
$.getJSON(url, datatosend, function(data){
//do something with the data
});
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?"
and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.
You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object (found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.
this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...
=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))
It seems that you can check the tabIndex
property of an element to determine if it is focusable. An element that is not focusable has a tabindex
of "-1".
Then you just need to know the rules for tab stops:
tabIndex="1"
has the highest priorty.tabIndex="2"
has the next highest priority.tabIndex="3"
is next, and so on.tabIndex="0"
(or tabbable by default) has the lowest priority.tabIndex="-1"
(or not tabbable by default) does not act as a tab stop.Here is an example of how to build the list of tab stops, in sequence, using pure Javascript:
function getTabStops(o, a, el) {
// Check if this element is a tab stop
if (el.tabIndex > 0) {
if (o[el.tabIndex]) {
o[el.tabIndex].push(el);
} else {
o[el.tabIndex] = [el];
}
} else if (el.tabIndex === 0) {
// Tab index "0" comes last so we accumulate it seperately
a.push(el);
}
// Check if children are tab stops
for (var i = 0, l = el.children.length; i < l; i++) {
getTabStops(o, a, el.children[i]);
}
}
var o = [],
a = [],
stops = [],
active = document.activeElement;
getTabStops(o, a, document.body);
// Use simple loops for maximum browser support
for (var i = 0, l = o.length; i < l; i++) {
if (o[i]) {
for (var j = 0, m = o[i].length; j < m; j++) {
stops.push(o[i][j]);
}
}
}
for (var i = 0, l = a.length; i < l; i++) {
stops.push(a[i]);
}
We first walk the DOM, collecting up all tab stops in sequence with their index. We then assemble the final list. Notice that we add the items with tabIndex="0"
at the very end of the list, after the items with a tabIndex
of 1, 2, 3, etc.
For a fully working example, where you can tab around using the "enter" key, check out this fiddle.
In layman's language, it is like you are making a cake and you will need 5-10 ingredients from fridge. You have two options, get all ingredients from fridge and put it on your kitchen platform, or bring the item you want when you need.
Similarly, in eager loading, you fetch all information about bean and its related classes (not child or is-a relation but has a relationship, i.e. cake has flour, has milk, has cream etc), and in case of lazy loading, first you bring only its identifier and values that are coming from same table (necessary ingredients that first you will need in your bowl in case of cake). All information that is coming from other tables will be fetched as and when required/used.
A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:
fd = codecs.open(tempfilename, 'wb', 'utf-8')
for c in whatever :
fd.write( json.dumps(c) [1:-1] ) # json dumps writes ["a",..]
fd.write('\n')
fd.close()
Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*
tl;dr ~
flips the bits. As a result the sign changes. ~2
is a negative number (0b..101
). To output a negative number ruby
prints -
, then two's complement of ~2
: -(~~2 + 1) == -(2 + 1) == 3
. Positive numbers are output as is.
There's an internal value, and its string representation. For positive integers, they basically coincide:
irb(main):001:0> '%i' % 2
=> "2"
irb(main):002:0> 2
=> 2
The latter being equivalent to:
irb(main):003:0> 2.to_s
"2"
~
flips the bits of the internal value. 2
is 0b010
. ~2
is 0b..101
. Two dots (..
) represent an infinite number of 1
's. Since the most significant bit (MSB) of the result is 1
, the result is a negative number ((~2).negative? == true
). To output a negative number ruby
prints -
, then two's complement of the internal value. Two's complement is calculated by flipping the bits, then adding 1
. Two's complement of 0b..101
is 3
. As such:
irb(main):005:0> '%b' % 2
=> "10"
irb(main):006:0> '%b' % ~2
=> "..101"
irb(main):007:0> ~2
=> -3
To sum it up, it flips the bits, which changes the sign. To output a negative number it prints -
, then ~~2 + 1
(~~2 == 2
).
The reason why ruby
outputs negative numbers like so, is because it treats the stored value as a two's complement of the absolute value. In other words, what's stored is 0b..101
. It's a negative number, and as such it's a two's complement of some value x
. To find x
, it does two's complement of 0b..101
. Which is two's complement of two's complement of x
. Which is x
(e.g ~(~2 + 1) + 1 == 2
).
In case you apply ~
to a negative number, it just flips the bits (which nevertheless changes the sign):
irb(main):008:0> '%b' % -3
=> "..101"
irb(main):009:0> '%b' % ~-3
=> "10"
irb(main):010:0> ~-3
=> 2
What is more confusing is that ~0xffffff00 != 0xff
(or any other value with MSB equal to 1
). Let's simplify it a bit: ~0xf0 != 0x0f
. That's because it treats 0xf0
as a positive number. Which actually makes sense. So, ~0xf0 == 0x..f0f
. The result is a negative number. Two's complement of 0x..f0f
is 0xf1
. So:
irb(main):011:0> '%x' % ~0xf0
=> "..f0f"
irb(main):012:0> (~0xf0).to_s(16)
=> "-f1"
In case you're not going to apply bitwise operators to the result, you can consider ~
as a -x - 1
operator:
irb(main):018:0> -2 - 1
=> -3
irb(main):019:0> --3 - 1
=> 2
But that is arguably of not much use.
An example Let's say you're given a 8-bit (for simplicity) netmask, and you want to calculate the number of 0
's. You can calculate them by flipping the bits and calling bit_length
(0x0f.bit_length == 4
). But ~0xf0 == 0x..f0f
, so we've got to cut off the unneeded bits:
irb(main):014:0> '%x' % (~0xf0 & 0xff)
=> "f"
irb(main):015:0> (~0xf0 & 0xff).bit_length
=> 4
Or you can use the XOR operator (^
):
irb(main):016:0> i = 0xf0
irb(main):017:0> '%x' % i ^ ((1 << i.bit_length) - 1)
=> "f"
just put #login-box
before <h2>Welcome</h2>
will be ok.
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
here is jsfiddle http://jsfiddle.net/SyjjW/4/
The most direct way to get a list of columns of certain dtype e.g. 'object':
df.select_dtypes(include='object').columns
For example:
>>df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>df.dtypes
A int64
B float64
C object
D object
E int64
dtype: object
To get all 'object' dtype columns:
>>df.select_dtypes(include='object').columns
Index(['C', 'D'], dtype='object')
For just the list:
>>list(df.select_dtypes(include='object').columns)
['C', 'D']
If you want a fixed size website this should be fairly simple:
// Override container sizes_x000D_
@container-sm: 700px;_x000D_
@container-md: 700px;_x000D_
@container-lg: 700px;_x000D_
_x000D_
// Fixate media queries to tablet view only (lower viewports set to 0px, desired one to 1px, and the higher to ~9999px)_x000D_
_x000D_
@screen-xs-min: 0px;_x000D_
@screen-sm-min: 1px;_x000D_
@screen-md-min: 9999px;_x000D_
@screen-lg-min: 9999px;_x000D_
_x000D_
// Disable responsive features such as navbar-collapse_x000D_
@grid-float-breakpoint: 9999px;
_x000D_
Unless you are using .container-fluid, then also add:
.container-fluid {
width: 700px;
}
body {
width: 700px + @general-min-width;
}
You have most of the code…
CURLOPT_HTTPHEADER
for curl_setopt()
takes an array with each header as an element. You have one element with multiple headers.
You also need to add the Authorization header to your $header
array.
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';
Add this class
css
to your style sheet
.border_gradient {
border: 8px solid #000;
-moz-border-bottom-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-top-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-left-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-right-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
padding: 5px 5px 5px 15px;
width: 300px;
}
set width
to the width
of your image. and use this html
for image
<div class="border_gradient">
<img src="image.png" />
</div>
though it may not give the same exact border, it will some gradient looks on the border.
source: CSS3 Borders
Use mvn -N versions:update-child-modules
to update child pom`s version
https://www.mojohaus.org/versions-maven-plugin/examples/update-child-modules.html
For Linux Users:
The solution: In terminal: sudo /etc/init.d/apache2 stop
Edit: If you still get this kind of error at next computer start then you probably have apache2 process starting at computer startup.
To prevent apache2 starting automatically at startup: cd /etc/init.d/ sudo update-rc.d -f apache2 remove
Reboot your computer and now hopefully you can turn on Apache from the XAMPP Control Panel!
According to the switch statement documentation if there is an unambiguous way to implicitly convert the the object to an integral type, then it will be allowed. I think you are expecting a behavior where for each case statement it would be replaced with if (t == typeof(int))
, but that would open a whole can of worms when you get to overload that operator. The behavior would change when implementation details for the switch statement changed if you wrote your == override incorrectly. By reducing the comparisons to integral types and string and those things that can be reduced to integral types (and are intended to) they avoid potential issues.
Assume UTF8 encoding in file - if not, just leave out the "UTF8" argument & will use the default charset for the underlying operating system in each case.
Quick way in JSE 6 - Simple & no 3rd party library!
import java.io.File;
public class FooTest {
@Test public void readXMLToString() throws Exception {
java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
//Z means: "The end of the input but for the final terminator, if any"
String xml = new java.util.Scanner(new File(url.toURI()),"UTF8").useDelimiter("\\Z").next();
}
}
Quick way in JSE 7
public class FooTest {
@Test public void readXMLToString() throws Exception {
java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
String xml = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
}
Quick way since Java 9
new String(getClass().getClassLoader().getResourceAsStream(resourceName).readAllBytes());
Neither intended for enormous files though.
Here is a simple approach:
my_string = 'abcdefg'
print(text.find('def'))
Output:
3
I the substring is not there, you will get -1. For example:
my_string = 'abcdefg'
print(text.find('xyz'))
Output:
-1
Sometimes, you might want to throw exception if substring is not there:
my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present
Output:
Traceback (most recent call last):
File "test.py", line 6, in print(text.index('xyz'))
ValueError: substring not found
I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().
This is what worked for me:
To add safe environment variables, in command line, type:
export MY_SUDO_PASS="user_password_here"
To test if it's working type:
echo $MY_SUDO_PASS
> user_password_here
To run it at system startup add it to the end of this file:
nano ~/.bashrc
#.bashrc
...
existing_content:
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
...
export MY_SUDO_PASS="user_password_here"
You can add all your environment variables passwords, usernames, host, etc here later.
If your variables are ready you can run:
To update:
echo $MY_SUDO_PASS | sudo -S apt-get update
Or to install Midnight Commander
echo $MY_SUDO_PASS | sudo -S apt-get install mc
To start Midnight Commander with sudo
echo $MY_SUDO_PASS | sudo -S mc
Or from python shell (or Django/Celery), to change directory ownership recursively:
python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)
Hope it helps.
first in your ajax call include success & error function and then check if it gives you error or what?
your code should be like this
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
One way:
def change(f):
if f is None:
return unicode(f.strip())
else:
return ''
row = [change(x) for x in row]
Although then you have:
row = map(change, row)
Or you can use a lambda inline.
Here is the simplest way of achieving Light and Dark Theme for Toolbar.You have to change the value of app:theme
of the Toolbar tag
app:theme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat"
This is an adaptable version of the amazing solution provided by @Gildas.Tambo elsewhere in this page. Simply change the values of the variables at the top to change the size of the "X".
Credit for the solution itself goes to Gildas. All I've done is given it adaptable math.
:root {
/* Width and height of the box containing the "X" */
--BUTTON_W: 40px;
/* This is the length of either of the 2 lines which form the "X", as a
percentage of the width of the button. */
--CLOSE_X_W: 95%;
/* Thickness of the lines of the "X" */
--CLOSE_X_THICKNESS: 4px;
}
body{
background:blue;
}
div{
width: var(--BUTTON_W);
height: var(--BUTTON_W);
background-color:red;
position: relative;
border-radius: 6px;
box-shadow: 2px 2px 4px 0 white;
}
/* The "X" in the button. "before" and "after" each represent one of the two lines of the "X" */
div:before,div:after{
content: '';
position: absolute;
width: var(--CLOSE_X_W);
height: var(--CLOSE_X_THICKNESS);
background-color:white;
border-radius: 2px;
top: calc(50% - var(--CLOSE_X_THICKNESS) / 2);
box-shadow: 0 0 2px 0 #ccc;
}
/* One line of the "X" */
div:before{
-webkit-transform:rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
left: calc((100% - var(--CLOSE_X_W)) / 2);
}
/* The other line of the "X" */
div:after{
-webkit-transform:rotate(-45deg);
-moz-transform: rotate(-45deg);
transform: rotate(-45deg);
right: calc((100% - var(--CLOSE_X_W)) / 2);
}
_x000D_
<div></div>
_x000D_
use google guava !
Iterable<String> fieldsIterable = ...
List<String> fields = Lists.newArrayList(fieldsIterable);
++
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
I was needing to print DEBUG info in some logs and was unable to use pprint because it would break it. Instead I did this and got virtually the same thing.
DO = DemoObject()
itemDir = DO.__dict__
for i in itemDir:
print '{0} : {1}'.format(i, itemDir[i])
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
There is a high level library dateparser
that can determine the past date given natural language, and return the corresponding Python datetime
object
from dateparser import parse
parse('4 months ago')
It means that the query you wrote returns more than one element(result) while your code expects a single result.
Try
safeRunCommand() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$1'"
exit $ERROR_CODE
fi
}
#!/usr/bin/env python
#-*- coding: utf-8 -*-
u = u'moçambique'
print u.encode("utf-8")
print u
chmod +x test.py
./test.py
moçambique
moçambique
./test.py > output.txt
Traceback (most recent call last):
File "./test.py", line 5, in <module>
print u
UnicodeEncodeError: 'ascii' codec can't encode character
u'\xe7' in position 2: ordinal not in range(128)
on shell works , sending to sdtout not , so that is one workaround, to write to stdout .
I made other approach, which is not run if sys.stdout.encoding is not define, or in others words , need export PYTHONIOENCODING=UTF-8 first to write to stdout.
import sys
if (sys.stdout.encoding is None):
print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout."
exit(1)
so, using same example:
export PYTHONIOENCODING=UTF-8
./test.py > output.txt
will work
@Baba's answer is great. But you don't need to use explode
because fputcsv
takes an array as a parameter
For instance, if you have a three columns, four lines document, here's a more straight version:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$user_CSV[0] = array('first_name', 'last_name', 'age');
// very simple to increment with i++ if looping through a database result
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);
$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
// though CSV stands for "comma separated value"
// in many countries (including France) separator is ";"
fputcsv($fp, $line, ',');
}
fclose($fp);
Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.
Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.
When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.
Hope that was clear!
From Oracle Wiki, error 02287 is
An ORA-02287 occurs when you use a sequence where it is not allowed.
Of the places where sequences can't be used, you seem to be trying:
In a sub-query
So it seems you can't do multiples in the same statement.
The solution they offer is:
If you want the sequence value to be inserted into the column for every row created, then create a before insert trigger and fetch the sequence value in the trigger and assign it to the column
Adapt this example to your code
HTML
<div class="img-holder">
<img src="images/img-1.png" alt="image description"/>
<a class="link" href=""></a>
</div>
CSS
.img-holder {position: relative;}
.img-holder .link {
position: absolute;
bottom: 10px; /*your button position*/
right: 10px; /*your button position*/
}
It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.
MyClass myClass = new MyClass();
once you've added that line you can then call your method
myClass.myMethod();
Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.
Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.
UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE
append
appends a single element. extend
appends a list of elements.
Note that if you pass a list to append, it still adds one element:
>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]
after hardware check on the server and it was found out that memory had gone bad, replaced the memory and the server is now fully accessible.
I use this script to delete last 10 commands in history:
pos=$HISTCMD; start=$(( $pos-11 )); end=$(( $pos-1 )); for i in $(eval echo "{${start}..${end}}"); do history -d $start; done
It uses $HISTCMD
environment var to get the history index and uses that to delete last 10 entries in history
.
$IFS
comment hacksThis hack uses parameter expansion on $IFS
, which is used to separate words in commands:
$ echo foo${IFS}bar
foo bar
Similarly:
$ echo foo${IFS#comment}bar
foo bar
Using this, you can put a comment on a command line with contination:
$ echo foo${IFS# Comment here} \
> bar
foo bar
but the comment will need to be before the \
continuation.
Note that parameter expansion is performed inside the comment:
$ ls file
ls: cannot access 'file': No such file or directory
$ echo foo${IFS# This command will create file: $(touch file)}bar
foo bar
$ ls file
file
Rare exception
The only rare case this fails is if $IFS
previously started with the exact text which is removed via the expansion (ie, after the #
character):
$ IFS=x
$ echo foo${IFS#y}bar
foo bar
$ echo foo${IFS#x}bar
foobar
Note the final foobar
has no space, illustrating the issue.
Since $IFS
contains only whitespace by default, it's extremely unlikely you'll run into this problem.
Credit to @pjh's comment which sparked off this answer.
To complete,
In a shell (bash) script, you can use \r
to send cursor, in front on line and, of course \n
to put cursor on a new line.
For example, try :
echo -en "AA--AA" ; echo -en "BB" ; echo -en "\rBB"
AA--AA
AA--AABB
BB--AABB
But don't forget to use -en
as parameters.